activateOnKeyPress method

void activateOnKeyPress(
  1. ActiveItemModel activeModel,
  2. int charCode,
  3. SelectionOptions? options,
  4. ItemRenderer<T>? itemRenderer,
  5. SelectionModel? selection,
)

Activates an item in the ActiveItemModel based on the key passed in. If the current item already matches, it will select the next item that matches.

Implementation

void activateOnKeyPress(
    ActiveItemModel activeModel,
    int charCode,
    SelectionOptions? options,
    ItemRenderer<T>? itemRenderer,
    SelectionModel? selection) {
  // Guard against being called when not all data is initialized.
  if (itemRenderer == null || options == null) return;

  String key = _charCodeToString(charCode);
  var optionsList = options.optionsList;
  // Cached map of options to search strings.
  var searchMap = <dynamic, String>{};

  var startsWith = (option, String keys) {
    if (option == null) return false;
    var searchString = searchMap[option];
    if (searchString == null) {
      searchString = itemRenderer(option)!.toLowerCase();
      searchMap[option] = searchString;
    }
    return searchString.startsWith(keys);
  };
  var maybeSelectOption = (option, String keys) {
    if (Selectable.isSelectableIn(options, option) &&
        startsWith(option, keys)) {
      activeModel.activate(option);
      selection?.select(option);
      _enteredKeys = keys;
      return true;
    }
    return false;
  };

  // If there's previously entered keys, try to match multiple keys.
  if (_enteredKeys.isNotEmpty) {
    var keys = _enteredKeys + key;
    for (var option in optionsList) {
      if (maybeSelectOption(option, keys)) return;
    }
  }

  // If there is already an active item then check if the key code matches
  // it and also matches the next item then select the next item.
  if (startsWith(activeModel.activeItem, key)) {
    if (maybeSelectOption(activeModel.peekNext, key)) return;
  }

  for (var option in optionsList) {
    if (maybeSelectOption(option, key)) return;
  }

  resetEnteredKeys();
}