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