zefyr

util.dart 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // Copyright (c) 2018, the Zefyr project authors. Please see the AUTHORS file
  2. // for details. All rights reserved. Use of this source code is governed by a
  3. // BSD-style license that can be found in the LICENSE file.
  4. /// Utility functions for Zefyr.
  5. library zefyr.util;
  6. import 'dart:math' as math;
  7. import 'package:quill_delta/quill_delta.dart';
  8. export 'src/fast_diff.dart';
  9. int getPositionDelta(Delta user, Delta actual) {
  10. final userIter = DeltaIterator(user);
  11. final actualIter = DeltaIterator(actual);
  12. int diff = 0;
  13. while (userIter.hasNext || actualIter.hasNext) {
  14. num length = math.min(userIter.peekLength(), actualIter.peekLength());
  15. final userOp = userIter.next(length);
  16. final actualOp = actualIter.next(length);
  17. assert(userOp.length == actualOp.length);
  18. if (userOp.key == actualOp.key) continue;
  19. if (userOp.isInsert && actualOp.isRetain) {
  20. diff -= userOp.length;
  21. } else if (userOp.isDelete && actualOp.isRetain) {
  22. diff += userOp.length;
  23. } else if (userOp.isRetain && actualOp.isInsert) {
  24. if (actualOp.data.startsWith('\n')) {
  25. // At this point user input reached its end (retain). If a heuristic
  26. // rule inserts a new line we should keep cursor on it's original position.
  27. continue;
  28. }
  29. diff += actualOp.length;
  30. } else {
  31. // TODO: this likely needs to cover more edge cases.
  32. }
  33. }
  34. return diff;
  35. }