Skip to content

Commit fbd0d56

Browse files
committed
refactor: optimize keyboard navigation logic with modular arithmetic
1 parent 28be306 commit fbd0d56

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

src/index.tsx

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -201,26 +201,28 @@ const Segmented = React.forwardRef<HTMLDivElement, SegmentedProps>(
201201
};
202202

203203
// ======================= Keyboard ========================
204-
const handleKeyDown = (event: React.KeyboardEvent) => {
204+
const onOffset = (offset: number) => {
205205
const total = segmentedOptions.length;
206-
let nextIndex = currentIndex;
206+
const nextIndex = (currentIndex + offset + total) % total;
207+
208+
const nextOption = segmentedOptions[nextIndex];
209+
if (nextOption) {
210+
setRawValue(nextOption.value);
211+
onChange?.(nextOption.value);
212+
}
213+
};
207214

215+
const handleKeyDown = (event: React.KeyboardEvent) => {
208216
switch (event.key) {
209217
case 'ArrowLeft':
210218
case 'ArrowUp':
211-
nextIndex = currentIndex === 0 ? total - 1 : currentIndex - 1;
219+
onOffset(-1);
212220
break;
213221
case 'ArrowRight':
214222
case 'ArrowDown':
215-
nextIndex = currentIndex === total - 1 ? 0 : currentIndex + 1;
223+
onOffset(1);
216224
break;
217225
}
218-
219-
const nextOption = segmentedOptions[nextIndex];
220-
if (nextOption) {
221-
setRawValue(nextOption.value);
222-
onChange?.(nextOption.value);
223-
}
224226
};
225227

226228
return (

0 commit comments

Comments
 (0)