apply method

  1. @override
Delta? apply(
  1. Delta document,
  2. int index,
  3. Object data
)
override

Applies heuristic rule to an insert operation on a document and returns resulting Delta.

Implementation

@override
Delta? apply(Delta document, int index, Object data) {
  if (data is! String) return null;

  // This rule applies to a space inserted after a link, so we can ignore
  // everything else.
  final text = data;
  if (text != ' ') return null;

  final iter = DeltaIterator(document);
  final previous = iter.skip(index);
  // No previous operation means nothing to analyze.
  if (previous == null || previous.data is! String) return null;
  final previousText = previous.data as String;

  // Split text of previous operation in lines and words and take the last
  // word to test.
  final candidate = previousText.split('\n').last.split(' ').last;
  try {
    final link = Uri.parse(candidate);
    if (!['https', 'http'].contains(link.scheme)) {
      // TODO: might need a more robust way of validating links here.
      return null;
    }
    final attributes = previous.attributes ?? <String, dynamic>{};

    // Do nothing if already formatted as link.
    if (attributes.containsKey(NotusAttribute.link.key)) return null;

    attributes
        .addAll(NotusAttribute.link.fromString(link.toString()).toJson());
    return Delta()
      ..retain(index - candidate.length)
      ..retain(candidate.length, attributes)
      ..insert(text, previous.attributes);
  } on FormatException {
    return null; // Our candidate is not a link.
  }
}