1use crate::grapheme::{floor_grapheme_boundary, next_grapheme_boundary, prev_grapheme_boundary};
14
15#[derive(Clone, Debug, PartialEq, Eq)]
17pub struct TextEdit<P> {
18 pub start: P,
19 pub end: P,
20 pub removed: String,
21 pub inserted: String,
22 pub new_end: P,
23}
24
25pub trait TextBuffer {
30 type Pos: Clone + Ord;
31
32 fn start_pos(&self) -> Self::Pos;
33 fn end_pos(&self) -> Self::Pos;
34 fn clamp_pos(&self, pos: Self::Pos) -> Self::Pos;
35 fn prev_boundary(&self, pos: Self::Pos) -> Self::Pos;
36 fn next_boundary(&self, pos: Self::Pos) -> Self::Pos;
37 fn text_between(&self, start: Self::Pos, end: Self::Pos) -> String;
38 fn replace(&mut self, start: Self::Pos, end: Self::Pos, text: &str) -> TextEdit<Self::Pos>;
39}
40
41impl TextBuffer for String {
42 type Pos = usize;
43
44 fn start_pos(&self) -> usize {
45 0
46 }
47
48 fn end_pos(&self) -> usize {
49 self.len()
50 }
51
52 fn clamp_pos(&self, pos: usize) -> usize {
53 floor_grapheme_boundary(self, pos)
54 }
55
56 fn prev_boundary(&self, pos: usize) -> usize {
57 prev_grapheme_boundary(self, pos)
58 }
59
60 fn next_boundary(&self, pos: usize) -> usize {
61 next_grapheme_boundary(self, pos)
62 }
63
64 fn text_between(&self, start: usize, end: usize) -> String {
65 let len = self.len();
66 let a = start.min(end).min(len);
67 let b = start.max(end).min(len);
68 self[a..b].to_string()
69 }
70
71 fn replace(&mut self, start: usize, end: usize, text: &str) -> TextEdit<usize> {
72 let start = self.clamp_pos(start);
73 let end = self.clamp_pos(end);
74 let (start, end) = if start <= end { (start, end) } else { (end, start) };
75 let removed = self[start..end].to_string();
76 self.replace_range(start..end, text);
77 TextEdit { start, end, removed, inserted: text.to_string(), new_end: start + text.len() }
78 }
79}
80
81#[derive(Clone, Debug, PartialEq, Eq)]
83pub struct TextSelection<P> {
84 anchor: P,
85 focus: P,
86}
87
88impl<P: Clone + Ord> TextSelection<P> {
89 pub fn new(anchor: P, focus: P) -> Self {
90 Self { anchor, focus }
91 }
92
93 pub fn collapsed(pos: P) -> Self {
94 Self::new(pos.clone(), pos)
95 }
96
97 pub fn from_range(a: P, b: P) -> Self {
99 let (start, end) = if a <= b { (a, b) } else { (b, a) };
100 Self::new(start, end)
101 }
102
103 pub fn anchor(&self) -> &P {
104 &self.anchor
105 }
106
107 pub fn focus(&self) -> &P {
108 &self.focus
109 }
110
111 pub fn is_empty(&self) -> bool {
112 self.anchor == self.focus
113 }
114
115 pub fn range(&self) -> (P, P) {
116 if self.anchor <= self.focus {
117 (self.anchor.clone(), self.focus.clone())
118 } else {
119 (self.focus.clone(), self.anchor.clone())
120 }
121 }
122
123 pub fn set_anchor(&mut self, pos: P) {
124 self.anchor = pos;
125 }
126
127 pub fn collapse_to(&mut self, pos: P) {
128 self.anchor = pos.clone();
129 self.focus = pos;
130 }
131
132 pub fn set_focus(&mut self, pos: P) {
133 self.focus = pos;
134 }
135}
136
137#[derive(Clone, Copy, Debug, PartialEq, Eq)]
139pub enum TextMove {
140 Left,
141 Right,
142}
143
144pub fn move_selection<B: TextBuffer>(buf: &B, sel: &mut TextSelection<B::Pos>, dir: TextMove, extend: bool) {
146 let focus = sel.focus().clone();
147 let next = match dir {
148 TextMove::Left => buf.prev_boundary(focus),
149 TextMove::Right => buf.next_boundary(focus),
150 };
151 if extend {
152 sel.set_focus(next);
153 } else {
154 sel.collapse_to(next);
155 }
156}
157
158pub fn replace_selection<B: TextBuffer>(
160 buf: &mut B,
161 sel: &mut TextSelection<B::Pos>,
162 text: &str,
163) -> Option<TextEdit<B::Pos>> {
164 if sel.is_empty() && text.is_empty() {
165 return None;
166 }
167 let (start, end) = sel.range();
168 let edit = buf.replace(start, end, text);
169 sel.collapse_to(edit.new_end.clone());
170 Some(edit)
171}
172
173pub fn delete_selection<B: TextBuffer>(buf: &mut B, sel: &mut TextSelection<B::Pos>) -> Option<TextEdit<B::Pos>> {
175 if sel.is_empty() {
176 return None;
177 }
178 replace_selection(buf, sel, "")
179}
180
181pub fn delete_before<B: TextBuffer>(buf: &mut B, sel: &mut TextSelection<B::Pos>) -> Option<TextEdit<B::Pos>> {
183 if !sel.is_empty() {
184 return delete_selection(buf, sel);
185 }
186 let focus = sel.focus().clone();
187 let start = buf.prev_boundary(focus.clone());
188 if start == focus {
189 return None;
190 }
191 let edit = buf.replace(start, focus, "");
192 sel.collapse_to(edit.new_end.clone());
193 Some(edit)
194}
195
196pub fn delete_after<B: TextBuffer>(buf: &mut B, sel: &mut TextSelection<B::Pos>) -> Option<TextEdit<B::Pos>> {
198 if !sel.is_empty() {
199 return delete_selection(buf, sel);
200 }
201 let focus = sel.focus().clone();
202 let end = buf.next_boundary(focus.clone());
203 if end == focus {
204 return None;
205 }
206 let edit = buf.replace(focus, end, "");
207 sel.collapse_to(edit.new_end.clone());
208 Some(edit)
209}
210
211#[derive(Clone, Debug, Default, PartialEq, Eq)]
215pub struct PreeditState {
216 text: Option<String>,
217 cursor: Option<(usize, usize)>,
218}
219
220impl PreeditState {
221 pub fn is_active(&self) -> bool {
222 self.text.is_some()
223 }
224
225 pub fn text(&self) -> Option<&str> {
226 self.text.as_deref()
227 }
228
229 pub fn cursor(&self) -> Option<(usize, usize)> {
230 self.cursor
231 }
232
233 pub fn update(&mut self, text: &str, cursor: Option<(usize, usize)>) {
235 if text.is_empty() {
236 self.cancel();
237 return;
238 }
239 let len = text.len();
240 self.cursor = cursor.map(|(a, b)| {
241 let a = a.min(len);
242 let b = b.min(len);
243 (a.min(b), a.max(b))
244 });
245 self.text = Some(text.to_string());
246 }
247
248 pub fn commit(&mut self) -> Option<String> {
250 let text = self.text.take();
251 self.cursor = None;
252 text
253 }
254
255 pub fn cancel(&mut self) {
256 self.text = None;
257 self.cursor = None;
258 }
259}
260
261#[cfg(test)]
262mod tests {
263 use super::*;
264
265 #[test]
266 fn selection_normalizes_anchor_and_focus() {
267 let sel = TextSelection::from_range(9usize, 3);
268 assert_eq!(sel.range(), (3, 9));
269 assert_eq!(sel.anchor(), &3);
270 assert_eq!(sel.focus(), &9);
271 assert!(!sel.is_empty());
272
273 let mut sel = TextSelection::collapsed(4usize);
274 assert!(sel.is_empty());
275 sel.set_anchor(1);
276 assert_eq!(sel.range(), (1, 4));
277 }
278
279 #[test]
280 fn movement_and_delete_keep_emoji_zwj_intact() {
281 let family = "👨👩👧👦";
282 let mut buf = format!("A{family}B");
283 let mut sel = TextSelection::collapsed(1 + family.len());
284 move_selection(&buf, &mut sel, TextMove::Left, false);
285 assert_eq!(*sel.focus(), 1, "左移跳过整个 ZWJ 簇");
286
287 sel.collapse_to(1 + family.len());
288 let edit = delete_before(&mut buf, &mut sel).expect("应删除一个簇");
289 assert_eq!(edit.removed, family);
290 assert_eq!(buf, "AB");
291 assert_eq!(*sel.focus(), 1);
292 }
293
294 #[test]
295 fn replace_selection_collapses_focus_after_insert() {
296 let mut buf = String::from("hello");
297 let mut sel = TextSelection::from_range(1usize, 4);
298 let edit = replace_selection(&mut buf, &mut sel, "i").expect("替换选区");
299 assert_eq!(edit.removed, "ell");
300 assert_eq!(buf, "hio");
301 assert_eq!(*sel.focus(), 2);
302 assert!(sel.is_empty());
303 }
304
305 #[test]
306 fn preedit_lifecycle_never_touches_buffer() {
307 let buf = String::from("ab");
308 let mut preedit = PreeditState::default();
309 preedit.update("中", Some((9, 0)));
310 assert!(preedit.is_active());
311 assert_eq!(preedit.text(), Some("中"));
312 assert_eq!(preedit.cursor(), Some((0, 3)), "光标区间夹紧并排序");
313 assert_eq!(buf, "ab");
314
315 assert_eq!(preedit.commit().as_deref(), Some("中"));
316 assert!(!preedit.is_active());
317 assert_eq!(buf, "ab", "commit 由调用方决定如何写入 buffer");
318
319 preedit.update("x", None);
320 preedit.cancel();
321 assert_eq!(preedit.text(), None);
322 }
323}