1use unicode_segmentation::UnicodeSegmentation;
4
5use crate::accessibility::Role;
6use crate::animation::Tuning;
7use crate::color::Color;
8use crate::context::{Cursor, HostCommand, Response, Sense};
9use crate::geometry::{Rect, vec2};
10use crate::icon::Icon;
11use crate::input::Key;
12use crate::material::{Corner, Glass};
13use crate::text::{TextLayout, TextStyle};
14use crate::ui::{Ui, Widget};
15
16pub struct TextEdit<'a> {
19 text: &'a mut String,
20 hint: &'a str,
21 icon: Option<Icon>,
22 password: bool,
23 rows: usize,
24 width: Option<f32>,
25 clear_button: bool,
26}
27
28#[derive(Clone, Copy, Default, Debug)]
29struct Edit {
30 cursor: usize,
31 anchor: usize,
32 scroll: f32,
33 blink: f64,
34}
35
36impl Edit {
37 fn range(&self) -> (usize, usize) {
38 (self.cursor.min(self.anchor), self.cursor.max(self.anchor))
39 }
40 fn clamp(&mut self, s: &str) {
41 let fix = |i: usize| {
42 let mut i = i.min(s.len());
43 while !s.is_char_boundary(i) {
44 i -= 1;
45 }
46 i
47 };
48 self.cursor = fix(self.cursor);
49 self.anchor = fix(self.anchor);
50 }
51 fn replace(&mut self, s: &mut String, with: &str) {
52 let (a, b) = self.range();
53 s.replace_range(a..b, with);
54 self.cursor = a + with.len();
55 self.anchor = self.cursor;
56 }
57}
58
59#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
61enum Kind {
62 #[default]
63 None,
64 Insert,
65 Delete,
66 Other,
68}
69
70#[derive(Clone, Debug)]
71struct Snap {
72 text: String,
73 cursor: usize,
74 anchor: usize,
75}
76
77#[derive(Clone, Default, Debug)]
79struct History {
80 undo: Vec<Snap>,
81 redo: Vec<Snap>,
82 known: Option<String>,
85 kind: Kind,
86 at: f64,
87 caret: usize,
88}
89
90const UNDO_LIMIT: usize = 200;
91const UNDO_PAUSE: f64 = 1.2;
93
94impl History {
95 fn record(&mut self, kind: Kind, text: &str, e: &Edit, now: f64) {
97 let merge = kind != Kind::Other
98 && kind == self.kind
99 && now - self.at < UNDO_PAUSE
100 && e.cursor == self.caret
101 && !self.undo.is_empty();
102 if !merge {
103 self.undo.push(Snap { text: text.to_string(), cursor: e.cursor, anchor: e.anchor });
104 if self.undo.len() > UNDO_LIMIT {
105 self.undo.remove(0);
106 }
107 }
108 self.redo.clear();
109 self.kind = kind;
110 self.at = now;
111 }
112
113 fn step(&mut self, redo: bool, text: &mut String, e: &mut Edit) -> bool {
115 let (from, to) =
116 if redo { (&mut self.redo, &mut self.undo) } else { (&mut self.undo, &mut self.redo) };
117 let Some(s) = from.pop() else { return false };
118 to.push(Snap { text: std::mem::replace(text, s.text), cursor: e.cursor, anchor: e.anchor });
119 e.cursor = s.cursor;
120 e.anchor = s.anchor;
121 self.kind = Kind::None;
122 true
123 }
124}
125
126fn prev(s: &str, i: usize) -> usize {
127 s[..i].grapheme_indices(true).next_back().map_or(0, |g| g.0)
128}
129fn next(s: &str, i: usize) -> usize {
130 s[i..].graphemes(true).next().map_or(s.len(), |g| i + g.len())
131}
132fn prev_word(s: &str, i: usize) -> usize {
133 s[..i].unicode_word_indices().next_back().map_or(0, |w| w.0)
134}
135fn next_word(s: &str, i: usize) -> usize {
136 s[i..].unicode_word_indices().next().map_or(s.len(), |w| i + w.0 + w.1.len())
137}
138
139impl<'a> TextEdit<'a> {
140 pub fn new(text: &'a mut String) -> Self {
142 Self { text, hint: "", icon: None, password: false, rows: 1, width: None, clear_button: false }
143 }
144 pub fn hint(mut self, hint: &'a str) -> Self {
146 self.hint = hint;
147 self
148 }
149 pub fn icon(mut self, icon: Icon) -> Self {
151 self.icon = Some(icon);
152 self
153 }
154 pub fn password(mut self) -> Self {
156 self.password = true;
157 self
158 }
159 pub fn rows(mut self, rows: usize) -> Self {
162 self.rows = rows.max(1);
163 self
164 }
165 pub fn width(mut self, width: f32) -> Self {
167 self.width = Some(width);
168 self
169 }
170 pub fn search(mut self) -> Self {
172 self.icon = Some(Icon::Search);
173 self.clear_button = true;
174 self
175 }
176}
177
178impl Widget for TextEdit<'_> {
179 fn ui(self, ui: &mut Ui) -> Response {
180 let multi = self.rows > 1;
181 let font = ui.ctx.theme.body_size;
182 let line = (font * 1.28).ceil();
183 let h = if multi { line * self.rows as f32 + 22.0 } else { ui.ctx.theme.control_height };
184 let w = self.width.unwrap_or_else(|| ui.available_width().clamp(80.0, 420.0));
185 let mut r = ui.allocate_response(vec2(w, h), Sense::Drag);
186 let id = r.id;
187 ui.ctx.focusable(id);
188 let mut e: Edit = ui.ctx.get(id);
189 let mut hist: History = ui.ctx.take(id.with("undo"));
190 if hist.known.as_deref() != Some(self.text.as_str()) {
191 hist = History { known: Some(self.text.clone()), ..Default::default() };
193 }
194 let now = ui.ctx.time;
195 if r.hovered {
196 ui.ctx.cursor = Cursor::Text;
197 }
198 let corner = if multi { Corner::Radius(16.0) } else { Corner::Capsule };
199 let mut left = 14.0;
200 if self.icon.is_some() {
201 left += 22.0;
202 }
203 let show_clear = self.clear_button && !self.text.is_empty();
204 let right = if show_clear { 34.0 } else { 14.0 };
205 let top = if multi { 11.0 } else { (h - line) * 0.5 };
206 let inner = Rect {
207 min: r.rect.min + vec2(left, top),
208 max: r.rect.max - vec2(right, if multi { 11.0 } else { 0.0 }),
209 };
210 let mut st = TextStyle::new(font);
211 if multi {
212 st = st.wrap(inner.width());
213 }
214
215 let before = self.text.clone();
216 e.clamp(self.text);
217 if r.pressed {
218 ui.ctx.set_focus(Some(id));
219 r.focused = true;
220 e.blink = now;
221 }
222 if let Some(v) = ui.ctx.take_access_text(id) {
223 hist.record(Kind::Other, self.text, &e, now);
224 *self.text = v;
225 e.cursor = self.text.len();
226 e.anchor = e.cursor;
227 }
228 let preedit = if r.focused && !self.password { ui.ctx.input.preedit.clone() } else { None };
230 if r.focused && preedit.is_none() {
231 let keys = ui.ctx.input.keys.clone();
232 let typed: String =
233 ui.ctx.input.text.chars().filter(|c| !c.is_control() || (multi && *c == '\n')).collect();
234 for (k, m) in keys {
235 e.blink = now;
236 let word = m.ctrl || m.alt;
237 let moved = match k {
238 Key::Left if !m.shift && e.cursor != e.anchor => Some(e.range().0),
239 Key::Right if !m.shift && e.cursor != e.anchor => Some(e.range().1),
240 Key::Left => {
241 Some(if word { prev_word(self.text, e.cursor) } else { prev(self.text, e.cursor) })
242 }
243 Key::Right => {
244 Some(if word { next_word(self.text, e.cursor) } else { next(self.text, e.cursor) })
245 }
246 Key::Up | Key::Down if multi => {
247 let l = ui.layout_text(self.text, &st);
248 let (x, y, lh) = l.caret(e.cursor);
249 let y = y + lh * if k == Key::Up { -0.5 } else { 1.5 };
250 Some(if y < 0.0 {
251 0
252 } else if y > l.size.y {
253 self.text.len()
254 } else {
255 l.hit(vec2(x, y))
256 })
257 }
258 Key::Home | Key::Up => Some(line_start(self.text, e.cursor, k == Key::Up)),
259 Key::End | Key::Down => Some(line_end(self.text, e.cursor, k == Key::Down)),
260 _ => None,
261 };
262 if let Some(to) = moved {
263 e.cursor = to;
264 if !m.shift {
265 e.anchor = to;
266 }
267 continue;
268 }
269 match k {
270 Key::Backspace | Key::Delete => {
271 if e.cursor == e.anchor {
272 e.anchor = match (k == Key::Backspace, word) {
273 (true, true) => prev_word(self.text, e.cursor),
274 (true, false) => prev(self.text, e.cursor),
275 (false, true) => next_word(self.text, e.cursor),
276 (false, false) => next(self.text, e.cursor),
277 };
278 }
279 if e.cursor != e.anchor {
280 let kind = if e.range().1 - e.range().0 > 4 { Kind::Other } else { Kind::Delete };
281 hist.record(kind, self.text, &e, now);
282 e.replace(self.text, "");
283 }
284 }
285 Key::Enter if multi => {
286 hist.record(Kind::Other, self.text, &e, now);
287 e.replace(self.text, "\n");
288 }
289 Key::Escape | Key::Enter => {
290 ui.ctx.set_focus(None);
291 r.focused = false;
292 }
293 Key::Char('a') if m.command => {
294 e.anchor = 0;
295 e.cursor = self.text.len();
296 }
297 Key::Char('z') if m.command => {
298 hist.step(m.shift, self.text, &mut e);
299 }
300 Key::Char('y') if m.command && !cfg!(target_os = "macos") => {
301 hist.step(true, self.text, &mut e);
302 }
303 Key::Char(c @ ('c' | 'x')) if m.command && !self.password => {
304 let (a, b) = e.range();
305 if a != b {
306 ui.ctx.host_commands.push(HostCommand::Copy(self.text[a..b].to_string()));
307 if c == 'x' {
308 hist.record(Kind::Other, self.text, &e, now);
309 e.replace(self.text, "");
310 }
311 }
312 }
313 _ => {}
314 }
315 }
316 if !typed.is_empty() {
317 let one = typed.graphemes(true).count() == 1 && e.cursor == e.anchor;
320 let kind = if one { Kind::Insert } else { Kind::Other };
321 hist.record(kind, self.text, &e, now);
322 e.replace(self.text, &typed);
323 if typed.chars().all(char::is_whitespace) {
324 hist.kind = Kind::None;
325 }
326 e.blink = now;
327 }
328 }
329
330 let shown =
331 if self.password { "\u{2022}".repeat(self.text.chars().count()) } else { self.text.clone() };
332 let text_ref: &str = self.text;
334 let password = self.password;
335 let to_shown = |i: usize| if password { text_ref[..i].chars().count() * 3 } else { i };
336 let from_shown = |i: usize| {
337 if password { text_ref.char_indices().nth(i / 3).map_or(text_ref.len(), |c| c.0) } else { i }
338 };
339 let l = ui.layout_text(&shown, &st);
340 if r.held
341 && preedit.is_none()
342 && let Some(p) = r.pointer
343 {
344 let q = p - inner.min + if multi { vec2(0.0, e.scroll) } else { vec2(e.scroll, 0.0) };
345 e.cursor = from_shown(l.hit(q));
346 if r.pressed && !ui.ctx.input.modifiers.shift {
347 e.anchor = e.cursor;
348 }
349 }
350 if r.double_clicked {
351 e.anchor = prev_word(text_ref, next(text_ref, e.cursor).max(e.cursor));
352 e.cursor = next_word(text_ref, e.anchor);
353 }
354
355 let (a, b) = e.range();
357 let (sa, sb) = (to_shown(a), to_shown(b));
358 let (l, caret, composing) = match &preedit {
359 Some(p) => {
360 let s = format!("{}{}{}", &shown[..sa], p.text, &shown[sb..]);
361 let at = sa + p.cursor.map_or(p.text.len(), |c| c.1.min(p.text.len()));
362 (ui.layout_text(&s, &st), at, Some((sa, sa + p.text.len())))
363 }
364 None => (l, to_shown(e.cursor), None),
365 };
366
367 let (cx, cy, ch) = l.caret(caret);
369 if multi {
370 let view = inner.height();
371 if cy < e.scroll {
372 e.scroll = cy;
373 }
374 if cy + ch > e.scroll + view {
375 e.scroll = cy + ch - view;
376 }
377 e.scroll = e.scroll.clamp(0.0, (l.size.y - view).max(0.0));
378 } else {
379 let view = inner.width();
380 if cx < e.scroll {
381 e.scroll = cx;
382 }
383 if cx > e.scroll + view {
384 e.scroll = cx - view;
385 }
386 e.scroll = e.scroll.clamp(0.0, (l.size.x - view).max(0.0));
387 }
388 ui.ctx.set(id, e);
389 if before != *self.text || hist.known.is_none() {
390 hist.known = Some(self.text.clone());
391 }
392 hist.caret = e.cursor;
393 ui.ctx.set(id.with("undo"), hist);
394
395 let f = ui.ctx.animate_bool(id.with("f"), r.focused, Tuning::SMOOTH);
396 let hov = ui.ctx.animate_bool(id.with("h"), r.hovered, Tuning::SNAP);
397 let accent = ui.ctx.theme.accent;
398 let mut s = ui.surface;
399 if ui.surface.is_glass() {
400 let c = s.fill_color();
401 ui.painter().fill(r.rect, corner, c.fade(1.0 + 0.4 * hov));
402 } else {
403 let mut m = ui.ctx.theme.regular;
404 m.blur = m.blur.max(4.0);
405 let mut g = Glass::new(r.rect, corner, m);
406 s = ui.ctx.prepare_glass(id, &mut g, !multi).surface();
407 ui.painter().glass(&g);
408 }
409 let off = if multi { vec2(0.0, e.scroll) } else { vec2(e.scroll, 0.0) };
410 let origin = inner.min - off;
411 let caret_on = r.focused && (composing.is_some() || ((now - e.blink) % 1.06) < 0.56);
412 if r.focused {
413 ui.ctx.request_repaint();
414 let c = origin + vec2(cx, cy);
415 ui.ctx.ime_area = Some(Rect { min: c, max: c + vec2(1.0, ch) });
416 }
417 let hint = ui.layout_text(self.hint, &st);
418 let old_clip = ui.clip;
419 ui.clip =
420 ui.clip.intersect(Rect { min: inner.min - vec2(2.0, 2.0), max: inner.max + vec2(2.0, 2.0) });
421 let text_color = s.text_color();
422 let mut p = ui.painter();
423 if composing.is_none() && sa != sb && f > 0.01 {
424 for (s0, s1, top, height) in spans(&l, sa, sb) {
425 let sel = Rect { min: origin + vec2(s0, top), max: origin + vec2(s1, top + height) };
426 p.fill(sel, 3.0, accent.alpha(0.30 * f));
427 }
428 }
429 if let Some((c0, c1)) = composing {
430 for (s0, s1, top, height) in spans(&l, c0, c1) {
431 let y = top + height - 2.0;
432 p.line(origin + vec2(s0, y), origin + vec2(s1, y), 1.4, text_color.fade(0.8));
433 }
434 }
435 if shown.is_empty() && composing.is_none() {
436 p.text(origin, &hint, s.tertiary_color());
437 }
438 p.text(origin, &l, text_color);
439 if caret_on {
440 let c = origin + vec2(cx, cy);
441 p.fill(Rect { min: c + vec2(-1.0, 1.0), max: c + vec2(1.0, ch - 1.0) }, 1.0, accent);
442 }
443 ui.clip = old_clip;
444 if let Some(i) = self.icon {
445 let y = if multi { r.rect.min.y + 11.0 + line * 0.5 } else { r.rect.center().y };
446 let c = s.secondary_color();
447 ui.painter().icon(vec2(r.rect.min.x + 22.0, y), 16.0, i, c);
448 }
449 if show_clear {
450 let c = vec2(r.rect.max.x - 19.0, r.rect.center().y);
451 let cr = Rect::from_center_size(c, vec2(20.0, 20.0));
452 let x = ui.interact(id.with("clear"), cr, Sense::Click);
453 if let Some(n) = ui.access(x.id, Role::Button, cr) {
454 n.label("Clear text");
455 }
456 if x.clicked {
457 let mut hist: History = ui.ctx.take(id.with("undo"));
458 hist.record(Kind::Other, self.text, &e, now);
459 self.text.clear();
460 hist.known = Some(String::new());
461 ui.ctx.set(id.with("undo"), hist);
462 ui.ctx.set_focus(Some(id));
463 }
464 if x.hovered {
465 ui.ctx.cursor = Cursor::Pointer;
466 }
467 let (bg, fg) = (s.tertiary_color(), if s.darkness() > 0.5 { Color::BLACK } else { Color::WHITE });
468 let mut p = ui.painter();
469 p.fill(cr.shrink(1.5), Corner::Capsule, bg);
470 p.icon(c, 12.0, Icon::Close, fg);
471 }
472 if f > 0.01 {
473 ui.painter().stroke(r.rect.expand(2.0), corner, 2.0, accent.alpha(0.55 * f.clamp(0.0, 1.0)));
474 }
475 let role = if self.password {
476 Role::PasswordInput
477 } else if multi {
478 Role::MultilineTextInput
479 } else if self.icon == Some(Icon::Search) {
480 Role::SearchInput
481 } else {
482 Role::TextInput
483 };
484 if let Some(n) = ui.access(id, role, r.rect) {
485 n.label(self.hint).value(shown);
486 }
487 r.changed = before != *self.text;
488 r
489 }
490}
491
492fn spans(l: &TextLayout, a: usize, b: usize) -> Vec<(f32, f32, f32, f32)> {
494 let mut out = Vec::new();
495 for ln in &l.lines {
496 let s0 = a.max(ln.start);
497 let s1 = b.min(ln.end);
498 if s0 >= s1 {
499 continue;
500 }
501 let x = |i: usize| ln.stops.iter().rev().find(|s| s.0 <= i).map_or(0.0, |s| s.1);
502 out.push((x(s0), x(s1), ln.top, ln.height));
503 }
504 out
505}
506
507fn line_start(s: &str, i: usize, all: bool) -> usize {
508 if all { 0 } else { s[..i].rfind('\n').map_or(0, |p| p + 1) }
509}
510fn line_end(s: &str, i: usize, all: bool) -> usize {
511 if all { s.len() } else { s[i..].find('\n').map_or(s.len(), |p| i + p) }
512}
513
514impl Ui<'_> {
515 pub fn text_edit(&mut self, text: &mut String, hint: &str) -> Response {
517 self.add(TextEdit::new(text).hint(hint))
518 }
519 pub fn search_field(&mut self, text: &mut String, hint: &str) -> Response {
521 self.add(TextEdit::new(text).hint(hint).search())
522 }
523}
524
525#[cfg(test)]
526mod tests {
527 use super::*;
528
529 #[test]
530 fn grapheme_and_word_steps() {
531 let s = "a👩🚀b two";
532 assert_eq!(next(s, 1), s.find('b').unwrap());
533 assert_eq!(prev(s, s.find('b').unwrap()), 1);
534 assert_eq!(prev_word(s, s.len()), s.find("two").unwrap());
535 }
536
537 #[test]
538 fn replace_selection() {
539 let mut s = String::from("hello world");
540 let mut e = Edit { cursor: 0, anchor: 5, ..Default::default() };
541 e.replace(&mut s, "bye");
542 assert_eq!(s, "bye world");
543 assert_eq!(e.cursor, 3);
544 }
545
546 #[test]
547 fn clamp_lands_on_char_boundary() {
548 let mut e = Edit { cursor: 2, anchor: 99, ..Default::default() };
549 e.clamp("é");
550 assert_eq!((e.cursor, e.anchor), (2, 2));
551 let mut e = Edit { cursor: 1, ..Default::default() };
552 e.clamp("é");
553 assert_eq!(e.cursor, 0);
554 }
555
556 #[test]
557 fn typing_runs_undo_in_one_step() {
558 let mut h = History::default();
559 let mut s = String::new();
560 let mut e = Edit::default();
561 for (i, c) in "ab".chars().enumerate() {
562 h.record(Kind::Insert, &s, &e, i as f64 * 0.1);
563 e.replace(&mut s, &c.to_string());
564 h.caret = e.cursor;
565 }
566 h.record(Kind::Insert, &s, &e, 5.0);
568 e.replace(&mut s, "c");
569 h.caret = e.cursor;
570 assert_eq!(s, "abc");
571 assert!(h.step(false, &mut s, &mut e));
572 assert_eq!((s.as_str(), e.cursor), ("ab", 2));
573 assert!(h.step(false, &mut s, &mut e));
574 assert_eq!(s, "");
575 assert!(!h.step(false, &mut s, &mut e));
576 assert!(h.step(true, &mut s, &mut e));
577 assert!(h.step(true, &mut s, &mut e));
578 assert_eq!(s, "abc");
579 }
580}