continuity_text/
selection.rs1use serde::{Deserialize, Serialize};
8
9use crate::{Position, Range};
10
11#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
13pub enum SelectionKind {
14 Caret,
16 LineWise,
18 BlockWise,
20}
21
22#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
24pub struct Selection {
25 pub anchor: Position,
27 pub head: Position,
29 pub kind: SelectionKind,
31}
32
33impl Selection {
34 #[must_use]
36 pub const fn new(anchor: Position, head: Position, kind: SelectionKind) -> Self {
37 Self { anchor, head, kind }
38 }
39
40 #[must_use]
42 pub const fn caret_at(p: Position) -> Self {
43 Self {
44 anchor: p,
45 head: p,
46 kind: SelectionKind::Caret,
47 }
48 }
49
50 #[must_use]
52 pub fn is_collapsed(&self) -> bool {
53 self.anchor == self.head
54 }
55
56 #[must_use]
58 pub fn is_caret(&self) -> bool {
59 matches!(self.kind, SelectionKind::Caret) && self.is_collapsed()
60 }
61
62 #[must_use]
64 pub fn range(&self) -> Range {
65 Range::new(self.anchor, self.head)
66 }
67
68 #[must_use]
70 pub fn ordered_range(&self) -> Range {
71 self.range().ordered()
72 }
73}
74
75#[cfg(test)]
76mod tests {
77 use super::*;
78
79 #[test]
80 fn caret_at_origin_is_collapsed_and_caret() {
81 let s = Selection::caret_at(Position::ZERO);
82 assert!(s.is_collapsed());
83 assert!(s.is_caret());
84 }
85
86 #[test]
87 fn linewise_with_extent_is_not_caret() {
88 let s = Selection {
89 anchor: Position::ZERO,
90 head: Position::new(2, 0),
91 kind: SelectionKind::LineWise,
92 };
93 assert!(!s.is_collapsed());
94 assert!(!s.is_caret());
95 }
96
97 #[test]
98 fn caret_kind_with_extent_is_not_caret() {
99 let s = Selection {
100 anchor: Position::ZERO,
101 head: Position::new(0, 3),
102 kind: SelectionKind::Caret,
103 };
104 assert!(!s.is_collapsed());
105 assert!(!s.is_caret());
106 assert_eq!(s.ordered_range().start, Position::ZERO);
107 assert_eq!(s.ordered_range().end, Position::new(0, 3));
108 }
109}