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;

  final text = data;
  if (text != '\n') return null;

  final iter = DeltaIterator(document);
  final previous = iter.skip(index);
  final target = iter.next();
  final isInBlock = target.isNotPlain &&
      target.attributes!.containsKey(NotusAttribute.block.key);

  // We are not in a block, ignore.
  if (!isInBlock) return null;
  // We are not on an empty line, ignore.
  if (!isEmptyLine(previous, target)) return null;

  final blockStyle = target.attributes![NotusAttribute.block.key];

  // We are on an empty line. Now we need to determine if we are on the
  // last line of a block.
  // First check if `target` length is greater than 1, this would indicate
  // that it contains multiple newline characters which share the same style.
  // This would mean we are not on the last line yet.
  final targetText = target.value
      as String; // this is safe since we already called isEmptyLine and know it contains a newline

  if (targetText.length > 1) {
    // We are not on the last line of this block, ignore.
    return null;
  }

  // Keep looking for the next newline character to see if it shares the same
  // block style as `target`.
  final nextNewline = _findNextNewline(iter);
  if (nextNewline.isNotEmpty &&
      nextNewline.op!.attributes != null &&
      nextNewline.op!.attributes![NotusAttribute.block.key] == blockStyle) {
    // We are not at the end of this block, ignore.
    return null;
  }

  // Here we now know that the line after `target` is not in the same block
  // therefore we can exit this block.
  final attributes = target.attributes ?? <String, dynamic>{};
  attributes.addAll(NotusAttribute.block.unset.toJson());
  return Delta()..retain(index)..retain(1, attributes);
}