cosmic_applet_avestruz/handlers/
completing.rs1use std::sync::Arc;
33
34use cosmic::iced::core::text::editor::{Cursor, Position};
35use cosmic::iced::widget::operation::focus;
36use cosmic::prelude::*;
37use cosmic::widget::text_editor::{Action, Content, Edit};
38
39use crate::emoji::{self, COMPLETED_FROM, COMPLETED_MAX, Used};
40use crate::messages::Message;
41use crate::state::{AppModel, EmojiHint, Step};
42use crate::views::compose::COMPOSE_EDITOR_ID;
43
44fn before_cursor(content: &Content) -> Option<String> {
48 let cursor = content.cursor();
49 if cursor.selection.is_some() {
50 return None;
51 }
52 let line = content.line(cursor.position.line)?;
53 line.text.get(..cursor.position.column).map(str::to_string)
54}
55
56fn replace_before_cursor(content: &mut Content, bytes: usize, with: &str) {
59 let position = content.cursor().position;
60 let Some(start) = position.column.checked_sub(bytes) else {
61 return;
62 };
63 content.move_to(Cursor { position, selection: Some(Position { line: position.line, column: start }) });
64 content.perform(Action::Edit(Edit::Paste(Arc::new(with.to_string()))));
65}
66
67fn completed(content: &mut Content, closed: bool, used: &[Used]) -> Option<EmojiHint> {
73 let before = before_cursor(content)?;
74 if closed {
75 let whole = before.strip_suffix(':').and_then(emoji::typed_code);
76 if let Some((code, emoji)) = whole.and_then(|code| Some((code, emoji::by_code(code)?))) {
77 replace_before_cursor(content, code.len() + 2, emoji);
78 }
79 return None;
80 }
81 let typed = emoji::typed_code(&before).filter(|typed| typed.len() >= COMPLETED_FROM)?;
82 let found = emoji::completing(typed, used, COMPLETED_MAX);
83 (!found.is_empty()).then(|| EmojiHint { typed: typed.to_string(), found, at: 0 })
84}
85
86impl AppModel {
87 pub(crate) fn complete_emoji(&mut self, closed: bool) {
92 if let Some(composer) = self.composer.as_mut() {
93 composer.emoji = completed(&mut composer.content, closed, &self.config.reaction_emojis);
94 }
95 }
96
97 pub fn handle_emoji_hint_step(&mut self, step: Step) {
100 if let Some(hint) = self.composer.as_mut().and_then(|composer| composer.emoji.as_mut()) {
101 let offered = hint.found.len().max(1);
102 hint.at = match step {
103 Step::Next => (hint.at + 1) % offered,
104 Step::Previous => (hint.at + offered - 1) % offered,
105 Step::Top => 0,
106 };
107 }
108 }
109
110 pub fn handle_emoji_hint_choose(&mut self, which: Option<usize>) -> Task<cosmic::Action<Message>> {
114 let Some(composer) = self.composer.as_mut().filter(|composer| !composer.publishing) else {
115 return Task::none();
116 };
117 let Some(hint) = composer.emoji.take() else {
118 return Task::none();
119 };
120 let still = before_cursor(&composer.content).is_some_and(|before| before.ends_with(&format!(":{}", hint.typed)));
123 if let Some(taken) = hint.found.get(which.unwrap_or(hint.at)).filter(|_| still) {
124 replace_before_cursor(&mut composer.content, hint.typed.len() + 1, &format!("{} ", taken.emoji));
125 composer.error = None;
126 }
127 focus(COMPOSE_EDITOR_ID.clone())
128 }
129
130 pub fn handle_emoji_hint_close(&mut self) {
132 if let Some(composer) = self.composer.as_mut() {
133 composer.emoji = None;
134 }
135 }
136}
137
138#[cfg(test)]
139mod tests {
140 use super::{before_cursor, completed, replace_before_cursor};
141 use cosmic::widget::text_editor::{Action, Content, Edit, Motion};
142
143 fn typing(typed: &str) -> (String, Option<Vec<&'static str>>) {
146 let mut content = Content::new();
147 let mut hint = None;
148 for c in typed.chars() {
149 match c {
150 '\n' => content.perform(Action::Edit(Edit::Enter)),
151 c => content.perform(Action::Edit(Edit::Insert(c))),
152 }
153 hint = completed(&mut content, c == ':', &[]);
154 }
155 let offered = hint.map(|hint| hint.found.iter().map(|found| found.emoji).collect());
156 (content.text().trim_end_matches('\n').to_string(), offered)
157 }
158
159 #[test]
160 fn a_colon_and_two_letters_offer_emoji_and_one_alone_does_not() {
161 assert_eq!(typing("gm :"), ("gm :".to_string(), None));
162 assert_eq!(typing("gm :t"), ("gm :t".to_string(), None));
163 let (text, offered) = typing("gm :ta");
164 assert_eq!(text, "gm :ta");
165 assert!(offered.is_some_and(|offered| offered.contains(&"π")));
166 assert!(typing("gm\nΓ©dith\n(:tad").1.is_some_and(|offered| offered.first() == Some(&"π")));
169 for other in ["gm :zzzz", "at 12:30", "https://ex", "gm :-)", "note:tada"] {
171 assert_eq!(typing(other), (other.to_string(), None), "{other}");
172 }
173 }
174
175 #[test]
176 fn a_short_code_typed_whole_is_its_emoji_where_it_stood() {
177 assert_eq!(typing("gm :tada:"), ("gm π".to_string(), None));
178 assert_eq!(typing("gm :TADA: all"), ("gm π all".to_string(), None));
179 assert_eq!(typing("Γ© :+1:\n:v:"), ("Γ© π\nβοΈ".to_string(), None));
180 assert_eq!(typing("gm :tad:"), ("gm :tad:".to_string(), None));
183 assert_eq!(typing("at 12:30:"), ("at 12:30:".to_string(), None));
184 assert_eq!(typing("note:tada:"), ("note:tada:".to_string(), None));
185 }
186
187 #[test]
188 fn the_emoji_taken_stands_where_what_was_typed_did() {
189 let mut content = Content::with_text("Γ© :ta and more");
190 content.perform(Action::Move(Motion::DocumentStart));
192 for _ in 0.."Γ© :ta".chars().count() {
193 content.perform(Action::Move(Motion::Right));
194 }
195 assert_eq!(before_cursor(&content).as_deref(), Some("Γ© :ta"));
196 replace_before_cursor(&mut content, ":ta".len(), "π ");
197 assert_eq!(content.text().trim_end_matches('\n'), "Γ© π and more");
198 assert_eq!(before_cursor(&content).as_deref(), Some("Γ© π "), "the cursor is after it");
199 replace_before_cursor(&mut content, 100, "x");
201 assert_eq!(content.text().trim_end_matches('\n'), "Γ© π and more");
202
203 content.perform(Action::Select(Motion::Left));
206 assert_eq!(before_cursor(&content), None);
207 }
208}