1use 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
54pub const MIN_HEIGHT: f32 = 80.0;
56const LINE_HEIGHT: f32 = 1.5;
58
59pub 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
75pub 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 pub fn id(mut self, id: impl Into<Id>) -> Self {
99 self.id = Some(id.into());
100 self
101 }
102
103 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 pub fn invalid(mut self, invalid: bool) -> Self {
116 self.invalid = invalid;
117 self
118 }
119
120 pub fn width(mut self, width: impl Into<Length>) -> Self {
122 self.width = width.into();
123 self
124 }
125
126 pub fn height(mut self, height: impl Into<Length>) -> Self {
129 self.height = height.into();
130 self
131 }
132
133 pub fn min_height(mut self, min_height: f32) -> Self {
135 self.min_height = min_height.max(0.0);
136 self
137 }
138
139 pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
144 self.shortcuts = shortcuts;
145 self
146 }
147
148 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 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 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 if let Some(placeholder) = textarea.placeholder {
203 editor = editor.placeholder(placeholder);
204 }
205 if let Some(id) = textarea.id {
206 editor = editor.id(id);
207 }
208 let on_action: Option<Rc<dyn Fn(Action) -> Message + 'a>> =
209 textarea.on_action.map(Rc::from);
210 let edited = Rc::new(Cell::new(false));
211 if let Some(on_action) = on_action.clone() {
212 let edited = Rc::clone(&edited);
213 editor = editor.on_action(move |action| {
214 edited.set(true);
215 on_action(action)
216 });
217 }
218
219 let mut editor = Element::new(Composing {
220 content: editor.into(),
221 composing,
222 });
223 if let Some(on_action) = on_action {
224 let field = Editor {
225 content: textarea.content,
226 on_action,
227 };
228 editor =
229 Editing::new(editor, field, textarea.keymap, textarea.shortcuts, edited).into();
230 }
231
232 touch_clicks(container(editor).width(textarea.width))
235 .scroll(true)
236 .line_height(text_size::SM * LINE_HEIGHT)
237 .into()
238 }
239}
240
241struct Composing<'a, Message> {
244 content: Element<'a, Message>,
245 composing: Rc<Cell<bool>>,
246}
247
248impl<Message> Widget<Message, Theme, Renderer> for Composing<'_, Message> {
249 fn tag(&self) -> tree::Tag {
250 tree::Tag::of::<bool>()
251 }
252
253 fn state(&self) -> tree::State {
254 tree::State::new(false)
255 }
256
257 fn children(&self) -> Vec<Tree> {
258 vec![Tree::new(&self.content)]
259 }
260
261 fn diff(&self, tree: &mut Tree) {
262 tree.diff_children(std::slice::from_ref(&self.content));
263 }
264
265 fn size(&self) -> Size<Length> {
266 self.content.as_widget().size()
267 }
268
269 fn size_hint(&self) -> Size<Length> {
270 self.content.as_widget().size_hint()
271 }
272
273 fn layout(
274 &mut self,
275 tree: &mut Tree,
276 renderer: &Renderer,
277 limits: &layout::Limits,
278 ) -> layout::Node {
279 self.content
280 .as_widget_mut()
281 .layout(&mut tree.children[0], renderer, limits)
282 }
283
284 fn draw(
285 &self,
286 tree: &Tree,
287 renderer: &mut Renderer,
288 theme: &Theme,
289 style: &renderer::Style,
290 layout: Layout<'_>,
291 cursor: mouse::Cursor,
292 viewport: &Rectangle,
293 ) {
294 self.composing.set(*tree.state.downcast_ref::<bool>());
295 self.content.as_widget().draw(
296 &tree.children[0],
297 renderer,
298 theme,
299 style,
300 layout,
301 cursor,
302 viewport,
303 );
304 }
305
306 fn operate(
307 &mut self,
308 tree: &mut Tree,
309 layout: Layout<'_>,
310 renderer: &Renderer,
311 operation: &mut dyn Operation,
312 ) {
313 self.content
314 .as_widget_mut()
315 .operate(&mut tree.children[0], layout, renderer, operation);
316 }
317
318 fn update(
319 &mut self,
320 tree: &mut Tree,
321 event: &Event,
322 layout: Layout<'_>,
323 cursor: mouse::Cursor,
324 renderer: &Renderer,
325 clipboard: &mut dyn Clipboard,
326 shell: &mut Shell<'_, Message>,
327 viewport: &Rectangle,
328 ) {
329 if let Event::InputMethod(event) = event {
332 match event {
333 input_method::Event::Opened | input_method::Event::Closed => {
334 *tree.state.downcast_mut::<bool>() = false;
335 }
336 input_method::Event::Preedit(text, _) if editor_focused(&tree.children[0]) => {
337 *tree.state.downcast_mut::<bool>() = !text.is_empty();
338 }
339 _ => {}
340 }
341 }
342 self.content.as_widget_mut().update(
343 &mut tree.children[0],
344 event,
345 layout,
346 cursor,
347 renderer,
348 clipboard,
349 shell,
350 viewport,
351 );
352 }
353
354 fn mouse_interaction(
355 &self,
356 tree: &Tree,
357 layout: Layout<'_>,
358 cursor: mouse::Cursor,
359 viewport: &Rectangle,
360 renderer: &Renderer,
361 ) -> mouse::Interaction {
362 self.content.as_widget().mouse_interaction(
363 &tree.children[0],
364 layout,
365 cursor,
366 viewport,
367 renderer,
368 )
369 }
370
371 fn overlay<'b>(
372 &'b mut self,
373 tree: &'b mut Tree,
374 layout: Layout<'b>,
375 renderer: &Renderer,
376 viewport: &Rectangle,
377 translation: Vector,
378 ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
379 self.content.as_widget_mut().overlay(
380 &mut tree.children[0],
381 layout,
382 renderer,
383 viewport,
384 translation,
385 )
386 }
387}
388
389fn editor_focused(tree: &Tree) -> bool {
390 let tree::State::Some(state) = &tree.state else {
391 return false;
392 };
393 state
394 .downcast_ref::<text_editor::State<PlainText>>()
395 .is_some_and(text_editor::State::is_focused)
396}
397
398struct Editor<'a, Message> {
401 content: &'a Content,
402 on_action: Rc<dyn Fn(Action) -> Message + 'a>,
403}
404
405impl<Message> editing::Field<Message> for Editor<'_, Message> {
406 fn text(&self) -> String {
407 self.content.text()
408 }
409
410 fn is_focused(&self, tree: &Tree) -> bool {
411 tree.children.first().is_some_and(editor_focused)
412 }
413
414 fn has_selection(&self, _tree: &Tree) -> bool {
415 self.content.cursor().selection.is_some()
416 }
417
418 fn restore(&self, _tree: &mut Tree, restore: Restore, shell: &mut Shell<'_, Message>) {
419 let (head, tail) = restore
420 .text
421 .split_at_checked(restore.caret)
422 .unwrap_or((restore.text.as_str(), ""));
423 for action in [
426 Action::SelectAll,
427 Action::Edit(Edit::Paste(Arc::new(tail.to_owned()))),
428 Action::Move(Motion::DocumentStart),
429 Action::Edit(Edit::Paste(Arc::new(head.to_owned()))),
430 ] {
431 shell.publish((self.on_action)(action));
432 }
433 }
434
435 fn delete_word(
436 &self,
437 tree: &mut Tree,
438 direction: Direction,
439 shell: &mut Shell<'_, Message>,
440 ) -> bool {
441 let (motion, edit) = match direction {
442 Direction::Backward => (Motion::WordLeft, Edit::Backspace),
443 Direction::Forward => (Motion::WordRight, Edit::Delete),
444 };
445 if !self.has_selection(tree) {
446 shell.publish((self.on_action)(Action::Select(motion)));
447 }
448 shell.publish((self.on_action)(Action::Edit(edit)));
449 true
450 }
451
452 fn unfocus(&self, tree: &mut Tree) {
453 let Some(tree::State::Some(state)) = tree.children.first_mut().map(|tree| &mut tree.state)
454 else {
455 return;
456 };
457 if let Some(state) = state.downcast_mut::<text_editor::State<PlainText>>() {
458 operation::Focusable::unfocus(state);
459 }
460 }
461}
462
463pub fn style(tokens: &Tokens, status: Status, invalid: bool) -> Style {
465 let status = match status {
466 Status::Active => text_input::Status::Active,
467 Status::Hovered => text_input::Status::Hovered,
468 Status::Focused { is_hovered } => text_input::Status::Focused { is_hovered },
469 Status::Disabled => text_input::Status::Disabled,
470 };
471 let style = input::style(tokens, status, invalid);
472
473 text_editor::Style {
474 background: style.background,
475 border: style.border,
476 placeholder: style.placeholder,
477 value: style.value,
478 selection: style.selection,
479 }
480}
481
482#[cfg(test)]
483mod tests {
484 use super::*;
485 use crate::theme::{dark, light};
486
487 const STATES: [Status; 5] = [
488 Status::Active,
489 Status::Hovered,
490 Status::Focused { is_hovered: false },
491 Status::Focused { is_hovered: true },
492 Status::Disabled,
493 ];
494
495 #[test]
496 fn default_builder_shrinks_with_minimum_and_is_disabled() {
497 let content = Content::new();
498 let t: Textarea<'_, ()> = textarea(&content);
499 assert_eq!(t.height, Length::Shrink);
500 assert_eq!(t.width, Length::Fill);
501 assert_eq!(t.min_height, MIN_HEIGHT);
502 assert!(t.placeholder.is_none() && !t.invalid);
503 assert!(!t.is_enabled());
504 assert_eq!(t.shortcuts, Shortcuts::all());
505 assert_eq!(t.keymap, input::default_keymap());
506 let off: Textarea<'_, ()> = textarea(&content).shortcuts(Shortcuts::none());
507 assert_eq!(off.shortcuts, Shortcuts::none());
508 }
509
510 #[test]
511 fn on_action_enables_and_none_disables() {
512 let content = Content::new();
513 assert!(textarea::<Action>(&content).on_action(|a| a).is_enabled());
514 let none: Option<fn(Action) -> Action> = None;
515 assert!(
516 !textarea::<Action>(&content)
517 .on_action(|a| a)
518 .on_action_maybe(none)
519 .is_enabled()
520 );
521 }
522
523 #[test]
524 fn negative_min_height_clamps_to_zero() {
525 let content = Content::new();
526 let t: Textarea<'_, ()> = textarea(&content).min_height(-5.0);
527 assert_eq!(t.min_height, 0.0);
528 }
529
530 #[test]
531 fn style_matches_input_for_every_status() {
532 for theme in [light(), dark()] {
533 let tokens = Tokens::of(&theme);
534 for (editor, field) in STATES.into_iter().zip([
535 text_input::Status::Active,
536 text_input::Status::Hovered,
537 text_input::Status::Focused { is_hovered: false },
538 text_input::Status::Focused { is_hovered: true },
539 text_input::Status::Disabled,
540 ]) {
541 for invalid in [false, true] {
542 let a = style(&tokens, editor, invalid);
543 let b = input::style(&tokens, field, invalid);
544 assert_eq!(a.border, b.border, "{editor:?}");
545 assert_eq!(a.background, b.background);
546 assert_eq!(a.value, b.value);
547 assert_eq!(a.placeholder, b.placeholder);
548 }
549 }
550 }
551 }
552
553 #[test]
554 fn invalid_and_disabled_are_distinct_from_active() {
555 let tokens = Tokens::of(&light());
556 let active = style(&tokens, Status::Active, false);
557 assert_ne!(style(&tokens, Status::Active, true).border, active.border);
558 assert_ne!(style(&tokens, Status::Disabled, false).value, active.value);
559 }
560}