transformPosition method

int transformPosition(
  1. int index, {
  2. bool force = true,
})

Transforms index against this delta.

Any "delete" operation before specified index shifts it backward, as well as any "insert" operation shifts it forward.

The force argument is used to resolve scenarios when there is an insert operation at the same position as index. If force is set to true (default) then position is forced to shift forward, otherwise position stays at the same index. In other words setting force to false gives higher priority to the transformed position.

Useful to adjust caret or selection positions.

Implementation

int transformPosition(int index, {bool force = true}) {
  final iter = DeltaIterator(this);
  var offset = 0;
  while (iter.hasNext && offset <= index) {
    final op = iter.next();
    if (op.isDelete) {
      index -= math.min(op.length!, index - offset);
      continue;
    } else if (op.isInsert && (offset < index || force)) {
      index += op.length!;
    }
    offset += op.length!;
  }
  return index;
}