selection.dart 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import 'package:flowy_editor/document/path.dart';
  2. import 'package:flowy_editor/document/position.dart';
  3. import 'package:flowy_editor/extensions/path_extensions.dart';
  4. class Selection {
  5. final Position start;
  6. final Position end;
  7. Selection({
  8. required this.start,
  9. required this.end,
  10. });
  11. Selection.single({
  12. required Path path,
  13. required int startOffset,
  14. int? endOffset,
  15. }) : start = Position(path: path, offset: startOffset),
  16. end = Position(path: path, offset: endOffset ?? startOffset);
  17. Selection.collapsed(Position position)
  18. : start = position,
  19. end = position;
  20. Selection collapse({bool atStart = false}) {
  21. if (atStart) {
  22. return Selection(start: start, end: start);
  23. } else {
  24. return Selection(start: end, end: end);
  25. }
  26. }
  27. bool get isCollapsed => start == end;
  28. bool get isSingle => pathEquals(start.path, end.path);
  29. bool get isUpward =>
  30. start.path >= end.path && !pathEquals(start.path, end.path);
  31. bool get isDownward =>
  32. start.path <= end.path && !pathEquals(start.path, end.path);
  33. Selection copyWith({Position? start, Position? end}) {
  34. return Selection(
  35. start: start ?? this.start,
  36. end: end ?? this.end,
  37. );
  38. }
  39. Selection copy() => Selection(start: start, end: end);
  40. @override
  41. String toString() => '[Selection] start = $start, end = $end';
  42. Map<String, dynamic> toJson() {
  43. return {
  44. "start": start.toJson(),
  45. "end": end.toJson(),
  46. };
  47. }
  48. @override
  49. bool operator ==(Object other) {
  50. if (other is! Selection) {
  51. return false;
  52. }
  53. if (identical(this, other)) {
  54. return true;
  55. }
  56. return start == other.start && end == other.end;
  57. }
  58. @override
  59. int get hashCode => Object.hash(start, end);
  60. }