File size: 16,388 Bytes
064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 | import {
useCallback,
useEffect,
useMemo,
useReducer,
useRef,
useState,
} from 'react'
import { isDeepStrictEqual } from 'util'
import OptionMap from './option-map.js'
import type { OptionWithDescription } from './select.js'
type State<T> = {
/**
* Map where key is option's value and value is option's index.
*/
optionMap: OptionMap<T>
/**
* Number of visible options.
*/
visibleOptionCount: number
/**
* Value of the currently focused option.
*/
focusedValue: T | undefined
/**
* Index of the first visible option.
*/
visibleFromIndex: number
/**
* Index of the last visible option.
*/
visibleToIndex: number
}
type Action<T> =
| FocusNextOptionAction
| FocusPreviousOptionAction
| FocusNextPageAction
| FocusPreviousPageAction
| SetFocusAction<T>
| ResetAction<T>
type SetFocusAction<T> = {
type: 'set-focus'
value: T
}
type FocusNextOptionAction = {
type: 'focus-next-option'
}
type FocusPreviousOptionAction = {
type: 'focus-previous-option'
}
type FocusNextPageAction = {
type: 'focus-next-page'
}
type FocusPreviousPageAction = {
type: 'focus-previous-page'
}
type ResetAction<T> = {
type: 'reset'
state: State<T>
}
const reducer = <T>(state: State<T>, action: Action<T>): State<T> => {
switch (action.type) {
case 'focus-next-option': {
if (state.focusedValue === undefined) {
return state
}
const item = state.optionMap.get(state.focusedValue)
if (!item) {
return state
}
// Wrap to first item if at the end
const next = item.next || state.optionMap.first
if (!next) {
return state
}
// When wrapping to first, reset viewport to start
if (!item.next && next === state.optionMap.first) {
return {
...state,
focusedValue: next.value,
visibleFromIndex: 0,
visibleToIndex: state.visibleOptionCount,
}
}
const needsToScroll = next.index >= state.visibleToIndex
if (!needsToScroll) {
return {
...state,
focusedValue: next.value,
}
}
const nextVisibleToIndex = Math.min(
state.optionMap.size,
state.visibleToIndex + 1,
)
const nextVisibleFromIndex = nextVisibleToIndex - state.visibleOptionCount
return {
...state,
focusedValue: next.value,
visibleFromIndex: nextVisibleFromIndex,
visibleToIndex: nextVisibleToIndex,
}
}
case 'focus-previous-option': {
if (state.focusedValue === undefined) {
return state
}
const item = state.optionMap.get(state.focusedValue)
if (!item) {
return state
}
// Wrap to last item if at the beginning
const previous = item.previous || state.optionMap.last
if (!previous) {
return state
}
// When wrapping to last, reset viewport to end
if (!item.previous && previous === state.optionMap.last) {
const nextVisibleToIndex = state.optionMap.size
const nextVisibleFromIndex = Math.max(
0,
nextVisibleToIndex - state.visibleOptionCount,
)
return {
...state,
focusedValue: previous.value,
visibleFromIndex: nextVisibleFromIndex,
visibleToIndex: nextVisibleToIndex,
}
}
const needsToScroll = previous.index <= state.visibleFromIndex
if (!needsToScroll) {
return {
...state,
focusedValue: previous.value,
}
}
const nextVisibleFromIndex = Math.max(0, state.visibleFromIndex - 1)
const nextVisibleToIndex = nextVisibleFromIndex + state.visibleOptionCount
return {
...state,
focusedValue: previous.value,
visibleFromIndex: nextVisibleFromIndex,
visibleToIndex: nextVisibleToIndex,
}
}
case 'focus-next-page': {
if (state.focusedValue === undefined) {
return state
}
const item = state.optionMap.get(state.focusedValue)
if (!item) {
return state
}
// Move by a full page (visibleOptionCount items)
const targetIndex = Math.min(
state.optionMap.size - 1,
item.index + state.visibleOptionCount,
)
// Find the item at the target index
let targetItem = state.optionMap.first
while (targetItem && targetItem.index < targetIndex) {
if (targetItem.next) {
targetItem = targetItem.next
} else {
break
}
}
if (!targetItem) {
return state
}
// Update the visible range to include the new focused item
const nextVisibleToIndex = Math.min(
state.optionMap.size,
targetItem.index + 1,
)
const nextVisibleFromIndex = Math.max(
0,
nextVisibleToIndex - state.visibleOptionCount,
)
return {
...state,
focusedValue: targetItem.value,
visibleFromIndex: nextVisibleFromIndex,
visibleToIndex: nextVisibleToIndex,
}
}
case 'focus-previous-page': {
if (state.focusedValue === undefined) {
return state
}
const item = state.optionMap.get(state.focusedValue)
if (!item) {
return state
}
// Move by a full page (visibleOptionCount items)
const targetIndex = Math.max(0, item.index - state.visibleOptionCount)
// Find the item at the target index
let targetItem = state.optionMap.first
while (targetItem && targetItem.index < targetIndex) {
if (targetItem.next) {
targetItem = targetItem.next
} else {
break
}
}
if (!targetItem) {
return state
}
// Update the visible range to include the new focused item
const nextVisibleFromIndex = Math.max(0, targetItem.index)
const nextVisibleToIndex = Math.min(
state.optionMap.size,
nextVisibleFromIndex + state.visibleOptionCount,
)
return {
...state,
focusedValue: targetItem.value,
visibleFromIndex: nextVisibleFromIndex,
visibleToIndex: nextVisibleToIndex,
}
}
case 'reset': {
return action.state
}
case 'set-focus': {
// Early return if already focused on this value
if (state.focusedValue === action.value) {
return state
}
const item = state.optionMap.get(action.value)
if (!item) {
return state
}
// Check if the item is already in view
if (
item.index >= state.visibleFromIndex &&
item.index < state.visibleToIndex
) {
// Already visible, just update focus
return {
...state,
focusedValue: action.value,
}
}
// Need to scroll to make the item visible
// Scroll as little as possible - put item at edge of viewport
let nextVisibleFromIndex: number
let nextVisibleToIndex: number
if (item.index < state.visibleFromIndex) {
// Item is above viewport - scroll up to put it at the top
nextVisibleFromIndex = item.index
nextVisibleToIndex = Math.min(
state.optionMap.size,
nextVisibleFromIndex + state.visibleOptionCount,
)
} else {
// Item is below viewport - scroll down to put it at the bottom
nextVisibleToIndex = Math.min(state.optionMap.size, item.index + 1)
nextVisibleFromIndex = Math.max(
0,
nextVisibleToIndex - state.visibleOptionCount,
)
}
return {
...state,
focusedValue: action.value,
visibleFromIndex: nextVisibleFromIndex,
visibleToIndex: nextVisibleToIndex,
}
}
}
}
export type UseSelectNavigationProps<T> = {
/**
* Number of items to display.
*
* @default 5
*/
visibleOptionCount?: number
/**
* Options.
*/
options: OptionWithDescription<T>[]
/**
* Initially focused option's value.
*/
initialFocusValue?: T
/**
* Callback for focusing an option.
*/
onFocus?: (value: T) => void
/**
* Value to focus
*/
focusValue?: T
}
export type SelectNavigation<T> = {
/**
* Value of the currently focused option.
*/
focusedValue: T | undefined
/**
* 1-based index of the focused option in the full list.
* Returns 0 if no option is focused.
*/
focusedIndex: number
/**
* Index of the first visible option.
*/
visibleFromIndex: number
/**
* Index of the last visible option.
*/
visibleToIndex: number
/**
* All options.
*/
options: OptionWithDescription<T>[]
/**
* Visible options.
*/
visibleOptions: Array<OptionWithDescription<T> & { index: number }>
/**
* Whether the focused option is an input type.
*/
isInInput: boolean
/**
* Focus next option and scroll the list down, if needed.
*/
focusNextOption: () => void
/**
* Focus previous option and scroll the list up, if needed.
*/
focusPreviousOption: () => void
/**
* Focus next page and scroll the list down by a page.
*/
focusNextPage: () => void
/**
* Focus previous page and scroll the list up by a page.
*/
focusPreviousPage: () => void
/**
* Focus a specific option by value.
*/
focusOption: (value: T | undefined) => void
}
const createDefaultState = <T>({
visibleOptionCount: customVisibleOptionCount,
options,
initialFocusValue,
currentViewport,
}: Pick<UseSelectNavigationProps<T>, 'visibleOptionCount' | 'options'> & {
initialFocusValue?: T
currentViewport?: { visibleFromIndex: number; visibleToIndex: number }
}): State<T> => {
const visibleOptionCount =
typeof customVisibleOptionCount === 'number'
? Math.min(customVisibleOptionCount, options.length)
: options.length
const optionMap = new OptionMap<T>(options)
const focusedItem =
initialFocusValue !== undefined && optionMap.get(initialFocusValue)
const focusedValue = focusedItem ? initialFocusValue : optionMap.first?.value
let visibleFromIndex = 0
let visibleToIndex = visibleOptionCount
// When there's a valid focused item, adjust viewport to show it
if (focusedItem) {
const focusedIndex = focusedItem.index
if (currentViewport) {
// If focused item is already in the current viewport range, try to preserve it
if (
focusedIndex >= currentViewport.visibleFromIndex &&
focusedIndex < currentViewport.visibleToIndex
) {
// Keep the same viewport if it's valid
visibleFromIndex = currentViewport.visibleFromIndex
visibleToIndex = Math.min(
optionMap.size,
currentViewport.visibleToIndex,
)
} else {
// Need to adjust viewport to show focused item
// Use minimal scrolling - put item at edge of viewport
if (focusedIndex < currentViewport.visibleFromIndex) {
// Item is above current viewport - scroll up to put it at the top
visibleFromIndex = focusedIndex
visibleToIndex = Math.min(
optionMap.size,
visibleFromIndex + visibleOptionCount,
)
} else {
// Item is below current viewport - scroll down to put it at the bottom
visibleToIndex = Math.min(optionMap.size, focusedIndex + 1)
visibleFromIndex = Math.max(0, visibleToIndex - visibleOptionCount)
}
}
} else if (focusedIndex >= visibleOptionCount) {
// No current viewport but focused item is outside default viewport
// Scroll to show the focused item at the bottom of the viewport
visibleToIndex = Math.min(optionMap.size, focusedIndex + 1)
visibleFromIndex = Math.max(0, visibleToIndex - visibleOptionCount)
}
// Ensure viewport bounds are valid
visibleFromIndex = Math.max(
0,
Math.min(visibleFromIndex, optionMap.size - 1),
)
visibleToIndex = Math.min(
optionMap.size,
Math.max(visibleOptionCount, visibleToIndex),
)
}
return {
optionMap,
visibleOptionCount,
focusedValue,
visibleFromIndex,
visibleToIndex,
}
}
export function useSelectNavigation<T>({
visibleOptionCount = 5,
options,
initialFocusValue,
onFocus,
focusValue,
}: UseSelectNavigationProps<T>): SelectNavigation<T> {
const [state, dispatch] = useReducer(
reducer<T>,
{
visibleOptionCount,
options,
initialFocusValue: focusValue || initialFocusValue,
} as Parameters<typeof createDefaultState<T>>[0],
createDefaultState<T>,
)
// Store onFocus in a ref to avoid re-running useEffect when callback changes
const onFocusRef = useRef(onFocus)
onFocusRef.current = onFocus
const [lastOptions, setLastOptions] = useState(options)
if (options !== lastOptions && !isDeepStrictEqual(options, lastOptions)) {
dispatch({
type: 'reset',
state: createDefaultState({
visibleOptionCount,
options,
initialFocusValue:
focusValue ?? state.focusedValue ?? initialFocusValue,
currentViewport: {
visibleFromIndex: state.visibleFromIndex,
visibleToIndex: state.visibleToIndex,
},
}),
})
setLastOptions(options)
}
const focusNextOption = useCallback(() => {
dispatch({
type: 'focus-next-option',
})
}, [])
const focusPreviousOption = useCallback(() => {
dispatch({
type: 'focus-previous-option',
})
}, [])
const focusNextPage = useCallback(() => {
dispatch({
type: 'focus-next-page',
})
}, [])
const focusPreviousPage = useCallback(() => {
dispatch({
type: 'focus-previous-page',
})
}, [])
const focusOption = useCallback((value: T | undefined) => {
if (value !== undefined) {
dispatch({
type: 'set-focus',
value,
})
}
}, [])
const visibleOptions = useMemo(() => {
return options
.map((option, index) => ({
...option,
index,
}))
.slice(state.visibleFromIndex, state.visibleToIndex)
}, [options, state.visibleFromIndex, state.visibleToIndex])
// Validate that focusedValue exists in current options.
// This handles the case where options change during render but the reset
// action hasn't been processed yet - without this, the cursor would disappear
// because focusedValue points to an option that no longer exists.
const validatedFocusedValue = useMemo(() => {
if (state.focusedValue === undefined) {
return undefined
}
const exists = options.some(opt => opt.value === state.focusedValue)
if (exists) {
return state.focusedValue
}
// Fall back to first option if focused value doesn't exist
return options[0]?.value
}, [state.focusedValue, options])
const isInInput = useMemo(() => {
const focusedOption = options.find(
opt => opt.value === validatedFocusedValue,
)
return focusedOption?.type === 'input'
}, [validatedFocusedValue, options])
// Call onFocus with the validated value (what's actually displayed),
// not the internal state value which may be stale if options changed.
// Use ref to avoid re-running when callback reference changes.
useEffect(() => {
if (validatedFocusedValue !== undefined) {
onFocusRef.current?.(validatedFocusedValue)
}
}, [validatedFocusedValue])
// Allow parent to programmatically set focus via focusValue prop
useEffect(() => {
if (focusValue !== undefined) {
dispatch({
type: 'set-focus',
value: focusValue,
})
}
}, [focusValue])
// Compute 1-based focused index for scroll position display
const focusedIndex = useMemo(() => {
if (validatedFocusedValue === undefined) {
return 0
}
const index = options.findIndex(opt => opt.value === validatedFocusedValue)
return index >= 0 ? index + 1 : 0
}, [validatedFocusedValue, options])
return {
focusedValue: validatedFocusedValue,
focusedIndex,
visibleFromIndex: state.visibleFromIndex,
visibleToIndex: state.visibleToIndex,
visibleOptions,
isInInput: isInInput ?? false,
focusNextOption,
focusPreviousOption,
focusNextPage,
focusPreviousPage,
focusOption,
options,
}
}
|