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                .disabled(!enabled)
251                .component("iced_cube::textarea");
252            if let Some(placeholder) = placeholder {
253                annotated = annotated.placeholder(placeholder);
254            }
255            if invalid {
256                annotated = annotated.invalid(true);
257            }
258            annotated.into()
259        };
260        element
261    }
262}
263
264/// Tracks whether the input method is composing a word, which iced's editor
265/// does not consider when it draws its placeholder.
266struct Composing<'a, Message> {
267    content: Element<'a, Message>,
268    composing: Rc<Cell<bool>>,
269}
270
271impl<Message> Widget<Message, Theme, Renderer> for Composing<'_, Message> {
272    fn tag(&self) -> tree::Tag {
273        tree::Tag::of::<bool>()
274    }
275
276    fn state(&self) -> tree::State {
277        tree::State::new(false)
278    }
279
280    fn children(&self) -> Vec<Tree> {
281        vec![Tree::new(&self.content)]
282    }
283
284    fn diff(&self, tree: &mut Tree) {
285        tree.diff_children(std::slice::from_ref(&self.content));
286    }
287
288    fn size(&self) -> Size<Length> {
289        self.content.as_widget().size()
290    }
291
292    fn size_hint(&self) -> Size<Length> {
293        self.content.as_widget().size_hint()
294    }
295
296    fn layout(
297        &mut self,
298        tree: &mut Tree,
299        renderer: &Renderer,
300        limits: &layout::Limits,
301    ) -> layout::Node {
302        self.content
303            .as_widget_mut()
304            .layout(&mut tree.children[0], renderer, limits)
305    }
306
307    fn draw(
308        &self,
309        tree: &Tree,
310        renderer: &mut Renderer,
311        theme: &Theme,
312        style: &renderer::Style,
313        layout: Layout<'_>,
314        cursor: mouse::Cursor,
315        viewport: &Rectangle,
316    ) {
317        self.composing.set(*tree.state.downcast_ref::<bool>());
318        self.content.as_widget().draw(
319            &tree.children[0],
320            renderer,
321            theme,
322            style,
323            layout,
324            cursor,
325            viewport,
326        );
327    }
328
329    fn operate(
330        &mut self,
331        tree: &mut Tree,
332        layout: Layout<'_>,
333        renderer: &Renderer,
334        operation: &mut dyn Operation,
335    ) {
336        self.content
337            .as_widget_mut()
338            .operate(&mut tree.children[0], layout, renderer, operation);
339    }
340
341    fn update(
342        &mut self,
343        tree: &mut Tree,
344        event: &Event,
345        layout: Layout<'_>,
346        cursor: mouse::Cursor,
347        renderer: &Renderer,
348        clipboard: &mut dyn Clipboard,
349        shell: &mut Shell<'_, Message>,
350        viewport: &Rectangle,
351    ) {
352        // Mirrors the editor, which keeps a composing word only while focused,
353        // so a word composed in another field is never counted.
354        if let Event::InputMethod(event) = event {
355            match event {
356                input_method::Event::Opened | input_method::Event::Closed => {
357                    *tree.state.downcast_mut::<bool>() = false;
358                }
359                input_method::Event::Preedit(text, _) if editor_focused(&tree.children[0]) => {
360                    *tree.state.downcast_mut::<bool>() = !text.is_empty();
361                }
362                _ => {}
363            }
364        }
365        self.content.as_widget_mut().update(
366            &mut tree.children[0],
367            event,
368            layout,
369            cursor,
370            renderer,
371            clipboard,
372            shell,
373            viewport,
374        );
375    }
376
377    fn mouse_interaction(
378        &self,
379        tree: &Tree,
380        layout: Layout<'_>,
381        cursor: mouse::Cursor,
382        viewport: &Rectangle,
383        renderer: &Renderer,
384    ) -> mouse::Interaction {
385        self.content.as_widget().mouse_interaction(
386            &tree.children[0],
387            layout,
388            cursor,
389            viewport,
390            renderer,
391        )
392    }
393
394    fn overlay<'b>(
395        &'b mut self,
396        tree: &'b mut Tree,
397        layout: Layout<'b>,
398        renderer: &Renderer,
399        viewport: &Rectangle,
400        translation: Vector,
401    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
402        self.content.as_widget_mut().overlay(
403            &mut tree.children[0],
404            layout,
405            renderer,
406            viewport,
407            translation,
408        )
409    }
410}
411
412fn editor_focused(tree: &Tree) -> bool {
413    let tree::State::Some(state) = &tree.state else {
414        return false;
415    };
416    state
417        .downcast_ref::<text_editor::State<PlainText>>()
418        .is_some_and(text_editor::State::is_focused)
419}
420
421/// The editor as seen by the editing shortcuts. Its tree is the
422/// [`Composing`] wrapper's.
423struct Editor<'a, Message> {
424    content: &'a Content,
425    on_action: Rc<dyn Fn(Action) -> Message + 'a>,
426}
427
428impl<Message> editing::Field<Message> for Editor<'_, Message> {
429    fn text(&self) -> String {
430        self.content.text()
431    }
432
433    fn is_focused(&self, tree: &Tree) -> bool {
434        tree.children.first().is_some_and(editor_focused)
435    }
436
437    fn has_selection(&self, _tree: &Tree) -> bool {
438        self.content.cursor().selection.is_some()
439    }
440
441    fn restore(&self, _tree: &mut Tree, restore: Restore, shell: &mut Shell<'_, Message>) {
442        let (head, tail) = restore
443            .text
444            .split_at_checked(restore.caret)
445            .unwrap_or((restore.text.as_str(), ""));
446        // Pasting the text after the caret first, then the text before it
447        // from the start, leaves the caret exactly where it belongs.
448        for action in [
449            Action::SelectAll,
450            Action::Edit(Edit::Paste(Arc::new(tail.to_owned()))),
451            Action::Move(Motion::DocumentStart),
452            Action::Edit(Edit::Paste(Arc::new(head.to_owned()))),
453        ] {
454            shell.publish((self.on_action)(action));
455        }
456    }
457
458    fn delete_word(
459        &self,
460        tree: &mut Tree,
461        direction: Direction,
462        shell: &mut Shell<'_, Message>,
463    ) -> bool {
464        let (motion, edit) = match direction {
465            Direction::Backward => (Motion::WordLeft, Edit::Backspace),
466            Direction::Forward => (Motion::WordRight, Edit::Delete),
467        };
468        if !self.has_selection(tree) {
469            shell.publish((self.on_action)(Action::Select(motion)));
470        }
471        shell.publish((self.on_action)(Action::Edit(edit)));
472        true
473    }
474
475    fn unfocus(&self, tree: &mut Tree) {
476        let Some(tree::State::Some(state)) = tree.children.first_mut().map(|tree| &mut tree.state)
477        else {
478            return;
479        };
480        if let Some(state) = state.downcast_mut::<text_editor::State<PlainText>>() {
481            operation::Focusable::unfocus(state);
482        }
483    }
484}
485
486/// The iced text editor style for a status, matching the input's look.
487pub fn style(tokens: &Tokens, status: Status, invalid: bool) -> Style {
488    let status = match status {
489        Status::Active => text_input::Status::Active,
490        Status::Hovered => text_input::Status::Hovered,
491        Status::Focused { is_hovered } => text_input::Status::Focused { is_hovered },
492        Status::Disabled => text_input::Status::Disabled,
493    };
494    let style = input::style(tokens, status, invalid);
495
496    text_editor::Style {
497        background: style.background,
498        border: style.border,
499        placeholder: style.placeholder,
500        value: style.value,
501        selection: style.selection,
502    }
503}
504
505#[cfg(test)]
506mod tests {
507    use super::*;
508    use crate::theme::{dark, light};
509
510    const STATES: [Status; 5] = [
511        Status::Active,
512        Status::Hovered,
513        Status::Focused { is_hovered: false },
514        Status::Focused { is_hovered: true },
515        Status::Disabled,
516    ];
517
518    #[test]
519    fn default_builder_shrinks_with_minimum_and_is_disabled() {
520        let content = Content::new();
521        let t: Textarea<'_, ()> = textarea(&content);
522        assert_eq!(t.height, Length::Shrink);
523        assert_eq!(t.width, Length::Fill);
524        assert_eq!(t.min_height, MIN_HEIGHT);
525        assert!(t.placeholder.is_none() && !t.invalid);
526        assert!(!t.is_enabled());
527        assert_eq!(t.shortcuts, Shortcuts::all());
528        assert_eq!(t.keymap, input::default_keymap());
529        let off: Textarea<'_, ()> = textarea(&content).shortcuts(Shortcuts::none());
530        assert_eq!(off.shortcuts, Shortcuts::none());
531    }
532
533    #[test]
534    fn on_action_enables_and_none_disables() {
535        let content = Content::new();
536        assert!(textarea::<Action>(&content).on_action(|a| a).is_enabled());
537        let none: Option<fn(Action) -> Action> = None;
538        assert!(
539            !textarea::<Action>(&content)
540                .on_action(|a| a)
541                .on_action_maybe(none)
542                .is_enabled()
543        );
544    }
545
546    #[test]
547    fn negative_min_height_clamps_to_zero() {
548        let content = Content::new();
549        let t: Textarea<'_, ()> = textarea(&content).min_height(-5.0);
550        assert_eq!(t.min_height, 0.0);
551    }
552
553    #[test]
554    fn style_matches_input_for_every_status() {
555        for theme in [light(), dark()] {
556            let tokens = Tokens::of(&theme);
557            for (editor, field) in STATES.into_iter().zip([
558                text_input::Status::Active,
559                text_input::Status::Hovered,
560                text_input::Status::Focused { is_hovered: false },
561                text_input::Status::Focused { is_hovered: true },
562                text_input::Status::Disabled,
563            ]) {
564                for invalid in [false, true] {
565                    let a = style(&tokens, editor, invalid);
566                    let b = input::style(&tokens, field, invalid);
567                    assert_eq!(a.border, b.border, "{editor:?}");
568                    assert_eq!(a.background, b.background);
569                    assert_eq!(a.value, b.value);
570                    assert_eq!(a.placeholder, b.placeholder);
571                }
572            }
573        }
574    }
575
576    #[test]
577    fn invalid_and_disabled_are_distinct_from_active() {
578        let tokens = Tokens::of(&light());
579        let active = style(&tokens, Status::Active, false);
580        assert_ne!(style(&tokens, Status::Active, true).border, active.border);
581        assert_ne!(style(&tokens, Status::Disabled, false).value, active.value);
582    }
583}