use crate::grapheme::{floor_grapheme_boundary, next_grapheme_boundary, prev_grapheme_boundary};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextEdit<P> {
pub start: P,
pub end: P,
pub removed: String,
pub inserted: String,
pub new_end: P,
}
pub trait TextBuffer {
type Pos: Clone + Ord;
fn start_pos(&self) -> Self::Pos;
fn end_pos(&self) -> Self::Pos;
fn clamp_pos(&self, pos: Self::Pos) -> Self::Pos;
fn prev_boundary(&self, pos: Self::Pos) -> Self::Pos;
fn next_boundary(&self, pos: Self::Pos) -> Self::Pos;
fn text_between(&self, start: Self::Pos, end: Self::Pos) -> String;
fn replace(&mut self, start: Self::Pos, end: Self::Pos, text: &str) -> TextEdit<Self::Pos>;
}
impl TextBuffer for String {
type Pos = usize;
fn start_pos(&self) -> usize {
0
}
fn end_pos(&self) -> usize {
self.len()
}
fn clamp_pos(&self, pos: usize) -> usize {
floor_grapheme_boundary(self, pos)
}
fn prev_boundary(&self, pos: usize) -> usize {
prev_grapheme_boundary(self, pos)
}
fn next_boundary(&self, pos: usize) -> usize {
next_grapheme_boundary(self, pos)
}
fn text_between(&self, start: usize, end: usize) -> String {
let len = self.len();
let a = start.min(end).min(len);
let b = start.max(end).min(len);
self[a..b].to_string()
}
fn replace(&mut self, start: usize, end: usize, text: &str) -> TextEdit<usize> {
let start = self.clamp_pos(start);
let end = self.clamp_pos(end);
let (start, end) = if start <= end { (start, end) } else { (end, start) };
let removed = self[start..end].to_string();
self.replace_range(start..end, text);
TextEdit { start, end, removed, inserted: text.to_string(), new_end: start + text.len() }
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextSelection<P> {
anchor: P,
focus: P,
}
impl<P: Clone + Ord> TextSelection<P> {
pub fn new(anchor: P, focus: P) -> Self {
Self { anchor, focus }
}
pub fn collapsed(pos: P) -> Self {
Self::new(pos.clone(), pos)
}
pub fn from_range(a: P, b: P) -> Self {
let (start, end) = if a <= b { (a, b) } else { (b, a) };
Self::new(start, end)
}
pub fn anchor(&self) -> &P {
&self.anchor
}
pub fn focus(&self) -> &P {
&self.focus
}
pub fn is_empty(&self) -> bool {
self.anchor == self.focus
}
pub fn range(&self) -> (P, P) {
if self.anchor <= self.focus {
(self.anchor.clone(), self.focus.clone())
} else {
(self.focus.clone(), self.anchor.clone())
}
}
pub fn set_anchor(&mut self, pos: P) {
self.anchor = pos;
}
pub fn collapse_to(&mut self, pos: P) {
self.anchor = pos.clone();
self.focus = pos;
}
pub fn set_focus(&mut self, pos: P) {
self.focus = pos;
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TextMove {
Left,
Right,
}
pub fn move_selection<B: TextBuffer>(buf: &B, sel: &mut TextSelection<B::Pos>, dir: TextMove, extend: bool) {
let focus = sel.focus().clone();
let next = match dir {
TextMove::Left => buf.prev_boundary(focus),
TextMove::Right => buf.next_boundary(focus),
};
if extend {
sel.set_focus(next);
} else {
sel.collapse_to(next);
}
}
pub fn replace_selection<B: TextBuffer>(
buf: &mut B,
sel: &mut TextSelection<B::Pos>,
text: &str,
) -> Option<TextEdit<B::Pos>> {
if sel.is_empty() && text.is_empty() {
return None;
}
let (start, end) = sel.range();
let edit = buf.replace(start, end, text);
sel.collapse_to(edit.new_end.clone());
Some(edit)
}
pub fn delete_selection<B: TextBuffer>(buf: &mut B, sel: &mut TextSelection<B::Pos>) -> Option<TextEdit<B::Pos>> {
if sel.is_empty() {
return None;
}
replace_selection(buf, sel, "")
}
pub fn delete_before<B: TextBuffer>(buf: &mut B, sel: &mut TextSelection<B::Pos>) -> Option<TextEdit<B::Pos>> {
if !sel.is_empty() {
return delete_selection(buf, sel);
}
let focus = sel.focus().clone();
let start = buf.prev_boundary(focus.clone());
if start == focus {
return None;
}
let edit = buf.replace(start, focus, "");
sel.collapse_to(edit.new_end.clone());
Some(edit)
}
pub fn delete_after<B: TextBuffer>(buf: &mut B, sel: &mut TextSelection<B::Pos>) -> Option<TextEdit<B::Pos>> {
if !sel.is_empty() {
return delete_selection(buf, sel);
}
let focus = sel.focus().clone();
let end = buf.next_boundary(focus.clone());
if end == focus {
return None;
}
let edit = buf.replace(focus, end, "");
sel.collapse_to(edit.new_end.clone());
Some(edit)
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PreeditState {
text: Option<String>,
cursor: Option<(usize, usize)>,
}
impl PreeditState {
pub fn is_active(&self) -> bool {
self.text.is_some()
}
pub fn text(&self) -> Option<&str> {
self.text.as_deref()
}
pub fn cursor(&self) -> Option<(usize, usize)> {
self.cursor
}
pub fn update(&mut self, text: &str, cursor: Option<(usize, usize)>) {
if text.is_empty() {
self.cancel();
return;
}
let len = text.len();
self.cursor = cursor.map(|(a, b)| {
let a = a.min(len);
let b = b.min(len);
(a.min(b), a.max(b))
});
self.text = Some(text.to_string());
}
pub fn commit(&mut self) -> Option<String> {
let text = self.text.take();
self.cursor = None;
text
}
pub fn cancel(&mut self) {
self.text = None;
self.cursor = None;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn selection_normalizes_anchor_and_focus() {
let sel = TextSelection::from_range(9usize, 3);
assert_eq!(sel.range(), (3, 9));
assert_eq!(sel.anchor(), &3);
assert_eq!(sel.focus(), &9);
assert!(!sel.is_empty());
let mut sel = TextSelection::collapsed(4usize);
assert!(sel.is_empty());
sel.set_anchor(1);
assert_eq!(sel.range(), (1, 4));
}
#[test]
fn movement_and_delete_keep_emoji_zwj_intact() {
let family = "👨👩👧👦";
let mut buf = format!("A{family}B");
let mut sel = TextSelection::collapsed(1 + family.len());
move_selection(&buf, &mut sel, TextMove::Left, false);
assert_eq!(*sel.focus(), 1, "左移跳过整个 ZWJ 簇");
sel.collapse_to(1 + family.len());
let edit = delete_before(&mut buf, &mut sel).expect("应删除一个簇");
assert_eq!(edit.removed, family);
assert_eq!(buf, "AB");
assert_eq!(*sel.focus(), 1);
}
#[test]
fn replace_selection_collapses_focus_after_insert() {
let mut buf = String::from("hello");
let mut sel = TextSelection::from_range(1usize, 4);
let edit = replace_selection(&mut buf, &mut sel, "i").expect("替换选区");
assert_eq!(edit.removed, "ell");
assert_eq!(buf, "hio");
assert_eq!(*sel.focus(), 2);
assert!(sel.is_empty());
}
#[test]
fn preedit_lifecycle_never_touches_buffer() {
let buf = String::from("ab");
let mut preedit = PreeditState::default();
preedit.update("中", Some((9, 0)));
assert!(preedit.is_active());
assert_eq!(preedit.text(), Some("中"));
assert_eq!(preedit.cursor(), Some((0, 3)), "光标区间夹紧并排序");
assert_eq!(buf, "ab");
assert_eq!(preedit.commit().as_deref(), Some("中"));
assert!(!preedit.is_active());
assert_eq!(buf, "ab", "commit 由调用方决定如何写入 buffer");
preedit.update("x", None);
preedit.cancel();
assert_eq!(preedit.text(), None);
}
}