update method

  1. @override
(AnticipateModel, Cmd?) update(
  1. Msg msg
)
override

Updates the component state in response to a message.

Returns the updated component (often this) and an optional command.

Implementation

@override
(AnticipateModel, Cmd?) update(Msg msg) {
  if (!_focused) return (this, null);

  if (msg is KeyMsg) {
    if (keyMatches(msg.key, [keyMap.cancel])) {
      return (blur().copyWith(value: ''), null);
    } else if (keyMatches(msg.key, [keyMap.acceptSuggestion])) {
      final result = _filteredSuggestions.isNotEmpty
          ? _filteredSuggestions[_selectedIndex]
          : (_value.isNotEmpty ? _value : defaultValue);
      return (blur().copyWith(value: result), null);
    } else if (keyMatches(msg.key, [keyMap.nextSuggestion])) {
      if (_filteredSuggestions.isNotEmpty) {
        final newIndex = (_selectedIndex + 1) % _filteredSuggestions.length;
        return (copyWith(selectedIndex: newIndex), null);
      }
    } else if (keyMatches(msg.key, [keyMap.prevSuggestion])) {
      if (_filteredSuggestions.isNotEmpty) {
        final newIndex = _selectedIndex > 0
            ? _selectedIndex - 1
            : _filteredSuggestions.length - 1;
        return (copyWith(selectedIndex: newIndex), null);
      }
    } else if (keyMatches(msg.key, [keyMap.deleteCharacterBackward])) {
      if (_value.isNotEmpty) {
        final newValue = _dropLastGrapheme(_value);
        final newModel = copyWith(value: newValue);
        return (newModel, null);
      }
    } else if (msg.key.runes.isNotEmpty) {
      // Handle character input
      final newValue = _value + String.fromCharCodes(msg.key.runes);
      final newModel = copyWith(value: newValue);
      return (newModel, null);
    }
  }

  return (this, null);
}