handleKeyEvent method

bool handleKeyEvent(
  1. KeyEvent event
)

Handles key events to update the text area value and cursor position.

Implementation

bool handleKeyEvent(KeyEvent event) {
  // Determine the mapped action
  TextFieldAction? action;
  final shortcuts = customShortcuts ?? defaultShortcuts;

  for (final entry in shortcuts.entries) {
    if (entry.key.matches(event)) {
      action = entry.value;
      break;
    }
  }

  if (action != null) {
    _executeAction(action);
    return true;
  }

  // Default character inserts
  final hasControlOrAltOrMeta =
      event.modifiers.contains(ev.Modifier.control) ||
      event.modifiers.contains(ev.Modifier.alt) ||
      event.modifiers.contains(ev.Modifier.meta);

  if (event.type == KeyType.enter ||
      (event.type == KeyType.character &&
          (event.key == '\n' || event.key == '\r' || event.key == '\r\n'))) {
    if (multiline) {
      controller.saveStateToHistory();
      final lines = List<String>.from(controller.value.lines);
      final lineIdx = cursorLine;
      final colIdx = cursorColumn;
      final current = lines[lineIdx].characters;
      final prefix = current.take(colIdx).toString();
      final suffix = current.skip(colIdx).toString();
      lines[lineIdx] = prefix;
      lines.insert(lineIdx + 1, suffix);

      final nextLine = lineIdx + 1;
      final nextCol = 0;
      final nextText = lines.join('\n');
      final nextOffset = _getOffsetFromLineColumn(
        nextText,
        nextLine,
        nextCol,
      );

      controller.value = TextEditingValue(
        text: nextText,
        selection: TextSelection(
          baseOffset: nextOffset,
          extentOffset: nextOffset,
          cursorLine: nextLine,
          cursorColumn: nextCol,
        ),
      );
      return true;
    }
    return false;
  }

  if (event.type == KeyType.character && !hasControlOrAltOrMeta) {
    if (event.key == '\t') return false;
    controller.saveStateToHistory();
    final lines = List<String>.from(controller.value.lines);
    final lineIdx = cursorLine;
    final colIdx = cursorColumn;
    final current = lines[lineIdx].characters;
    lines[lineIdx] =
        current.take(colIdx).toString() +
        event.key +
        current.skip(colIdx).toString();

    final nextLine = lineIdx;
    final nextCol = colIdx + event.key.characters.length;
    final nextText = lines.join('\n');
    final nextOffset = _getOffsetFromLineColumn(nextText, nextLine, nextCol);

    controller.value = TextEditingValue(
      text: nextText,
      selection: TextSelection(
        baseOffset: nextOffset,
        extentOffset: nextOffset,
        cursorLine: nextLine,
        cursorColumn: nextCol,
      ),
    );
    return true;
  }

  return false;
}