Skip to main content

cosmic_applet_avestruz/handlers/
completing.rs

1// SPDX-License-Identifier: MIT
2
3//! Handlers for the emoji offered while one is being written: a colon
4//! and the start of its short code, typed in the composer.
5//!
6//! After everything that is done to the text, what is on the cursor's
7//! line before the cursor is looked at (see [`emoji::typed_code`]). If
8//! it ends in a colon and [`COMPLETED_FROM`] letters or more of a
9//! short code, the emoji that may be are offered under the text, the
10//! likeliest first (see [`emoji::completing`]), and the keys that would
11//! move through the text move through them instead: the arrows up and
12//! down, Enter or Tab to take the one marked, Escape to put them away.
13//! The one taken stands where the colon and the letters were, with a
14//! space after it. Moving the cursor away, or typing what no short code
15//! has, puts them away as well.
16//!
17//! A short code typed whole, with the colon that closes it, is its emoji
18//! at once: `:tada:` is what is written wherever emoji are written this
19//! way, by those who know the name and need no list.
20//!
21//! ```mermaid
22//! flowchart TD
23//!     edit["Something is done to the text"] --> closed{"A colon was typed that closes a short code?"}
24//!     closed -->|"yes, and it is one"| swap["The emoji stands in its place"]
25//!     closed -->|"no"| typed{"The line ends, at the cursor, in a colon and two letters or more?"}
26//!     typed -->|"yes, and emoji are called that"| offer["They are offered under the text"]
27//!     typed -->|"no"| away["Nothing is offered"]
28//!     offer -->|"Enter, Tab, a click"| swap
29//!     offer -->|"Esc"| away
30//! ```
31
32use 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
44/// What is on the cursor's line of `content` before the cursor, where
45/// nothing is selected: with something selected, what is typed takes its
46/// place, and completes nothing.
47fn 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
56/// Put `with` in `content` in place of the `bytes` bytes before the
57/// cursor, which are on its line.
58fn 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
67/// What comes of the text of `content` being as it is now, for the emoji
68/// that are written by their short codes: the emoji to offer for the one
69/// being typed, if one is, ranked by the ones `used`. And if `closed`,
70/// which is whether the last thing done was typing a colon, and that
71/// colon closed a short code, the emoji is put in its place.
72fn 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    /// Something was done to the text in the composer: offer the emoji
88    /// for the short code that is being typed in it now, if one is, and
89    /// have one typed whole be its emoji. `closed` is whether what was
90    /// done was typing a colon.
91    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    /// An arrow was pressed while emoji are offered: mark the next of
98    /// them, or the one before, around from the last to the first.
99    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    /// One of the emoji offered was taken: the one at `which`, or the
111    /// one marked. It stands where the colon and what was typed after it
112    /// were, with a space after it, and the keyboard is in the text.
113    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        // Only while it is still what is before the cursor: the text is
121        // written to between its being offered and its being taken.
122        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    /// The emoji offered are put away, until more is typed.
131    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    /// What is typed, a character at a time, into nothing: the text it
144    /// leaves, and what is offered at the end.
145    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        // On a line of its own under others, and after what is no
167        // letter, as after a letter that is not ASCII before it.
168        assert!(typing("gm\nΓ©dith\n(:tad").1.is_some_and(|offered| offered.first() == Some(&"πŸŽ‰")));
169        // Nothing is called that; and a time, an address, a face.
170        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        // What is no short code stays as it was typed, and so does one
181        // whose colon starts nothing.
182        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        // The cursor after ":ta", in the middle of the line.
191        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        // Nothing is replaced past the start of the line.
200        replace_before_cursor(&mut content, 100, "x");
201        assert_eq!(content.text().trim_end_matches('\n'), "Γ© πŸŽ‰  and more");
202
203        // With something selected there is nothing before the cursor to
204        // complete.
205        content.perform(Action::Select(Motion::Left));
206        assert_eq!(before_cursor(&content), None);
207    }
208}