apply method
Applies heuristic rule to an insert operation on a document
and returns
resulting Delta.
Implementation
@override
Delta? apply(Delta document, int index, String text) {
// This rule applies to a space inserted after a link, so we can ignore
// everything else.
if (text != ' ') return null;
final iter = DeltaIterator(document);
final previous = iter.skip(index);
// No previous operation means no link.
if (previous == null) return null;
// Split text of previous operation in lines and words and take last word to test.
final candidate = previous.data.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.
}
}