forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

text_field.rs70 lines, 2.4 KiBHistoryRawDownload
1//! The one text-field behaviour the in-place renames share (sequence tabs, track heads): a
2//! name opens fully selected, so typing replaces it; Ctrl+A selects it all again; backspace
3//! on a selection clears it; enter saves and escape gives up are the caller's.
4
5/// A name being retyped: its text and whether all of it is selected.
6#[derive(Clone, Debug, PartialEq, Eq)]
7pub(crate) struct TextField {
8 pub(crate) text: String,
9 pub(crate) all: bool,
10}
11
12/// What a key did to the field.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub(crate) enum FieldKey {
15 Edited,
16 Commit,
17 Cancel,
18}
19
20impl TextField {
21 /// A field opened on `text` with all of it selected (the convention for a rename).
22 pub(crate) fn selected(text: impl Into<String>) -> Self {
23 Self { text: text.into(), all: true }
24 }
25
26 /// A field a click focused: the text stays as it is and the caret sits
27 /// where the click put it (at the end -- a name has no caret to place
28 /// mid-text), so the next key edits and nothing is replaced.
29 #[allow(dead_code)]
30 pub(crate) fn clicked(text: impl Into<String>) -> Self {
31 Self { text: text.into(), all: false }
32 }
33
34 /// A field Tab focused: all of it selected, as in every desktop form.
35 #[allow(dead_code)]
36 pub(crate) fn tabbed(text: impl Into<String>) -> Self {
37 Self::selected(text)
38 }
39
40 /// Applies one key; `max` caps the characters.
41 pub(crate) fn key(&mut self, key: &str, ctrl: bool, alt: bool, key_char: Option<&str>, max: usize) -> FieldKey {
42 match key {
43 "escape" => return FieldKey::Cancel,
44 "enter" => return FieldKey::Commit,
45 "a" if ctrl && !alt => self.all = true,
46 "backspace" => {
47 if self.all {
48 self.text.clear();
49 self.all = false;
50 } else {
51 self.text.pop();
52 }
53 }
54 _ => {
55 if !ctrl && !alt && let Some(chars) = key_char {
56 for c in chars.chars().filter(|c| !c.is_control()) {
57 if self.all {
58 self.text.clear();
59 self.all = false;
60 }
61 if self.text.chars().count() < max {
62 self.text.push(c);
63 }
64 }
65 }
66 }
67 }
68 FieldKey::Edited
69 }
70}