用滚轮滚动菜单——而不滚动页面
onWheel 处理器,以及一个防止底下页面移动的原生非被动监听器。后一半单靠 React 做不到。把指针停在这一行上转滚轮:这一行翻页,页面保持不动。移出这一行,滚轮就又滚动页面了。
把滚轮变成翻页
ScrollMenu 的 onWheel 属性会连同 API 对象与滚轮事件一起被调用。真正的鼠标滚轮以粗细步长报告仅 Y 轴的增量,所以处理器在 deltaY 为负时调用 scrollNext,否则调用 scrollPrev——每个刻度给这一行翻页。在此之前,它先检查事件是否像触控板手势:只要有任何 deltaX,或 deltaY 小于 15。
为什么锁定页面需要原生监听器
在 React 处理器里调用 preventDefault 是阻止页面的显而易见的办法——但它在静默地什么都不做,因为 React 以被动方式注册滚轮监听器,而被动监听器被禁止取消事件。所以 usePreventBodyScroll 绕过 React:在 mouseenter 时运行 document.addEventListener('wheel', preventDefault, { passive: false }),在 mouseleave 时再次移除监听器。当指针在菜单上方时,每个滚轮事件冒泡到 document,其默认动作——滚动页面——在那里被取消。一个 useEffect 清理在卸载时调用 enableScroll,因此页面绝不会被遗留在锁定状态。
触控板逃生口
双指平移也会以滚轮事件抵达,而容器会原生地从它们滚动——document 监听器会杀掉这一点。对于符合触控板启发式规则的事件,处理器调用 stopPropagation 并返回:事件永远到不了 document 监听器,原生平移得以幸存。没有可靠办法检测触控板;这条增量启发式规则是 story 的诚实猜测,且在实践中站得住脚。
注意
- 浏览器默认把 document 级别的滚轮监听器设为被动,正是为了页面不会卡顿滚动——
passive: false是让preventDefault重新合法的显式退出方式。 - 滚轮向上向前翻页、滚轮向下向后翻页——这是 story 的映射;互换
scrollNext/scrollPrev分支即可反转。 - 触摸设备从不运行这些:没有
mouseenter,而且从一开始滑动这一行就是原生滚动。 - 锁定只存在于
mouseenter与mouseleave之间,因此指针一离开轨道,页面其余部分就照常滚动。
完整源码
完整且可直接复制粘贴——这正是背后这份文件的 可在 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';
function usePreventBodyScroll() {
const preventDefault = React.useCallback((ev: Event) => {
ev?.preventDefault?.();
}, []);
const enableScroll = React.useCallback(() => {
document && document.removeEventListener('wheel', preventDefault, false);
}, [preventDefault]);
const disableScroll = React.useCallback(() => {
document &&
document.addEventListener('wheel', preventDefault, {
passive: false,
});
}, [preventDefault]);
React.useEffect(() => {
return enableScroll;
}, [enableScroll]);
return { disableScroll, enableScroll };
}
export function PreventBodyScroll() {
const { disableScroll, enableScroll } = usePreventBodyScroll();
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),
);
};
return (
<div style={{ height: '200vh' }}>
<div>
<NoScrollbar onMouseEnter={disableScroll} onMouseLeave={enableScroll}>
<ScrollMenu
LeftArrow={LeftArrow}
RightArrow={RightArrow}
onWheel={onWheel}
>
{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>
</div>
</div>
);
}
export default PreventBodyScroll;
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 = () =>
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();
}
}