keyMatches function

bool keyMatches(
  1. Key key,
  2. List<KeyBinding> bindings
)

Checks if a key message matches any of the given bindings.

This is the primary way to check if user input matches a key binding.

Example

final keyMap = MyKeyMap();

(Model, Cmd?) update(Msg msg) {
  return switch (msg) {
    KeyMsg(:final key) when keyMatches(key, keyMap.up) =>
      (moveUp(), null),
    KeyMsg(:final key) when keyMatches(key, keyMap.down) =>
      (moveDown(), null),
    KeyMsg(:final key) when keyMatches(key, keyMap.quit) =>
      (this, Cmd.quit()),
    _ => (this, null),
  };
}

Implementation

bool keyMatches(Key key, List<KeyBinding> bindings) {
  final keyStr = key.toString();
  // Extract the key name from Key(...) format
  final keyName = keyStr.startsWith('Key(') && keyStr.endsWith(')')
      ? keyStr.substring(4, keyStr.length - 1)
      : keyStr;

  for (final binding in bindings) {
    if (!binding.enabled) continue;
    for (final k in binding.keys) {
      // For character keys (runes), match case-sensitively
      // For other keys, match case-insensitively
      final matches = key.type == KeyType.runes
          ? (keyName == k || keyStr == k)
          : (keyName.toLowerCase() == k.toLowerCase() || keyStr == k);
      if (matches) return true;
    }
  }
  return false;
}