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) {
    return null;
  }

  assert(data is Map);

  if (!(data as Map).containsKey(BlockEmbed.videoType)) {
    return null;
  }

  final delta = Delta()..retain(index + (len ?? 0));
  final itr = DeltaIterator(document);
  final prev = itr.skip(index), cur = itr.next();

  final textBefore = prev?.data is String ? prev!.data as String? : '';
  final textAfter = cur.data is String ? (cur.data as String?)! : '';

  final isNewlineBefore = prev == null || textBefore!.endsWith('\n');
  final isNewlineAfter = textAfter.startsWith('\n');

  if (isNewlineBefore && isNewlineAfter) {
    return delta..insert(data);
  }

  Map<String, dynamic>? lineStyle;
  if (textAfter.contains('\n')) {
    lineStyle = cur.attributes;
  } else {
    while (itr.hasNext) {
      final op = itr.next();
      if ((op.data is String ? op.data as String? : '')!.contains('\n')) {
        lineStyle = op.attributes;
        break;
      }
    }
  }

  if (!isNewlineBefore) {
    delta.insert('\n', lineStyle);
  }
  delta.insert(data);
  if (!isNewlineAfter) {
    delta.insert('\n');
  }
  return delta;
}