applyRule method

  1. @override
Delta? applyRule(
  1. Delta document,
  2. int index, {
  3. int? len,
  4. Object? data,
  5. Attribute? attribute,
})
override

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

Implementation

@override
Delta? applyRule(Delta document, int index, {int? len, Object? data, Attribute? attribute}) {
  if (data is! String || data.contains('\n')) {
    return null;
  }

  final itr = DeltaIterator(document);
  final prev = itr.skip(len == 0 ? index : index + 1);
  if (prev == null || prev.data is! String || (prev.data as String).contains('\n')) {
    return null;
  }

  final attributes = prev.attributes;
  final text = data;
  if (attributes == null || !attributes.containsKey(Attribute.link.key)) {
    return Delta()
      ..retain(index + (len ?? 0))
      ..insert(text, attributes);
  }

  attributes.remove(Attribute.link.key);
  final delta = Delta()
    ..retain(index + (len ?? 0))
    ..insert(text, attributes.isEmpty ? null : attributes);
  final next = itr.next();

  final nextAttributes = next.attributes ?? const <String, dynamic>{};
  if (!nextAttributes.containsKey(Attribute.link.key)) {
    return delta;
  }
  if (attributes[Attribute.link.key] == nextAttributes[Attribute.link.key]) {
    return Delta()
      ..retain(index + (len ?? 0))
      ..insert(text, attributes);
  }
  return delta;
}