Skip to main content

iced_cube/forms/
textarea.rs

1//! Multi-line text editing.
2//!
3//! A tap places the caret and a vertical drag scrolls the text, as with the
4//! mouse, so a textarea works on a touch screen.
5//!
6//! Undo, redo, word deletion and Escape follow the same [`Shortcut`]s as
7//! inputs. Undo sends ordinary [`Action`]s, so an app that applies each
8//! action to its [`Content`] needs no changes. Switch some or all of them
9//! off by passing a [`Shortcuts`] set to [`Textarea::shortcuts`].
10//!
11//! [`Shortcut`]: input::Shortcut
12//!
13//! The app owns the [`Content`] and applies each [`Action`] in `update`:
14//!
15//! ```no_run
16//! use iced::widget::text_editor::{Action, Content};
17//! use iced_cube::textarea;
18//!
19//! #[derive(Debug, Clone)]
20//! enum Message { Edit(Action) }
21//!
22//! let content = Content::new();
23//! let view: iced::Element<'_, Message> = textarea(&content)
24//!     .placeholder("Write a note")
25//!     .on_action(Message::Edit)
26//!     .into();
27//! ```
28
29use std::cell::Cell;
30use std::fmt;
31use std::rc::Rc;
32use std::sync::Arc;
33
34use iced::advanced::layout::{self, Layout};
35use iced::advanced::text::highlighter::PlainText;
36use iced::advanced::widget::{Operation, Tree, Widget, operation, tree};
37use iced::advanced::{Clipboard, Shell, input_method, overlay, renderer};
38use iced::widget::text::LineHeight;
39use iced::widget::text_editor::{self, Edit, Motion, Status, Style};
40use iced::widget::{Id, container, text_input};
41use iced::{
42    Color, Element, Event, Length, Padding, Rectangle, Renderer, Size, Theme, Vector, mouse,
43};
44
45pub use iced::widget::text_editor::{Action, Content};
46
47use crate::editing::{self, Direction, Editing, Restore};
48use crate::keys::Keymap;
49use crate::primitives::input;
50pub use crate::primitives::input::{Shortcut, Shortcuts};
51use crate::primitives::touch_clicks::touch_clicks;
52use crate::theme::{Tokens, space, text_size};
53
54/// Minimum height while the height is [`Length::Shrink`], roughly three lines.
55pub const MIN_HEIGHT: f32 = 80.0;
56/// Line height as a multiple of the text size.
57const LINE_HEIGHT: f32 = 1.5;
58
59/// A textarea builder. Convert it into an [`Element`] to render.
60///
61/// A textarea without an `on_action` message is rendered disabled.
62pub struct Textarea<'a, Message> {
63    content: &'a Content,
64    placeholder: Option<iced::widget::text::Fragment<'a>>,
65    id: Option<Id>,
66    on_action: Option<Box<dyn Fn(Action) -> Message + 'a>>,
67    invalid: bool,
68    width: Length,
69    height: Length,
70    min_height: f32,
71    shortcuts: Shortcuts,
72    keymap: Keymap<input::Shortcut>,
73}
74
75/// Creates a textarea editing `content`.
76pub fn textarea<'a, Message>(content: &'a Content) -> Textarea<'a, Message> {
77    Textarea {
78        content,
79        placeholder: None,
80        id: None,
81        on_action: None,
82        invalid: false,
83        width: Length::Fill,
84        height: Length::Shrink,
85        min_height: MIN_HEIGHT,
86        shortcuts: Shortcuts::all(),
87        keymap: input::default_keymap(),
88    }
89}
90
91impl<'a, Message> Textarea<'a, Message> {
92    pub fn placeholder(mut self, placeholder: impl iced::widget::text::IntoFragment<'a>) -> Self {
93        self.placeholder = Some(placeholder.into_fragment());
94        self
95    }
96
97    /// Sets the widget id, used to focus the textarea or find it in tests.
98    pub fn id(mut self, id: impl Into<Id>) -> Self {
99        self.id = Some(id.into());
100        self
101    }
102
103    /// Sets the message produced for every edit. Without it the textarea is disabled.
104    pub fn on_action(mut self, on_action: impl Fn(Action) -> Message + 'a) -> Self {
105        self.on_action = Some(Box::new(on_action));
106        self
107    }
108
109    pub fn on_action_maybe(mut self, on_action: Option<impl Fn(Action) -> Message + 'a>) -> Self {
110        self.on_action = on_action.map(|f| Box::new(f) as Box<dyn Fn(Action) -> Message + 'a>);
111        self
112    }
113
114    /// Marks the value as invalid, drawing a destructive border.
115    pub fn invalid(mut self, invalid: bool) -> Self {
116        self.invalid = invalid;
117        self
118    }
119
120    /// Overrides the width. Textareas fill the available width by default.
121    pub fn width(mut self, width: impl Into<Length>) -> Self {
122        self.width = width.into();
123        self
124    }
125
126    /// Sets the height. The default shrinks to the content and grows as
127    /// lines are added, starting at [`MIN_HEIGHT`].
128    pub fn height(mut self, height: impl Into<Length>) -> Self {
129        self.height = height.into();
130        self
131    }
132
133    /// Sets the minimum height used while the height is [`Length::Shrink`].
134    pub fn min_height(mut self, min_height: f32) -> Self {
135        self.min_height = min_height.max(0.0);
136        self
137    }
138
139    /// Sets which [`Shortcut`]s the textarea handles. All
140    /// of them by default; pass [`Shortcuts::none`] to turn them all off.
141    /// The keys of a shortcut that is off reach the app, and iced's own
142    /// editing keys always work.
143    pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
144        self.shortcuts = shortcuts;
145        self
146    }
147
148    /// Replaces the [`input::default_keymap`], to bind the shortcuts to
149    /// other keys.
150    pub fn keymap(mut self, keymap: Keymap<input::Shortcut>) -> Self {
151        self.keymap = keymap;
152        self
153    }
154
155    pub fn is_enabled(&self) -> bool {
156        self.on_action.is_some()
157    }
158}
159
160impl<Message> fmt::Debug for Textarea<'_, Message> {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        f.debug_struct("Textarea")
163            .field("placeholder", &self.placeholder)
164            .field("id", &self.id)
165            .field("enabled", &self.is_enabled())
166            .field("invalid", &self.invalid)
167            .field("width", &self.width)
168            .field("height", &self.height)
169            .field("min_height", &self.min_height)
170            .field("shortcuts", &self.shortcuts)
171            .field("keymap", &self.keymap)
172            .finish()
173    }
174}
175
176impl<'a, Message: Clone + 'a> From<Textarea<'a, Message>> for Element<'a, Message> {
177    fn from(textarea: Textarea<'a, Message>) -> Self {
178        let invalid = textarea.invalid;
179        let enabled = textarea.is_enabled();
180        let composing = Rc::new(Cell::new(false));
181        let hide_placeholder = Rc::clone(&composing);
182
183        // iced never reports Disabled for an editor without `on_action`.
184        let mut editor = iced::widget::text_editor(textarea.content)
185            .size(text_size::SM)
186            .line_height(LineHeight::Relative(LINE_HEIGHT))
187            .padding(Padding::from([space::SM, space::MD]))
188            .height(textarea.height)
189            .style(move |theme, status| {
190                let status = if enabled { status } else { Status::Disabled };
191                let mut style = style(&Tokens::of(theme), status, invalid);
192                // The keyboard draws the word it is composing over the
193                // editor, so the placeholder would show through it.
194                if hide_placeholder.get() && matches!(status, Status::Focused { .. }) {
195                    style.placeholder = Color::TRANSPARENT;
196                }
197                style
198            });
199        if textarea.height == Length::Shrink {
200            editor = editor.min_height(textarea.min_height);
201        }
202        #[cfg(feature = "icedwright")]
203        let placeholder = textarea.placeholder.clone();
204        if let Some(placeholder) = textarea.placeholder {
205            editor = editor.placeholder(placeholder);
206        }
207        if let Some(id) = textarea.id {
208            editor = editor.id(id);
209        }
210        let on_action: Option<Rc<dyn Fn(Action) -> Message + 'a>> =
211            textarea.on_action.map(Rc::from);
212        let edited = Rc::new(Cell::new(false));
213        if let Some(on_action) = on_action.clone() {
214            let edited = Rc::clone(&edited);
215            editor = editor.on_action(move |action| {
216                if action.is_edit() {
217                    edited.set(true);
218                }
219                on_action(action)
220            });
221        }
222
223        let mut editor = Element::new(Composing {
224            content: editor.into(),
225            composing,
226        });
227        if let Some(on_action) = on_action {
228            let field = Editor {
229                content: textarea.content,
230                on_action,
231            };
232            editor =
233                Editing::new(editor, field, textarea.keymap, textarea.shortcuts, edited).into();
234        }
235
236        // iced's editor reads only the mouse, so taps and drags are
237        // translated for it.
238        let element: Element<'a, Message> = touch_clicks(container(editor).width(textarea.width))
239            .scroll(true)
240            .line_height(text_size::SM * LINE_HEIGHT)
241            .into();
242        #[cfg(feature = "icedwright")]
243        let element = {
244            use icedwright_probe::{CaretClock, role, semantic};
245            let mut annotated = semantic(element)
246                .role(role::TextBox)
247                .multiline(true)
248                .value(textarea.content.text())
249                .caret_clock(CaretClock::Iced)
250                .component("iced_cube::textarea");
251            if let Some(placeholder) = placeholder {
252                annotated = annotated.placeholder(placeholder);
253            }
254            if !enabled {
255                annotated = annotated.disabled(true);
256            }
257            if invalid {
258                annotated = annotated.invalid(true);
259            }
260            annotated.into()
261        };
262        element
263    }
264}
265
266/// Tracks whether the input method is composing a word, which iced's editor
267/// does not consider when it draws its placeholder.
268struct Composing<'a, Message> {
269    content: Element<'a, Message>,
270    composing: Rc<Cell<bool>>,
271}
272
273impl<Message> Widget<Message, Theme, Renderer> for Composing<'_, Message> {
274    fn tag(&self) -> tree::Tag {
275        tree::Tag::of::<bool>()
276    }
277
278    fn state(&self) -> tree::State {
279        tree::State::new(false)
280    }
281
282    fn children(&self) -> Vec<Tree> {
283        vec![Tree::new(&self.content)]
284    }
285
286    fn diff(&self, tree: &mut Tree) {
287        tree.diff_children(std::slice::from_ref(&self.content));
288    }
289
290    fn size(&self) -> Size<Length> {
291        self.content.as_widget().size()
292    }
293
294    fn size_hint(&self) -> Size<Length> {
295        self.content.as_widget().size_hint()
296    }
297
298    fn layout(
299        &mut self,
300        tree: &mut Tree,
301        renderer: &Renderer,
302        limits: &layout::Limits,
303    ) -> layout::Node {
304        self.content
305            .as_widget_mut()
306            .layout(&mut tree.children[0], renderer, limits)
307    }
308
309    fn draw(
310        &self,
311        tree: &Tree,
312        renderer: &mut Renderer,
313        theme: &Theme,
314        style: &renderer::Style,
315        layout: Layout<'_>,
316        cursor: mouse::Cursor,
317        viewport: &Rectangle,
318    ) {
319        self.composing.set(*tree.state.downcast_ref::<bool>());
320        self.content.as_widget().draw(
321            &tree.children[0],
322            renderer,
323            theme,
324            style,
325            layout,
326            cursor,
327            viewport,
328        );
329    }
330
331    fn operate(
332        &mut self,
333        tree: &mut Tree,
334        layout: Layout<'_>,
335        renderer: &Renderer,
336        operation: &mut dyn Operation,
337    ) {
338        self.content
339            .as_widget_mut()
340            .operate(&mut tree.children[0], layout, renderer, operation);
341    }
342
343    fn update(
344        &mut self,
345        tree: &mut Tree,
346        event: &Event,
347        layout: Layout<'_>,
348        cursor: mouse::Cursor,
349        renderer: &Renderer,
350        clipboard: &mut dyn Clipboard,
351        shell: &mut Shell<'_, Message>,
352        viewport: &Rectangle,
353    ) {
354        // Mirrors the editor, which keeps a composing word only while focused,
355        // so a word composed in another field is never counted.
356        if let Event::InputMethod(event) = event {
357            match event {
358                input_method::Event::Opened | input_method::Event::Closed => {
359                    *tree.state.downcast_mut::<bool>() = false;
360                }
361                input_method::Event::Preedit(text, _) if editor_focused(&tree.children[0]) => {
362                    *tree.state.downcast_mut::<bool>() = !text.is_empty();
363                }
364                _ => {}
365            }
366        }
367        self.content.as_widget_mut().update(
368            &mut tree.children[0],
369            event,
370            layout,
371            cursor,
372            renderer,
373            clipboard,
374            shell,
375            viewport,
376        );
377    }
378
379    fn mouse_interaction(
380        &self,
381        tree: &Tree,
382        layout: Layout<'_>,
383        cursor: mouse::Cursor,
384        viewport: &Rectangle,
385        renderer: &Renderer,
386    ) -> mouse::Interaction {
387        self.content.as_widget().mouse_interaction(
388            &tree.children[0],
389            layout,
390            cursor,
391            viewport,
392            renderer,
393        )
394    }
395
396    fn overlay<'b>(
397        &'b mut self,
398        tree: &'b mut Tree,
399        layout: Layout<'b>,
400        renderer: &Renderer,
401        viewport: &Rectangle,
402        translation: Vector,
403    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
404        self.content.as_widget_mut().overlay(
405            &mut tree.children[0],
406            layout,
407            renderer,
408            viewport,
409            translation,
410        )
411    }
412}
413
414fn editor_focused(tree: &Tree) -> bool {
415    let tree::State::Some(state) = &tree.state else {
416        return false;
417    };
418    state
419        .downcast_ref::<text_editor::State<PlainText>>()
420        .is_some_and(text_editor::State::is_focused)
421}
422
423/// The editor as seen by the editing shortcuts. Its tree is the
424/// [`Composing`] wrapper's.
425struct Editor<'a, Message> {
426    content: &'a Content,
427    on_action: Rc<dyn Fn(Action) -> Message + 'a>,
428}
429
430impl<Message> editing::Field<Message> for Editor<'_, Message> {
431    fn text(&self) -> String {
432        self.content.text()
433    }
434
435    fn is_focused(&self, tree: &Tree) -> bool {
436        tree.children.first().is_some_and(editor_focused)
437    }
438
439    fn has_selection(&self, _tree: &Tree) -> bool {
440        self.content.cursor().selection.is_some()
441    }
442
443    fn restore(&self, _tree: &mut Tree, restore: Restore, shell: &mut Shell<'_, Message>) {
444        let (head, tail) = restore
445            .text
446            .split_at_checked(restore.caret)
447            .unwrap_or((restore.text.as_str(), ""));
448        // Pasting the text after the caret first, then the text before it
449        // from the start, leaves the caret exactly where it belongs.
450        for action in [
451            Action::SelectAll,
452            Action::Edit(Edit::Paste(Arc::new(tail.to_owned()))),
453            Action::Move(Motion::DocumentStart),
454            Action::Edit(Edit::Paste(Arc::new(head.to_owned()))),
455        ] {
456            shell.publish((self.on_action)(action));
457        }
458    }
459
460    fn delete_word(
461        &self,
462        tree: &mut Tree,
463        direction: Direction,
464        shell: &mut Shell<'_, Message>,
465    ) -> bool {
466        let (motion, edit) = match direction {
467            Direction::Backward => (Motion::WordLeft, Edit::Backspace),
468            Direction::Forward => (Motion::WordRight, Edit::Delete),
469        };
470        if !self.has_selection(tree) {
471            shell.publish((self.on_action)(Action::Select(motion)));
472        }
473        shell.publish((self.on_action)(Action::Edit(edit)));
474        true
475    }
476
477    fn unfocus(&self, tree: &mut Tree) {
478        let Some(tree::State::Some(state)) = tree.children.first_mut().map(|tree| &mut tree.state)
479        else {
480            return;
481        };
482        if let Some(state) = state.downcast_mut::<text_editor::State<PlainText>>() {
483            operation::Focusable::unfocus(state);
484        }
485    }
486}
487
488/// The iced text editor style for a status, matching the input's look.
489pub fn style(tokens: &Tokens, status: Status, invalid: bool) -> Style {
490    let status = match status {
491        Status::Active => text_input::Status::Active,
492        Status::Hovered => text_input::Status::Hovered,
493        Status::Focused { is_hovered } => text_input::Status::Focused { is_hovered },
494        Status::Disabled => text_input::Status::Disabled,
495    };
496    let style = input::style(tokens, status, invalid);
497
498    text_editor::Style {
499        background: style.background,
500        border: style.border,
501        placeholder: style.placeholder,
502        value: style.value,
503        selection: style.selection,
504    }
505}
506
507#[cfg(test)]
508mod tests {
509    use super::*;
510    use crate::theme::{dark, light};
511
512    const STATES: [Status; 5] = [
513        Status::Active,
514        Status::Hovered,
515        Status::Focused { is_hovered: false },
516        Status::Focused { is_hovered: true },
517        Status::Disabled,
518    ];
519
520    #[test]
521    fn default_builder_shrinks_with_minimum_and_is_disabled() {
522        let content = Content::new();
523        let t: Textarea<'_, ()> = textarea(&content);
524        assert_eq!(t.height, Length::Shrink);
525        assert_eq!(t.width, Length::Fill);
526        assert_eq!(t.min_height, MIN_HEIGHT);
527        assert!(t.placeholder.is_none() && !t.invalid);
528        assert!(!t.is_enabled());
529        assert_eq!(t.shortcuts, Shortcuts::all());
530        assert_eq!(t.keymap, input::default_keymap());
531        let off: Textarea<'_, ()> = textarea(&content).shortcuts(Shortcuts::none());
532        assert_eq!(off.shortcuts, Shortcuts::none());
533    }
534
535    #[test]
536    fn on_action_enables_and_none_disables() {
537        let content = Content::new();
538        assert!(textarea::<Action>(&content).on_action(|a| a).is_enabled());
539        let none: Option<fn(Action) -> Action> = None;
540        assert!(
541            !textarea::<Action>(&content)
542                .on_action(|a| a)
543                .on_action_maybe(none)
544                .is_enabled()
545        );
546    }
547
548    #[test]
549    fn negative_min_height_clamps_to_zero() {
550        let content = Content::new();
551        let t: Textarea<'_, ()> = textarea(&content).min_height(-5.0);
552        assert_eq!(t.min_height, 0.0);
553    }
554
555    #[test]
556    fn style_matches_input_for_every_status() {
557        for theme in [light(), dark()] {
558            let tokens = Tokens::of(&theme);
559            for (editor, field) in STATES.into_iter().zip([
560                text_input::Status::Active,
561                text_input::Status::Hovered,
562                text_input::Status::Focused { is_hovered: false },
563                text_input::Status::Focused { is_hovered: true },
564                text_input::Status::Disabled,
565            ]) {
566                for invalid in [false, true] {
567                    let a = style(&tokens, editor, invalid);
568                    let b = input::style(&tokens, field, invalid);
569                    assert_eq!(a.border, b.border, "{editor:?}");
570                    assert_eq!(a.background, b.background);
571                    assert_eq!(a.value, b.value);
572                    assert_eq!(a.placeholder, b.placeholder);
573                }
574            }
575        }
576    }
577
578    #[test]
579    fn invalid_and_disabled_are_distinct_from_active() {
580        let tokens = Tokens::of(&light());
581        let active = style(&tokens, Status::Active, false);
582        assert_ne!(style(&tokens, Status::Active, true).border, active.border);
583        assert_ne!(style(&tokens, Status::Disabled, false).value, active.value);
584    }
585}