focusNextOption method

void focusNextOption()

Focus next option and scroll down if needed. Port of focus-next-option action from use-select-navigation.ts reducer.

Implementation

void focusNextOption() {
  final current = focusedValue.value;
  if (current == null) return;

  final item = optionMap.get(current);
  if (item == null) return;

  // Wrap to first item if at the end
  final next = item.next ?? optionMap.first;
  if (next == null) return;

  // Check for onDownFromLastItem callback
  if (item.next == null && onDownFromLastItem != null) {
    onDownFromLastItem!();
    return;
  }

  // When wrapping to first, reset viewport
  if (item.next == null && next == optionMap.first) {
    focusedValue.value = next.value;
    visibleFromIndex.value = 0;
    visibleToIndex.value = math.min(visibleOptionCount, optionMap.size);
    onFocus?.call(next.value);
    return;
  }

  final needsScroll = next.index >= visibleToIndex.value;
  focusedValue.value = next.value;

  if (needsScroll) {
    final newTo = math.min(optionMap.size, visibleToIndex.value + 1);
    final newFrom = newTo - visibleOptionCount;
    visibleToIndex.value = newTo;
    visibleFromIndex.value = newFrom;
  }

  onFocus?.call(next.value);
}