从右到左的横向菜单
对于阿拉伯语或希伯来语界面,这一行必须从右边缘开始、向左延伸。一个布尔属性就能翻转滚动容器;留给你的唯一真正工作,就是决定当“前进”指向左边时箭头该如何理解。
RTL
拨动开关——这一行从相反边缘重新开始,箭头互换角色。
工作原理
RTL={true} 让滚动容器进入从右到左模式:第一个项目位于右边缘,滚动向左前进。所有逻辑依然保持逻辑——useIsVisible(’first’) 仍指数据中的第一个项目,scrollNext() 仍朝最后一个移动——翻转的只是屏幕上的方向。
箭头交换插槽,不交换逻辑
LeftArrow 属性总是渲染在屏幕左侧。在 RTL 下,那一侧正是“前进”所在之处,所以 story 给插槽喂入交换过的元素:LeftArrow={RTL ? <RightArrow /> : <LeftArrow />}。组件本身保持自己的逻辑——接到 scrollPrev 的那个仍通过 useIsVisible(’first’) 禁用——改变的只是它们的屏幕位置与标签。
注意
- 该 story 传入
noPolyfill={true},因此程序化滚动使用浏览器原生的平滑滚动,而非内置的补丁。 scrollPrev(’smooth’, ’end’)与scrollNext(’smooth’, ’start’)传入显式对齐——第二个参数是与scrollToItem相同的start/center/end集合。- 该 story 通过复选框实时切换
RTL——这个属性只是 state,菜单没有任何东西是在构建时配置的。
完整源码
完整且可直接复制粘贴——这正是背后这份文件的 可在 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 RTL() {
const [RTL, setRTL] = React.useState(true);
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 (
<>
<NoScrollbar>
<ScrollMenu
LeftArrow={RTL ? <RightArrow RTL={RTL} /> : <LeftArrow RTL={RTL} />}
RightArrow={RTL ? <LeftArrow RTL={RTL} /> : <RightArrow RTL={RTL} />}
onWheel={onWheel}
RTL={RTL}
noPolyfill={true}
>
{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>
<Checkbox label="RTL" value={RTL} onClick={setRTL} />
</>
);
}
export default RTL;
function LeftArrow({ RTL }: { RTL: boolean }) {
const visibility = React.useContext<publicApiType>(VisibilityContext);
const isFirstItemVisible = visibility.useIsVisible('first', true);
return (
<Arrow
disabled={isFirstItemVisible}
onClick={() => visibility.scrollPrev('smooth', 'end')}
testId={RTL ? 'right-arrow' : 'left-arrow'}
>
{RTL ? 'Right' : 'Left'}
</Arrow>
);
}
function RightArrow({ RTL }: { RTL: boolean }) {
const visibility = React.useContext<publicApiType>(VisibilityContext);
const isLastItemVisible = visibility.useIsVisible('last', false);
return (
<Arrow
disabled={isLastItemVisible}
onClick={() => visibility.scrollNext('smooth', 'start')}
testId={RTL ? 'left-arrow' : 'right-arrow'}
>
{RTL ? 'Left' : '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',
}));
const Checkbox = ({
onClick,
value,
label,
}: {
value: boolean;
label: string;
onClick: (val: boolean) => void;
}) => {
return (
<CheckboxWrapper>
<BigCheckbox
type="checkbox"
id={label}
onChange={(ev: React.ChangeEvent<HTMLInputElement>) =>
onClick(ev?.target?.checked)
}
checked={value}
defaultChecked={value}
/>
<label htmlFor={label}>{label}</label>
</CheckboxWrapper>
);
};
const CheckboxWrapper = styled('div')({
display: 'flex',
alignItems: 'center',
margin: '16px',
'& *:first-child': {
marginRight: '4px',
},
});
const BigCheckbox = styled('input')({
height: '24px',
width: '24px',
cursor: 'pointer',
});
function Card({
onClick,
selected,
title,
itemId,
}: {
onClick: (visibility: 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 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',
},
});
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 {
const isThouchpad = Math.abs(ev.deltaX) !== 0 || Math.abs(ev.deltaY) < 15;
if (isThouchpad) {
ev.stopPropagation();
return;
}
if (ev.deltaY < 0) {
apiObj.scrollPrev('smooth', 'end');
} else {
apiObj.scrollNext('smooth', 'start');
}
}