focusPreviousOption method

void focusPreviousOption()

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

Implementation

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

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

  // Wrap to last item if at the beginning
  final previous = item.previous ?? optionMap.last;
  if (previous == null) return;

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

  // When wrapping to last, reset viewport to end
  if (item.previous == null && previous == optionMap.last) {
    final newTo = optionMap.size;
    final newFrom = math.max(0, newTo - visibleOptionCount);
    focusedValue.value = previous.value;
    visibleFromIndex.value = newFrom;
    visibleToIndex.value = newTo;
    onFocus?.call(previous.value);
    return;
  }

  final needsScroll = previous.index <= visibleFromIndex.value;
  focusedValue.value = previous.value;

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

  onFocus?.call(previous.value);
}