invokingTrigger method

StreamAutocompleteQuery? invokingTrigger(
  1. Message message,
  2. TextEditingValue textEditingValue
)

Checks if the user is invoking the recognising trigger and returns the autocomplete query if so.

Implementation

StreamAutocompleteQuery? invokingTrigger(
  Message message,
  TextEditingValue textEditingValue,
) {
  final text = textEditingValue.text;
  final cursorPosition = textEditingValue.selection.baseOffset;

  // Find the first [trigger] location before the input cursor.
  final firstTriggerIndexBeforeCursor =
      text.substring(0, cursorPosition).lastIndexOf(trigger);

  // If the [trigger] is not found before the cursor, then it's not a trigger.
  if (firstTriggerIndexBeforeCursor == -1) return null;

  // If the [trigger] is found before the cursor, but the [trigger] is only
  // recognised at the start of the input, then it's not a trigger.
  if (triggerOnlyAtStart && firstTriggerIndexBeforeCursor != 0) {
    return null;
  }

  // Only show typing suggestions after a space, or at the start of the input
  // valid examples: "@user", "Hello @user"
  // invalid examples: "Hello@user"
  final textBeforeTrigger = text.substring(0, firstTriggerIndexBeforeCursor);
  if (triggerOnlyAfterSpace &&
      textBeforeTrigger.isNotEmpty &&
      !textBeforeTrigger.endsWith(' ')) {
    return null;
  }

  // The suggestion range. Protect against invalid ranges.
  final suggestionStart = firstTriggerIndexBeforeCursor + trigger.length;
  final suggestionEnd = cursorPosition;
  if (suggestionStart > suggestionEnd) return null;

  // Fetch the suggestion text. The suggestions can't have spaces.
  // valid example: "@luke_skywa..."
  // invalid example: "@luke skywa..."
  final suggestionText = text.substring(suggestionStart, suggestionEnd);
  if (suggestionText.contains(' ')) return null;

  // A minimum number of characters can be provided to only show
  // suggestions after the customer has input enough characters.
  if (suggestionText.length < minimumRequiredCharacters) return null;

  return StreamAutocompleteQuery(
    query: suggestionText,
    selection: TextSelection(
      baseOffset: suggestionStart,
      extentOffset: suggestionEnd,
    ),
  );
}