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) {
  // We are only interested in embeddable objects.
  if (data is String) return null;

  final result = Delta()..retain(index);
  final iter = DeltaIterator(document);
  final previous = iter.skip(index);
  final target = iter.next();

  // Check if [index] is on an empty line already.
  final textBefore =
      previous?.data is String ? previous!.data as String? : '';
  final textAfter = target.data is String ? (target.data as String?)! : '';

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

  if (isOnEmptyLine) {
    return result..insert(data);
  }
  // We are on a non-empty line, split it (preserving style if needed)
  // and insert our embed.
  final lineStyle = _getLineStyle(iter, target);
  if (!isNewlineBefore) {
    result..insert('\n', lineStyle);
  }
  result..insert(data);
  if (!isNewlineAfter) {
    result..insert('\n');
  }
  return result;
}