Skip to content

Commit

Permalink
test: add keyboard operation test case
Browse files Browse the repository at this point in the history
  • Loading branch information
小豪 committed Nov 24, 2024
1 parent 78bb227 commit 2f7630e
Show file tree
Hide file tree
Showing 5 changed files with 116 additions and 80 deletions.
3 changes: 3 additions & 0 deletions docs/demo/basic.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,16 @@ export default function App() {
<div className="wrapper">
<Segmented
options={['iOS', 'Android', 'Web']}
defaultValue="Android"
name="segmented1"
onChange={(value) => console.log(value, typeof value)}
/>
</div>
<div className="wrapper">
<Segmented
vertical
options={['iOS', 'Android', 'Web']}
name="segmented2"
onChange={(value) => console.log(value, typeof value)}
/>
</div>
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"@rc-component/father-plugin": "^1.0.1",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^14.2.1",
"@testing-library/user-event": "^14.5.2",
"@types/classnames": "^2.2.9",
"@types/jest": "^29.2.4",
"@types/react": "^18.3.11",
Expand Down
34 changes: 9 additions & 25 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import classNames from 'classnames';
import useMergedState from 'rc-util/lib/hooks/useMergedState';
import KeyCode from 'rc-util/lib/KeyCode';
import omit from 'rc-util/lib/omit';
import { composeRef } from 'rc-util/lib/ref';
import * as React from 'react';
Expand Down Expand Up @@ -202,37 +201,22 @@ const Segmented = React.forwardRef<HTMLDivElement, SegmentedProps>(
};

// ======================= Keyboard ========================
const getNextIndex = (current: number, offset: number) => {
if (disabled) {
return current;
}

const total = segmentedOptions.length;
const nextIndex = (current + offset + total) % total;

if (segmentedOptions[nextIndex]?.disabled) {
return getNextIndex(nextIndex, offset);
}
return nextIndex;
};

const handleKeyDown = (event: React.KeyboardEvent) => {
let offset = 0;
const total = segmentedOptions.length;
let nextIndex = currentIndex;

switch (event.which) {
case KeyCode.LEFT:
case KeyCode.UP:
offset = -1;
switch (event.key) {
case 'ArrowLeft':
case 'ArrowUp':
nextIndex = currentIndex === 0 ? total - 1 : currentIndex - 1;
break;
case KeyCode.RIGHT:
case KeyCode.DOWN:
offset = 1;
case 'ArrowRight':
case 'ArrowDown':
nextIndex = currentIndex === total - 1 ? 0 : currentIndex + 1;
break;
}

const nextIndex = getNextIndex(currentIndex, offset);
const nextOption = segmentedOptions[nextIndex];

if (nextOption) {
setRawValue(nextOption.value);
onChange?.(nextOption.value);
Expand Down
Loading

0 comments on commit 2f7630e

Please sign in to comment.