Skip to main content

strata_editor/
ime.rs

1//! Input Method Editor (IME) composition tracking for East Asian CJK input.
2
3/// Lifecycle states of an active IME text composition session.
4#[derive(Debug, Clone, PartialEq, Eq, Default)]
5pub enum ImeState {
6    #[default]
7    Inactive,
8    /// Actively composing pre-edit candidate text (e.g. pinyin or hiragana).
9    Composing {
10        preedit_text: String,
11        cursor_offset: usize,
12        selection_range: Option<(usize, usize)>,
13    },
14    /// Text was finalized and committed to the document buffer.
15    Committed(String),
16}
17
18/// Tracks inline IME pre-edit composition states and cursor positioning.
19#[derive(Debug, Clone, Default)]
20pub struct ImeComposition {
21    state: ImeState,
22}
23
24impl ImeComposition {
25    pub fn new() -> Self {
26        Self {
27            state: ImeState::Inactive,
28        }
29    }
30
31    /// Returns the current IME composition state.
32    pub fn state(&self) -> &ImeState {
33        &self.state
34    }
35
36    /// Returns whether the user is actively composing an IME candidate string.
37    pub fn is_composing(&self) -> bool {
38        matches!(self.state, ImeState::Composing { .. })
39    }
40
41    /// Starts an IME composition session.
42    pub fn start(&mut self) {
43        self.state = ImeState::Composing {
44            preedit_text: String::new(),
45            cursor_offset: 0,
46            selection_range: None,
47        };
48    }
49
50    /// Updates the active pre-edit text and caret position during candidate composition.
51    pub fn update(&mut self, text: &str, cursor_offset: usize) {
52        self.state = ImeState::Composing {
53            preedit_text: text.to_string(),
54            cursor_offset,
55            selection_range: None,
56        };
57    }
58
59    /// Commits the composed string and resets IME state to inactive.
60    pub fn commit(&mut self) -> Option<String> {
61        match std::mem::replace(&mut self.state, ImeState::Inactive) {
62            ImeState::Composing { preedit_text, .. } => {
63                if !preedit_text.is_empty() {
64                    Some(preedit_text)
65                } else {
66                    None
67                }
68            }
69            ImeState::Committed(s) => Some(s),
70            ImeState::Inactive => None,
71        }
72    }
73
74    /// Cancels active composition without committing text.
75    pub fn cancel(&mut self) {
76        self.state = ImeState::Inactive;
77    }
78
79    /// Accesses the active pre-edit string if composing.
80    pub fn preedit_text(&self) -> Option<&str> {
81        match &self.state {
82            ImeState::Composing { preedit_text, .. } => Some(preedit_text.as_str()),
83            _ => None,
84        }
85    }
86}