1#![forbid(unsafe_code)]
2
3use crate::block::{Alignment, Block};
31use crate::borders::Borders;
32use crate::modal::{Modal, ModalConfig, ModalPosition, ModalSizeConstraints};
33use crate::{StatefulWidget, Widget, draw_text_span, set_style_area};
34use ftui_a11y::node::{A11yNodeInfo, A11yRole};
35use ftui_core::event::{
36 Event, KeyCode, KeyEvent, KeyEventKind, Modifiers, MouseButton, MouseEvent, MouseEventKind,
37};
38use ftui_core::geometry::Rect;
39use ftui_render::cell::Cell;
40use ftui_render::frame::{Frame, HitData, HitId, HitRegion};
41use ftui_style::{Style, StyleFlags};
42use ftui_text::display_width;
43use unicode_segmentation::UnicodeSegmentation;
44
45pub const DIALOG_HIT_BUTTON: HitRegion = HitRegion::Button;
47pub const DIALOG_HIT_INPUT: HitRegion = HitRegion::Custom(3);
57
58#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum DialogResult {
61 Dismissed,
63 Ok,
65 Cancel,
67 Custom(String),
69 Input(String),
71}
72
73#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct DialogButton {
76 pub label: String,
78 pub id: String,
80 pub primary: bool,
82}
83
84impl DialogButton {
85 pub fn new(label: impl Into<String>, id: impl Into<String>) -> Self {
87 Self {
88 label: label.into(),
89 id: id.into(),
90 primary: false,
91 }
92 }
93
94 #[must_use]
96 pub fn primary(mut self) -> Self {
97 self.primary = true;
98 self
99 }
100
101 pub fn display_width(&self) -> usize {
103 display_width(self.label.as_str()) + 4
105 }
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub enum DialogKind {
111 Alert,
113 Confirm,
115 Prompt,
117 Custom,
119}
120
121#[derive(Debug, Clone, Default)]
123pub struct DialogState {
124 pub focused_button: Option<usize>,
126 pressed_button: Option<usize>,
128 pub input_value: String,
130 pub input_focused: bool,
132 pub open: bool,
134 pub result: Option<DialogResult>,
136}
137
138impl DialogState {
139 pub fn new() -> Self {
141 Self {
142 open: true,
143 input_focused: true, ..Default::default()
145 }
146 }
147
148 #[inline]
150 pub fn is_open(&self) -> bool {
151 self.open
152 }
153
154 pub fn close(&mut self, result: DialogResult) {
156 self.open = false;
157 self.pressed_button = None;
158 self.result = Some(result);
159 }
160
161 pub fn reset(&mut self) {
163 self.open = true;
164 self.result = None;
165 self.input_value.clear();
166 self.focused_button = None;
167 self.pressed_button = None;
168 self.input_focused = true;
169 }
170
171 pub fn take_result(&mut self) -> Option<DialogResult> {
173 self.result.take()
174 }
175}
176
177#[derive(Debug, Clone)]
179pub struct DialogConfig {
180 pub modal_config: ModalConfig,
182 pub kind: DialogKind,
184 pub button_style: Style,
186 pub primary_button_style: Style,
188 pub focused_button_style: Style,
190 pub title_style: Style,
192 pub message_style: Style,
194 pub input_style: Style,
196}
197
198impl Default for DialogConfig {
199 fn default() -> Self {
200 Self {
201 modal_config: ModalConfig::default()
202 .position(ModalPosition::Center)
203 .size(ModalSizeConstraints::new().min_width(30).max_width(60)),
204 kind: DialogKind::Alert,
205 button_style: Style::new(),
206 primary_button_style: Style::new().bold(),
207 focused_button_style: Style::new().reverse(),
208 title_style: Style::new().bold(),
209 message_style: Style::new(),
210 input_style: Style::new(),
211 }
212 }
213}
214
215#[derive(Debug, Clone)]
226pub struct Dialog {
227 title: String,
229 message: String,
231 buttons: Vec<DialogButton>,
233 config: DialogConfig,
235 hit_id: Option<HitId>,
237}
238
239impl Dialog {
240 pub fn alert(title: impl Into<String>, message: impl Into<String>) -> Self {
242 Self {
243 title: title.into(),
244 message: message.into(),
245 buttons: vec![DialogButton::new("OK", "ok").primary()],
246 config: DialogConfig {
247 kind: DialogKind::Alert,
248 ..Default::default()
249 },
250 hit_id: None,
251 }
252 }
253
254 pub fn confirm(title: impl Into<String>, message: impl Into<String>) -> Self {
256 Self {
257 title: title.into(),
258 message: message.into(),
259 buttons: vec![
260 DialogButton::new("OK", "ok").primary(),
261 DialogButton::new("Cancel", "cancel"),
262 ],
263 config: DialogConfig {
264 kind: DialogKind::Confirm,
265 ..Default::default()
266 },
267 hit_id: None,
268 }
269 }
270
271 pub fn prompt(title: impl Into<String>, message: impl Into<String>) -> Self {
273 Self {
274 title: title.into(),
275 message: message.into(),
276 buttons: vec![
277 DialogButton::new("OK", "ok").primary(),
278 DialogButton::new("Cancel", "cancel"),
279 ],
280 config: DialogConfig {
281 kind: DialogKind::Prompt,
282 ..Default::default()
283 },
284 hit_id: None,
285 }
286 }
287
288 pub fn custom(title: impl Into<String>, message: impl Into<String>) -> DialogBuilder {
290 DialogBuilder {
291 title: title.into(),
292 message: message.into(),
293 buttons: Vec::new(),
294 config: DialogConfig {
295 kind: DialogKind::Custom,
296 ..Default::default()
297 },
298 hit_id: None,
299 }
300 }
301
302 #[must_use]
307 pub fn hit_id(mut self, id: HitId) -> Self {
308 self.hit_id = Some(id);
309 self.config.modal_config = self.config.modal_config.hit_id(id);
310 self
311 }
312
313 #[must_use]
315 pub fn modal_config(mut self, config: ModalConfig) -> Self {
316 self.hit_id = config.hit_id;
317 self.config.modal_config = config;
318 self
319 }
320
321 #[must_use]
323 pub fn button_style(mut self, style: Style) -> Self {
324 self.config.button_style = style;
325 self
326 }
327
328 #[must_use]
330 pub fn primary_button_style(mut self, style: Style) -> Self {
331 self.config.primary_button_style = style;
332 self
333 }
334
335 #[must_use]
337 pub fn focused_button_style(mut self, style: Style) -> Self {
338 self.config.focused_button_style = style;
339 self
340 }
341
342 pub fn handle_event(
344 &self,
345 event: &Event,
346 state: &mut DialogState,
347 hit: Option<(HitId, HitRegion, HitData)>,
348 ) -> Option<DialogResult> {
349 if !state.open {
350 return None;
351 }
352
353 if self.config.kind != DialogKind::Prompt && state.input_focused {
354 state.input_focused = false;
355 }
356
357 match event {
358 Event::Key(KeyEvent {
360 code: KeyCode::Escape,
361 kind: KeyEventKind::Press,
362 ..
363 }) if self.config.modal_config.close_on_escape => {
364 state.close(DialogResult::Dismissed);
365 return Some(DialogResult::Dismissed);
366 }
367
368 Event::Key(KeyEvent {
370 code: KeyCode::Tab,
371 kind: KeyEventKind::Press,
372 modifiers,
373 ..
374 }) => {
375 let shift = modifiers.contains(Modifiers::SHIFT);
376 self.cycle_focus(state, shift);
377 }
378
379 Event::Key(KeyEvent {
381 code: KeyCode::BackTab,
382 kind: KeyEventKind::Press,
383 ..
384 }) => {
385 self.cycle_focus(state, true);
386 }
387
388 Event::Key(KeyEvent {
390 code: KeyCode::Enter,
391 kind: KeyEventKind::Press,
392 ..
393 }) => {
394 return self.activate_button(state);
395 }
396
397 Event::Key(KeyEvent {
399 code: KeyCode::Left | KeyCode::Right,
400 kind: KeyEventKind::Press,
401 ..
402 }) if !state.input_focused => {
403 let forward = matches!(
404 event,
405 Event::Key(KeyEvent {
406 code: KeyCode::Right,
407 ..
408 })
409 );
410 self.navigate_buttons(state, forward);
411 }
412
413 Event::Mouse(MouseEvent {
415 kind: MouseEventKind::Down(MouseButton::Left),
416 ..
417 }) => {
418 state.pressed_button = None;
419 if self.config.kind == DialogKind::Prompt
420 && let (Some((id, region, _)), Some(expected)) = (hit, self.hit_id)
421 && id == expected
422 && region == DIALOG_HIT_INPUT
423 {
424 state.input_focused = true;
425 state.focused_button = None;
426 state.pressed_button = None;
427 } else if let (Some((id, region, data)), Some(expected)) = (hit, self.hit_id)
428 && id == expected
429 && region == DIALOG_HIT_BUTTON
430 && let Ok(idx) = usize::try_from(data)
431 && idx < self.buttons.len()
432 {
433 state.input_focused = false;
434 state.focused_button = Some(idx);
435 state.pressed_button = Some(idx);
436 }
437 }
438
439 Event::Mouse(MouseEvent {
441 kind: MouseEventKind::Up(MouseButton::Left),
442 ..
443 }) => {
444 let pressed = state.pressed_button.take();
445 if let (Some(pressed), Some((id, region, data)), Some(expected)) =
446 (pressed, hit, self.hit_id)
447 && id == expected
448 && region == DIALOG_HIT_BUTTON
449 && let Ok(idx) = usize::try_from(data)
450 && idx == pressed
451 {
452 state.input_focused = false;
453 state.focused_button = Some(idx);
454 return self.activate_button(state);
455 }
456 }
457
458 Event::Paste(paste)
459 if self.config.kind == DialogKind::Prompt && state.input_focused =>
460 {
461 self.handle_input_paste(state, &paste.text);
462 }
463
464 Event::Key(key_event)
466 if self.config.kind == DialogKind::Prompt && state.input_focused =>
467 {
468 self.handle_input_key(state, key_event);
469 }
470
471 _ => {}
472 }
473
474 None
475 }
476
477 fn cycle_focus(&self, state: &mut DialogState, reverse: bool) {
478 let has_input = self.config.kind == DialogKind::Prompt;
479 let button_count = self.buttons.len();
480 state.pressed_button = None;
481 state.focused_button = state.focused_button.filter(|&idx| idx < button_count);
484
485 if has_input {
486 if state.input_focused {
488 state.input_focused = false;
489 state.focused_button = if reverse {
490 Some(button_count.saturating_sub(1))
491 } else {
492 Some(0)
493 };
494 } else if let Some(idx) = state.focused_button {
495 if reverse {
496 if idx == 0 {
497 state.input_focused = true;
498 state.focused_button = None;
499 } else {
500 state.focused_button = Some(idx - 1);
501 }
502 } else if idx + 1 >= button_count {
503 state.input_focused = true;
504 state.focused_button = None;
505 } else {
506 state.focused_button = Some(idx + 1);
507 }
508 } else {
509 state.focused_button = if reverse {
510 Some(button_count.saturating_sub(1))
511 } else {
512 Some(0)
513 };
514 }
515 } else {
516 state.focused_button = if reverse {
518 Some(match state.focused_button {
519 Some(0) => button_count - 1,
520 Some(current) => current - 1,
521 None => button_count - 1,
522 })
523 } else {
524 Some(match state.focused_button {
525 Some(current) => (current + 1) % button_count,
526 None => 0,
527 })
528 };
529 }
530 }
531
532 fn navigate_buttons(&self, state: &mut DialogState, forward: bool) {
533 let count = self.buttons.len();
534 if count == 0 {
535 return;
536 }
537 state.pressed_button = None;
538 state.focused_button = state.focused_button.filter(|&idx| idx < count);
539 state.focused_button = if forward {
540 Some(match state.focused_button {
541 Some(current) => (current + 1) % count,
542 None => 0,
543 })
544 } else {
545 Some(match state.focused_button {
546 Some(0) => count - 1,
547 Some(current) => current - 1,
548 None => count - 1,
549 })
550 };
551 }
552
553 fn activate_button(&self, state: &mut DialogState) -> Option<DialogResult> {
554 let idx = state.focused_button.or_else(|| {
555 self.buttons.iter().position(|b| b.primary)
557 })?;
558
559 let button = self.buttons.get(idx)?;
560 let result = match button.id.as_str() {
561 "ok" => {
562 if self.config.kind == DialogKind::Prompt {
563 DialogResult::Input(state.input_value.clone())
564 } else {
565 DialogResult::Ok
566 }
567 }
568 "cancel" => DialogResult::Cancel,
569 id => DialogResult::Custom(id.to_string()),
570 };
571
572 state.close(result.clone());
573 Some(result)
574 }
575
576 fn handle_input_key(&self, state: &mut DialogState, key: &KeyEvent) {
577 if key.kind != KeyEventKind::Press {
578 return;
579 }
580
581 match key.code {
582 KeyCode::Char(c)
586 if !c.is_control()
587 && !key.modifiers.intersects(Modifiers::CTRL | Modifiers::SUPER) =>
588 {
589 state.input_value.push(c);
590 }
591 KeyCode::Backspace => {
592 if let Some((grapheme_start, _)) =
593 state.input_value.grapheme_indices(true).next_back()
594 {
595 state.input_value.truncate(grapheme_start);
596 }
597 }
598 KeyCode::Delete => {
599 state.input_value.clear();
600 }
601 _ => {}
602 }
603 }
604
605 fn handle_input_paste(&self, state: &mut DialogState, text: &str) {
606 let sanitized: String = text
607 .chars()
608 .map(|c| match c {
609 '\n' | '\r' | '\t' => ' ',
610 other => other,
611 })
612 .filter(|c| !c.is_control())
613 .collect();
614
615 if !sanitized.is_empty() {
616 state.input_value.push_str(&sanitized);
617 }
618 }
619
620 fn content_height(&self) -> u16 {
622 let mut height: u16 = 2; if !self.message.is_empty() {
628 height += 1;
629 }
630
631 height += 1;
633
634 if self.config.kind == DialogKind::Prompt {
636 height += 1;
637 height += 1; }
639
640 height += 1;
642
643 height
644 }
645
646 fn effective_size_constraints(&self, content_height: u16) -> ModalSizeConstraints {
647 let mut size = self.config.modal_config.size;
648 if size.min_width.is_none() && size.max_width.is_none() {
649 size.min_width = Some(30);
650 size.max_width = Some(60);
651 }
652 if size.min_height.is_none() && size.max_height.is_none() {
653 size.min_height = Some(content_height);
654 size.max_height = Some(content_height + 4);
655 }
656 size
657 }
658
659 fn render_content(&self, area: Rect, frame: &mut Frame, state: &DialogState) {
661 if area.is_empty() {
662 return;
663 }
664 let bounds = area.intersection(&frame.buffer.current_scissor());
665 if !frame.a11y_enabled() || bounds.is_empty() {
666 self.render_content_inner(area, frame, state, None);
667 return;
668 }
669
670 let id = self.hit_id.map_or_else(
671 || A11yNodeInfo::stable_id_for(A11yRole::Dialog, area),
672 |hit| u64::from(hit.id()),
673 );
674 let mut node = A11yNodeInfo::new(id, A11yRole::Dialog, bounds).with_name(
675 if self.title.trim().is_empty() {
676 "Dialog"
677 } else {
678 &self.title
679 },
680 );
681 if !self.message.trim().is_empty() {
682 node.description = Some(self.message.clone());
683 }
684 frame.with_a11y_scope(node, |frame| {
685 self.render_content_inner(area, frame, state, Some(id));
686 });
687 }
688
689 fn render_content_inner(
690 &self,
691 area: Rect,
692 frame: &mut Frame,
693 state: &DialogState,
694 a11y_parent: Option<u64>,
695 ) {
696 let block = Block::default()
700 .borders(Borders::ALL)
701 .title(&self.title)
702 .title_alignment(Alignment::Center);
703 if frame.a11y_enabled() {
704 let builder = frame.a11y.take();
705 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
706 block.render(area, frame);
707 }));
708 frame.a11y = builder;
709 if let Err(payload) = result {
710 std::panic::resume_unwind(payload);
711 }
712 } else {
713 block.render(area, frame);
714 }
715
716 let inner = block.inner(area);
717 if inner.is_empty() {
718 return;
719 }
720
721 for y in inner.y..inner.bottom() {
724 for x in inner.x..inner.right() {
725 if let Some(cell) = frame.buffer.get_mut(x, y) {
726 let bg = cell.bg;
727 *cell = Cell::from_char(' ');
728 cell.bg = bg;
729 }
730 }
731 }
732
733 let mut y = inner.y;
734
735 if !self.message.is_empty() && y < inner.bottom() {
737 self.draw_centered_text(
738 frame,
739 inner.x,
740 y,
741 inner.width,
742 &self.message,
743 self.config.message_style,
744 );
745 y += 1;
746 }
747
748 y += 1;
750
751 if self.config.kind == DialogKind::Prompt && y < inner.bottom() {
753 self.render_input(frame, inner.x, y, inner.width, state, a11y_parent);
754 y += 2; }
756
757 if y < inner.bottom() {
759 self.render_buttons(frame, inner.x, y, inner.width, state, a11y_parent);
760 }
761 }
762
763 fn draw_centered_text(
764 &self,
765 frame: &mut Frame,
766 x: u16,
767 y: u16,
768 width: u16,
769 text: &str,
770 style: Style,
771 ) {
772 let text_width = display_width(text).min(width as usize);
773 let offset = (width as usize - text_width) / 2;
774 let start_x = x.saturating_add(offset as u16);
775 draw_text_span(frame, start_x, y, text, style, x.saturating_add(width));
776 }
777
778 fn render_input(
779 &self,
780 frame: &mut Frame,
781 x: u16,
782 y: u16,
783 width: u16,
784 state: &DialogState,
785 a11y_parent: Option<u64>,
786 ) {
787 let input_area = Rect::new(x.saturating_add(1), y, width.saturating_sub(2), 1);
789 let input_style = self.config.input_style;
790 set_style_area(&mut frame.buffer, input_area, input_style);
791
792 if let Some(hit_id) = self.hit_id
793 && !input_area.is_empty()
794 {
795 frame.register_hit(input_area, hit_id, DIALOG_HIT_INPUT, 0);
796 }
797
798 if let Some(parent) = a11y_parent {
799 let bounds = input_area.intersection(&frame.buffer.current_scissor());
800 if !bounds.is_empty() {
801 let id = Self::a11y_child_id(parent, "input", "", 0);
802 let mut node = A11yNodeInfo::new(id, A11yRole::TextInput, bounds)
803 .with_parent(parent)
804 .with_name(if self.title.trim().is_empty() {
805 "Input"
806 } else {
807 &self.title
808 });
809 if !self.message.trim().is_empty() {
810 node.description = Some(self.message.clone());
811 }
812 node.state.focused = state.input_focused;
813 node.state.value_text = Some(state.input_value.clone());
814 frame.push_a11y(node);
815 }
816 }
817
818 let display_text = if state.input_value.is_empty() {
820 " "
821 } else {
822 &state.input_value
823 };
824
825 draw_text_span(
826 frame,
827 input_area.x,
828 y,
829 display_text,
830 input_style,
831 input_area.right(),
832 );
833
834 if state.input_focused {
836 let input_width = display_width(state.input_value.as_str());
837 let cursor_x = input_area.x + input_width.min(input_area.width as usize) as u16;
838 if cursor_x < input_area.right() {
839 frame.cursor_position = Some((cursor_x, y));
840 frame.cursor_visible = true;
841 }
842 }
843 }
844
845 fn render_buttons(
846 &self,
847 frame: &mut Frame,
848 x: u16,
849 y: u16,
850 width: u16,
851 state: &DialogState,
852 a11y_parent: Option<u64>,
853 ) {
854 if self.buttons.is_empty() {
855 return;
856 }
857
858 let total_width: usize = self
860 .buttons
861 .iter()
862 .map(|b| b.display_width())
863 .sum::<usize>()
864 + self.buttons.len().saturating_sub(1) * 2; let start_x = x + (width as usize - total_width.min(width as usize)) as u16 / 2;
868 let mut bx = start_x;
869
870 for (i, button) in self.buttons.iter().enumerate() {
871 let is_focused = !(self.config.kind == DialogKind::Prompt && state.input_focused)
874 && state.focused_button == Some(i);
875
876 let mut style = if is_focused {
878 self.config.focused_button_style
879 } else if button.primary {
880 self.config.primary_button_style
881 } else {
882 self.config.button_style
883 };
884 if is_focused {
885 let has_reverse = style
886 .attrs
887 .is_some_and(|attrs| attrs.contains(StyleFlags::REVERSE));
888 if !has_reverse {
889 style = style.reverse();
890 }
891 }
892
893 let btn_text = format!("[ {} ]", button.label);
895 let btn_width = display_width(btn_text.as_str());
896 draw_text_span(frame, bx, y, &btn_text, style, x.saturating_add(width));
897
898 let max_btn_width = width.saturating_sub(bx.saturating_sub(x));
900 let btn_area_width = btn_width.min(max_btn_width as usize) as u16;
901 if btn_area_width > 0 {
902 let btn_area = Rect::new(bx, y, btn_area_width, 1);
903 if let Some(hit_id) = self.hit_id {
904 frame.register_hit(btn_area, hit_id, DIALOG_HIT_BUTTON, i as u64);
905 }
906 if let Some(parent) = a11y_parent {
907 let bounds = btn_area.intersection(&frame.buffer.current_scissor());
908 if !bounds.is_empty() {
909 let occurrence = self.buttons[..i]
912 .iter()
913 .filter(|previous| previous.id == button.id)
914 .count();
915 let id = Self::a11y_child_id(parent, "button", &button.id, occurrence);
916 let mut node = A11yNodeInfo::new(id, A11yRole::Button, bounds)
917 .with_parent(parent)
918 .with_name(if button.label.trim().is_empty() {
919 if button.id.trim().is_empty() {
920 "Button"
921 } else {
922 &button.id
923 }
924 } else {
925 &button.label
926 });
927 node.state.focused = is_focused;
928 frame.push_a11y(node);
929 }
930 }
931 }
932
933 bx = bx
934 .saturating_add(u16::try_from(btn_width).unwrap_or(u16::MAX))
935 .saturating_add(2); }
937 }
938
939 fn a11y_child_id(parent: u64, kind: &str, key: &str, occurrence: usize) -> u64 {
940 use std::hash::{Hash, Hasher};
941 let mut hasher = std::collections::hash_map::DefaultHasher::new();
942 ("ftui.dialog", parent, kind, key, occurrence).hash(&mut hasher);
943 hasher.finish()
944 }
945}
946
947impl StatefulWidget for Dialog {
948 type State = DialogState;
949
950 fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State) {
951 if !state.open || area.is_empty() {
952 return;
953 }
954
955 let content_height = self.content_height();
957 let config = self
958 .config
959 .modal_config
960 .clone()
961 .size(self.effective_size_constraints(content_height))
962 .accessibility_container(false);
963
964 let content = DialogContent {
966 dialog: self,
967 state,
968 };
969
970 let modal = Modal::new(content).config(config);
972 modal.render(area, frame);
973 }
974}
975
976struct DialogContent<'a> {
978 dialog: &'a Dialog,
979 state: &'a DialogState,
980}
981
982impl Widget for DialogContent<'_> {
983 fn render(&self, area: Rect, frame: &mut Frame) {
984 self.dialog.render_content(area, frame, self.state);
985 }
986}
987
988#[derive(Debug, Clone)]
990#[must_use]
991pub struct DialogBuilder {
992 title: String,
993 message: String,
994 buttons: Vec<DialogButton>,
995 config: DialogConfig,
996 hit_id: Option<HitId>,
997}
998
999impl DialogBuilder {
1000 pub fn button(mut self, button: DialogButton) -> Self {
1002 self.buttons.push(button);
1003 self
1004 }
1005
1006 pub fn ok_button(self) -> Self {
1008 self.button(DialogButton::new("OK", "ok").primary())
1009 }
1010
1011 pub fn cancel_button(self) -> Self {
1013 self.button(DialogButton::new("Cancel", "cancel"))
1014 }
1015
1016 pub fn custom_button(self, label: impl Into<String>, id: impl Into<String>) -> Self {
1018 self.button(DialogButton::new(label, id))
1019 }
1020
1021 pub fn modal_config(mut self, config: ModalConfig) -> Self {
1023 self.hit_id = config.hit_id;
1024 self.config.modal_config = config;
1025 self
1026 }
1027
1028 pub fn hit_id(mut self, id: HitId) -> Self {
1030 self.hit_id = Some(id);
1031 self.config.modal_config = self.config.modal_config.hit_id(id);
1032 self
1033 }
1034
1035 pub fn build(self) -> Dialog {
1037 let mut buttons = self.buttons;
1038 if buttons.is_empty() {
1039 buttons.push(DialogButton::new("OK", "ok").primary());
1040 }
1041
1042 Dialog {
1043 title: self.title,
1044 message: self.message,
1045 buttons,
1046 config: self.config,
1047 hit_id: self.hit_id,
1048 }
1049 }
1050}
1051
1052#[cfg(test)]
1053mod tests {
1054 use super::*;
1055 use ftui_render::grapheme_pool::GraphemePool;
1056
1057 fn row_text(frame: &Frame, y: u16) -> String {
1058 (0..frame.buffer.width())
1059 .map(|x| {
1060 frame
1061 .buffer
1062 .get(x, y)
1063 .unwrap()
1064 .content
1065 .as_char()
1066 .unwrap_or(' ')
1067 })
1068 .collect()
1069 }
1070
1071 fn hit_bounds(frame: &Frame, expected: (HitId, HitRegion, u64)) -> Option<Rect> {
1072 let mut min_x = u16::MAX;
1073 let mut min_y = u16::MAX;
1074 let mut max_x = 0;
1075 let mut max_y = 0;
1076 let mut found = false;
1077
1078 for y in 0..frame.buffer.height() {
1079 for x in 0..frame.buffer.width() {
1080 if frame.hit_test(x, y) == Some(expected) {
1081 min_x = min_x.min(x);
1082 min_y = min_y.min(y);
1083 max_x = max_x.max(x);
1084 max_y = max_y.max(y);
1085 found = true;
1086 }
1087 }
1088 }
1089
1090 found.then(|| {
1091 Rect::new(
1092 min_x,
1093 min_y,
1094 max_x.saturating_sub(min_x) + 1,
1095 max_y.saturating_sub(min_y) + 1,
1096 )
1097 })
1098 }
1099
1100 #[test]
1101 fn alert_dialog_single_button() {
1102 let dialog = Dialog::alert("Title", "Message");
1103 assert_eq!(dialog.buttons.len(), 1);
1104 assert_eq!(dialog.buttons[0].label, "OK");
1105 assert!(dialog.buttons[0].primary);
1106 }
1107
1108 #[test]
1109 fn confirm_dialog_two_buttons() {
1110 let dialog = Dialog::confirm("Title", "Message");
1111 assert_eq!(dialog.buttons.len(), 2);
1112 assert_eq!(dialog.buttons[0].label, "OK");
1113 assert_eq!(dialog.buttons[1].label, "Cancel");
1114 }
1115
1116 #[test]
1117 fn prompt_dialog_has_input() {
1118 let dialog = Dialog::prompt("Title", "Message");
1119 assert_eq!(dialog.config.kind, DialogKind::Prompt);
1120 assert_eq!(dialog.buttons.len(), 2);
1121 }
1122
1123 #[test]
1124 fn custom_dialog_builder() {
1125 let dialog = Dialog::custom("Custom", "Message")
1126 .ok_button()
1127 .cancel_button()
1128 .custom_button("Help", "help")
1129 .build();
1130 assert_eq!(dialog.buttons.len(), 3);
1131 }
1132
1133 #[test]
1134 fn dialog_state_starts_open() {
1135 let state = DialogState::new();
1136 assert!(state.is_open());
1137 assert!(state.result.is_none());
1138 }
1139
1140 #[test]
1141 fn dialog_state_close_sets_result() {
1142 let mut state = DialogState::new();
1143 state.close(DialogResult::Ok);
1144 assert!(!state.is_open());
1145 assert_eq!(state.result, Some(DialogResult::Ok));
1146 }
1147
1148 #[test]
1149 fn dialog_escape_closes() {
1150 let dialog = Dialog::alert("Test", "Msg");
1151 let mut state = DialogState::new();
1152 let event = Event::Key(KeyEvent {
1153 code: KeyCode::Escape,
1154 modifiers: Modifiers::empty(),
1155 kind: KeyEventKind::Press,
1156 });
1157 let result = dialog.handle_event(&event, &mut state, None);
1158 assert_eq!(result, Some(DialogResult::Dismissed));
1159 assert!(!state.is_open());
1160 }
1161
1162 #[test]
1163 fn dialog_enter_activates_primary() {
1164 let dialog = Dialog::alert("Test", "Msg");
1165 let mut state = DialogState::new();
1166 state.input_focused = false; let event = Event::Key(KeyEvent {
1168 code: KeyCode::Enter,
1169 modifiers: Modifiers::empty(),
1170 kind: KeyEventKind::Press,
1171 });
1172 let result = dialog.handle_event(&event, &mut state, None);
1173 assert_eq!(result, Some(DialogResult::Ok));
1174 }
1175
1176 #[test]
1177 fn dialog_mouse_up_activates_pressed_button() {
1178 let dialog = Dialog::confirm("Test", "Msg").hit_id(HitId::new(1));
1179 let mut state = DialogState::new();
1180
1181 let down = Event::Mouse(MouseEvent::new(
1182 MouseEventKind::Down(MouseButton::Left),
1183 0,
1184 0,
1185 ));
1186 let hit = Some((HitId::new(1), HitRegion::Button, 0u64));
1187 let result = dialog.handle_event(&down, &mut state, hit);
1188 assert_eq!(result, None);
1189 assert_eq!(state.focused_button, Some(0));
1190 assert_eq!(state.pressed_button, Some(0));
1191
1192 let up = Event::Mouse(MouseEvent::new(MouseEventKind::Up(MouseButton::Left), 0, 0));
1193 let result = dialog.handle_event(&up, &mut state, hit);
1194 assert_eq!(result, Some(DialogResult::Ok));
1195 assert!(!state.is_open());
1196 }
1197
1198 #[test]
1199 fn prompt_mouse_down_on_button_transfers_focus_from_input() {
1200 let dialog = Dialog::prompt("Test", "Msg").hit_id(HitId::new(1));
1201 let mut state = DialogState::new();
1202 assert!(state.input_focused);
1203 assert_eq!(state.focused_button, None);
1204
1205 let down = Event::Mouse(MouseEvent::new(
1206 MouseEventKind::Down(MouseButton::Left),
1207 0,
1208 0,
1209 ));
1210 let hit = Some((HitId::new(1), HitRegion::Button, 1u64));
1211 let result = dialog.handle_event(&down, &mut state, hit);
1212
1213 assert_eq!(result, None);
1214 assert!(!state.input_focused);
1215 assert_eq!(state.focused_button, Some(1));
1216 assert_eq!(state.pressed_button, Some(1));
1217 }
1218
1219 #[test]
1220 fn prompt_mouse_button_focus_allows_arrow_navigation_after_missed_click() {
1221 let dialog = Dialog::prompt("Test", "Msg").hit_id(HitId::new(1));
1222 let mut state = DialogState::new();
1223
1224 let down = Event::Mouse(MouseEvent::new(
1225 MouseEventKind::Down(MouseButton::Left),
1226 0,
1227 0,
1228 ));
1229 let hit = Some((HitId::new(1), HitRegion::Button, 0u64));
1230 dialog.handle_event(&down, &mut state, hit);
1231
1232 let up_outside = Event::Mouse(MouseEvent::new(MouseEventKind::Up(MouseButton::Left), 0, 0));
1233 dialog.handle_event(&up_outside, &mut state, None);
1234 assert!(!state.input_focused);
1235 assert_eq!(state.focused_button, Some(0));
1236
1237 let right = Event::Key(KeyEvent {
1238 code: KeyCode::Right,
1239 modifiers: Modifiers::empty(),
1240 kind: KeyEventKind::Press,
1241 });
1242 dialog.handle_event(&right, &mut state, None);
1243 assert_eq!(state.focused_button, Some(1));
1244 }
1245
1246 #[test]
1247 fn prompt_mouse_down_on_input_restores_input_focus() {
1248 let dialog = Dialog::prompt("Test", "Msg").hit_id(HitId::new(1));
1249 let mut state = DialogState::new();
1250 state.input_focused = false;
1251 state.focused_button = Some(1);
1252 state.pressed_button = Some(1);
1253
1254 let down = Event::Mouse(MouseEvent::new(
1255 MouseEventKind::Down(MouseButton::Left),
1256 0,
1257 0,
1258 ));
1259 let hit = Some((HitId::new(1), DIALOG_HIT_INPUT, 0u64));
1260 let result = dialog.handle_event(&down, &mut state, hit);
1261
1262 assert_eq!(result, None);
1263 assert!(state.input_focused);
1264 assert_eq!(state.focused_button, None);
1265 assert_eq!(state.pressed_button, None);
1266 }
1267
1268 #[test]
1269 fn render_prompt_registers_input_hit_region() {
1270 let dialog = Dialog::prompt("Prompt", "Enter:").hit_id(HitId::new(7));
1271 let mut state = DialogState::new();
1272 let mut pool = GraphemePool::new();
1273 let mut frame = Frame::with_hit_grid(40, 10, &mut pool);
1274
1275 dialog.render(Rect::new(0, 0, 40, 10), &mut frame, &mut state);
1276
1277 let found = (0..frame.buffer.height()).any(|y| {
1278 (0..frame.buffer.width())
1279 .any(|x| frame.hit_test(x, y) == Some((HitId::new(7), DIALOG_HIT_INPUT, 0)))
1280 });
1281 assert!(found);
1282 }
1283
1284 #[test]
1285 fn render_prompt_registers_input_hit_region_from_modal_config_hit_id() {
1286 let dialog = Dialog::prompt("Prompt", "Enter:")
1287 .modal_config(ModalConfig::default().hit_id(HitId::new(7)));
1288 let mut state = DialogState::new();
1289 let mut pool = GraphemePool::new();
1290 let mut frame = Frame::with_hit_grid(40, 10, &mut pool);
1291
1292 dialog.render(Rect::new(0, 0, 40, 10), &mut frame, &mut state);
1293
1294 let found = (0..frame.buffer.height()).any(|y| {
1295 (0..frame.buffer.width())
1296 .any(|x| frame.hit_test(x, y) == Some((HitId::new(7), DIALOG_HIT_INPUT, 0)))
1297 });
1298 assert!(found);
1299 }
1300
1301 #[test]
1302 fn render_respects_modal_config_size_constraints() {
1303 let dialog = Dialog::alert("Prompt", "Enter:").modal_config(
1304 ModalConfig::default()
1305 .hit_id(HitId::new(11))
1306 .size(ModalSizeConstraints::new().max_width(10).max_height(5)),
1307 );
1308 let mut state = DialogState::new();
1309 let mut pool = GraphemePool::new();
1310 let mut frame = Frame::with_hit_grid(40, 20, &mut pool);
1311
1312 dialog.render(Rect::new(0, 0, 40, 20), &mut frame, &mut state);
1313
1314 let content = hit_bounds(&frame, (HitId::new(11), crate::modal::MODAL_HIT_CONTENT, 0))
1315 .expect("dialog content hit region should exist");
1316 assert_eq!(content.width, 10);
1317 assert_eq!(content.height, 5);
1318 }
1319
1320 #[test]
1321 fn dialog_mouse_up_outside_does_not_activate() {
1322 let dialog = Dialog::confirm("Test", "Msg").hit_id(HitId::new(1));
1323 let mut state = DialogState::new();
1324
1325 let down = Event::Mouse(MouseEvent::new(
1326 MouseEventKind::Down(MouseButton::Left),
1327 0,
1328 0,
1329 ));
1330 let hit = Some((HitId::new(1), HitRegion::Button, 0u64));
1331 let result = dialog.handle_event(&down, &mut state, hit);
1332 assert_eq!(result, None);
1333 assert_eq!(state.pressed_button, Some(0));
1334
1335 let up = Event::Mouse(MouseEvent::new(MouseEventKind::Up(MouseButton::Left), 0, 0));
1336 let result = dialog.handle_event(&up, &mut state, None);
1337 assert_eq!(result, None);
1338 assert!(state.is_open());
1339 assert_eq!(state.pressed_button, None);
1340 }
1341
1342 #[test]
1343 fn dialog_tab_cycles_focus() {
1344 let dialog = Dialog::confirm("Test", "Msg");
1345 let mut state = DialogState::new();
1346 state.input_focused = false;
1347 state.focused_button = Some(0);
1348
1349 let tab = Event::Key(KeyEvent {
1350 code: KeyCode::Tab,
1351 modifiers: Modifiers::empty(),
1352 kind: KeyEventKind::Press,
1353 });
1354
1355 dialog.handle_event(&tab, &mut state, None);
1356 assert_eq!(state.focused_button, Some(1));
1357
1358 dialog.handle_event(&tab, &mut state, None);
1359 assert_eq!(state.focused_button, Some(0)); }
1361
1362 #[test]
1363 fn fresh_non_prompt_tab_starts_on_primary_button() {
1364 let dialog = Dialog::confirm("Test", "Msg");
1365 let mut state = DialogState::new();
1366 assert_eq!(state.focused_button, None);
1367 assert!(state.input_focused);
1368
1369 let tab = Event::Key(KeyEvent {
1370 code: KeyCode::Tab,
1371 modifiers: Modifiers::empty(),
1372 kind: KeyEventKind::Press,
1373 });
1374
1375 dialog.handle_event(&tab, &mut state, None);
1376 assert!(!state.input_focused);
1377 assert_eq!(state.focused_button, Some(0));
1378 }
1379
1380 #[test]
1381 fn fresh_non_prompt_right_arrow_starts_on_primary_button() {
1382 let dialog = Dialog::confirm("Test", "Msg");
1383 let mut state = DialogState::new();
1384 assert_eq!(state.focused_button, None);
1385 assert!(state.input_focused);
1386
1387 let right = Event::Key(KeyEvent {
1388 code: KeyCode::Right,
1389 modifiers: Modifiers::empty(),
1390 kind: KeyEventKind::Press,
1391 });
1392
1393 dialog.handle_event(&right, &mut state, None);
1394 assert!(!state.input_focused);
1395 assert_eq!(state.focused_button, Some(0));
1396 }
1397
1398 #[test]
1399 fn tab_navigation_cancels_pressed_button() {
1400 let dialog = Dialog::confirm("Test", "Msg").hit_id(HitId::new(1));
1401 let mut state = DialogState::new();
1402
1403 let down = Event::Mouse(MouseEvent::new(
1404 MouseEventKind::Down(MouseButton::Left),
1405 0,
1406 0,
1407 ));
1408 let hit0 = Some((HitId::new(1), HitRegion::Button, 0u64));
1409 dialog.handle_event(&down, &mut state, hit0);
1410 assert_eq!(state.pressed_button, Some(0));
1411
1412 let tab = Event::Key(KeyEvent {
1413 code: KeyCode::Tab,
1414 modifiers: Modifiers::empty(),
1415 kind: KeyEventKind::Press,
1416 });
1417 dialog.handle_event(&tab, &mut state, None);
1418 assert_eq!(state.focused_button, Some(1));
1419 assert_eq!(state.pressed_button, None);
1420
1421 let up = Event::Mouse(MouseEvent::new(MouseEventKind::Up(MouseButton::Left), 0, 0));
1422 let result = dialog.handle_event(&up, &mut state, hit0);
1423 assert_eq!(result, None);
1424 assert!(state.is_open());
1425 }
1426
1427 #[test]
1428 fn prompt_enter_returns_input() {
1429 let dialog = Dialog::prompt("Test", "Enter:");
1430 let mut state = DialogState::new();
1431 state.input_value = "hello".to_string();
1432 state.input_focused = false;
1433 state.focused_button = Some(0); let enter = Event::Key(KeyEvent {
1436 code: KeyCode::Enter,
1437 modifiers: Modifiers::empty(),
1438 kind: KeyEventKind::Press,
1439 });
1440
1441 let result = dialog.handle_event(&enter, &mut state, None);
1442 assert_eq!(result, Some(DialogResult::Input("hello".to_string())));
1443 }
1444
1445 #[test]
1446 fn prompt_input_ignores_command_chords_and_control_chars() {
1447 let dialog = Dialog::prompt("Test", "Enter:");
1449 let mut state = DialogState::new();
1450 state.input_focused = true;
1451 let press = |c, modifiers| {
1452 Event::Key(KeyEvent {
1453 code: KeyCode::Char(c),
1454 modifiers,
1455 kind: KeyEventKind::Press,
1456 })
1457 };
1458 for event in [
1459 press('h', Modifiers::empty()),
1460 press('c', Modifiers::CTRL),
1461 press('s', Modifiers::SUPER),
1462 press('\u{7}', Modifiers::empty()),
1463 press('I', Modifiers::SHIFT),
1464 press('é', Modifiers::ALT),
1465 ] {
1466 dialog.handle_event(&event, &mut state, None);
1467 }
1468 assert_eq!(state.input_value, "hIé");
1469 }
1470
1471 #[test]
1472 fn button_display_width() {
1473 let button = DialogButton::new("OK", "ok");
1474 assert_eq!(button.display_width(), 6); }
1476
1477 #[test]
1478 fn render_alert_does_not_panic() {
1479 let dialog = Dialog::alert("Alert", "This is an alert message.");
1480 let mut state = DialogState::new();
1481 let mut pool = GraphemePool::new();
1482 let mut frame = Frame::new(80, 24, &mut pool);
1483 dialog.render(Rect::new(0, 0, 80, 24), &mut frame, &mut state);
1484 }
1485
1486 #[test]
1487 fn render_confirm_does_not_panic() {
1488 let dialog = Dialog::confirm("Confirm", "Are you sure?");
1489 let mut state = DialogState::new();
1490 let mut pool = GraphemePool::new();
1491 let mut frame = Frame::new(80, 24, &mut pool);
1492 dialog.render(Rect::new(0, 0, 80, 24), &mut frame, &mut state);
1493 }
1494
1495 #[test]
1496 fn render_prompt_does_not_panic() {
1497 let dialog = Dialog::prompt("Prompt", "Enter your name:");
1498 let mut state = DialogState::new();
1499 state.input_value = "Test User".to_string();
1500 let mut pool = GraphemePool::new();
1501 let mut frame = Frame::new(80, 24, &mut pool);
1502 dialog.render(Rect::new(0, 0, 80, 24), &mut frame, &mut state);
1503 }
1504
1505 #[test]
1506 fn render_content_shorter_message_and_buttons_clear_stale_inner_rows() {
1507 let dialog_long = Dialog::custom("Title", "LLLLLLLLLLLLLLLLLLLL")
1508 .custom_button("Alpha", "alpha")
1509 .custom_button("Beta", "beta")
1510 .custom_button("Gamma", "gamma")
1511 .build();
1512 let dialog_short = Dialog::custom("Title", "S").ok_button().build();
1513 let state = DialogState::new();
1514 let area = Rect::new(10, 5, 40, 8);
1515 let mut pool = GraphemePool::new();
1516 let mut frame = Frame::new(80, 24, &mut pool);
1517
1518 dialog_long.render_content(area, &mut frame, &state);
1519 dialog_short.render_content(area, &mut frame, &state);
1520
1521 let inner = Block::default()
1522 .borders(Borders::ALL)
1523 .title("Title")
1524 .title_alignment(Alignment::Center)
1525 .inner(area);
1526 let message_row = row_text(&frame, inner.y);
1527 let button_row = row_text(&frame, inner.y + 2);
1528
1529 assert!(message_row.contains('S'));
1530 assert!(!message_row.contains('L'));
1531 assert!(button_row.contains("[ OK ]"));
1532 assert!(!button_row.contains("Alpha"));
1533 assert!(!button_row.contains("Beta"));
1534 assert!(!button_row.contains("Gamma"));
1535 }
1536
1537 #[test]
1538 fn render_prompt_shorter_input_clears_stale_suffix() {
1539 let dialog = Dialog::prompt("Prompt", "Enter:");
1540 let area = Rect::new(10, 5, 40, 8);
1541 let mut long_state = DialogState::new();
1542 long_state.input_value = "LongInputValue".to_string();
1543 let mut short_state = DialogState::new();
1544 short_state.input_value = "Hi".to_string();
1545 let mut pool = GraphemePool::new();
1546 let mut frame = Frame::new(80, 24, &mut pool);
1547
1548 dialog.render_content(area, &mut frame, &long_state);
1549 dialog.render_content(area, &mut frame, &short_state);
1550
1551 let inner = Block::default()
1552 .borders(Borders::ALL)
1553 .title("Prompt")
1554 .title_alignment(Alignment::Center)
1555 .inner(area);
1556 let input_row = row_text(&frame, inner.y + 2);
1557
1558 assert!(input_row.contains("Hi"));
1559 assert!(!input_row.contains("LongInputValue"));
1560 assert!(!input_row.contains("ngInputValue"));
1561 }
1562
1563 #[test]
1564 fn render_tiny_area_does_not_panic() {
1565 let dialog = Dialog::alert("T", "M");
1566 let mut state = DialogState::new();
1567 let mut pool = GraphemePool::new();
1568 let mut frame = Frame::new(10, 5, &mut pool);
1569 dialog.render(Rect::new(0, 0, 10, 5), &mut frame, &mut state);
1570 }
1571
1572 #[test]
1573 fn custom_dialog_empty_buttons_gets_default() {
1574 let dialog = Dialog::custom("Custom", "No buttons").build();
1575 assert_eq!(dialog.buttons.len(), 1);
1576 assert_eq!(dialog.buttons[0].label, "OK");
1577 }
1578
1579 #[test]
1580 fn render_unicode_message_does_not_panic() {
1581 let dialog = Dialog::alert("你好", "这是一条消息 🎉");
1583 let mut state = DialogState::new();
1584 let mut pool = GraphemePool::new();
1585 let mut frame = Frame::new(80, 24, &mut pool);
1586 dialog.render(Rect::new(0, 0, 80, 24), &mut frame, &mut state);
1587 }
1588
1589 #[test]
1590 fn prompt_with_unicode_input_renders_correctly() {
1591 let dialog = Dialog::prompt("入力", "名前を入力:");
1592 let mut state = DialogState::new();
1593 state.input_value = "田中太郎".to_string(); let mut pool = GraphemePool::new();
1595 let mut frame = Frame::new(80, 24, &mut pool);
1596 dialog.render(Rect::new(0, 0, 80, 24), &mut frame, &mut state);
1597 }
1598
1599 #[test]
1602 fn edge_state_default_vs_new() {
1603 let default = DialogState::default();
1604 let new = DialogState::new();
1605 assert!(!default.open);
1607 assert!(!default.input_focused);
1608 assert!(new.open);
1610 assert!(new.input_focused);
1611 }
1612
1613 #[test]
1614 fn edge_state_reset_then_reuse() {
1615 let mut state = DialogState::new();
1616 state.input_value = "typed".to_string();
1617 state.focused_button = Some(1);
1618 state.close(DialogResult::Cancel);
1619
1620 assert!(!state.is_open());
1621 assert!(state.result.is_some());
1622
1623 state.reset();
1624 assert!(state.is_open());
1625 assert!(state.result.is_none());
1626 assert!(state.input_value.is_empty());
1627 assert_eq!(state.focused_button, None);
1628 assert_eq!(state.pressed_button, None);
1629 assert!(state.input_focused);
1630 }
1631
1632 #[test]
1633 fn edge_take_result_when_none() {
1634 let mut state = DialogState::new();
1635 assert_eq!(state.take_result(), None);
1636 assert_eq!(state.take_result(), None);
1638 }
1639
1640 #[test]
1641 fn edge_take_result_consumes() {
1642 let mut state = DialogState::new();
1643 state.close(DialogResult::Ok);
1644 assert_eq!(state.take_result(), Some(DialogResult::Ok));
1645 assert_eq!(state.take_result(), None);
1647 }
1648
1649 #[test]
1650 fn edge_handle_event_when_closed() {
1651 let dialog = Dialog::alert("Test", "Msg");
1652 let mut state = DialogState::new();
1653 state.close(DialogResult::Dismissed);
1654
1655 let enter = Event::Key(KeyEvent {
1656 code: KeyCode::Enter,
1657 modifiers: Modifiers::empty(),
1658 kind: KeyEventKind::Press,
1659 });
1660 let result = dialog.handle_event(&enter, &mut state, None);
1662 assert_eq!(result, None);
1663 }
1664
1665 #[test]
1666 fn edge_prompt_tab_full_cycle() {
1667 let dialog = Dialog::prompt("Test", "Enter:");
1668 let mut state = DialogState::new();
1669 assert!(state.input_focused);
1671 assert_eq!(state.focused_button, None);
1672
1673 let tab = Event::Key(KeyEvent {
1674 code: KeyCode::Tab,
1675 modifiers: Modifiers::empty(),
1676 kind: KeyEventKind::Press,
1677 });
1678
1679 dialog.handle_event(&tab, &mut state, None);
1681 assert!(!state.input_focused);
1682 assert_eq!(state.focused_button, Some(0));
1683
1684 dialog.handle_event(&tab, &mut state, None);
1686 assert!(!state.input_focused);
1687 assert_eq!(state.focused_button, Some(1));
1688
1689 dialog.handle_event(&tab, &mut state, None);
1691 assert!(state.input_focused);
1692 assert_eq!(state.focused_button, None);
1693 }
1694
1695 #[test]
1696 fn edge_prompt_shift_tab_reverse_cycle() {
1697 let dialog = Dialog::prompt("Test", "Enter:");
1698 let mut state = DialogState::new();
1699
1700 let shift_tab = Event::Key(KeyEvent {
1701 code: KeyCode::Tab,
1702 modifiers: Modifiers::SHIFT,
1703 kind: KeyEventKind::Press,
1704 });
1705
1706 dialog.handle_event(&shift_tab, &mut state, None);
1708 assert!(!state.input_focused);
1709 assert_eq!(state.focused_button, Some(1));
1710
1711 dialog.handle_event(&shift_tab, &mut state, None);
1713 assert!(!state.input_focused);
1714 assert_eq!(state.focused_button, Some(0));
1715
1716 dialog.handle_event(&shift_tab, &mut state, None);
1718 assert!(state.input_focused);
1719 assert_eq!(state.focused_button, None);
1720 }
1721
1722 #[test]
1723 fn prompt_tab_recovers_when_button_focus_is_missing() {
1724 let dialog = Dialog::prompt("Test", "Enter:");
1725 let mut state = DialogState::new();
1726 state.input_focused = false;
1727 state.focused_button = None;
1728
1729 let tab = Event::Key(KeyEvent {
1730 code: KeyCode::Tab,
1731 modifiers: Modifiers::empty(),
1732 kind: KeyEventKind::Press,
1733 });
1734
1735 dialog.handle_event(&tab, &mut state, None);
1736 assert!(!state.input_focused);
1737 assert_eq!(state.focused_button, Some(0));
1738 }
1739
1740 #[test]
1741 fn edge_arrow_key_navigation() {
1742 let dialog = Dialog::confirm("Test", "Msg");
1743 let mut state = DialogState::new();
1744 state.input_focused = false;
1745 state.focused_button = Some(0);
1746
1747 let right = Event::Key(KeyEvent {
1748 code: KeyCode::Right,
1749 modifiers: Modifiers::empty(),
1750 kind: KeyEventKind::Press,
1751 });
1752 let left = Event::Key(KeyEvent {
1753 code: KeyCode::Left,
1754 modifiers: Modifiers::empty(),
1755 kind: KeyEventKind::Press,
1756 });
1757
1758 dialog.handle_event(&right, &mut state, None);
1760 assert_eq!(state.focused_button, Some(1));
1761
1762 dialog.handle_event(&right, &mut state, None);
1764 assert_eq!(state.focused_button, Some(0));
1765
1766 dialog.handle_event(&left, &mut state, None);
1768 assert_eq!(state.focused_button, Some(1));
1769
1770 dialog.handle_event(&left, &mut state, None);
1772 assert_eq!(state.focused_button, Some(0));
1773 }
1774
1775 #[test]
1776 fn edge_arrow_keys_ignored_when_input_focused() {
1777 let dialog = Dialog::prompt("Test", "Enter:");
1778 let mut state = DialogState::new();
1779 assert!(state.input_focused);
1781 state.focused_button = None;
1782
1783 let right = Event::Key(KeyEvent {
1784 code: KeyCode::Right,
1785 modifiers: Modifiers::empty(),
1786 kind: KeyEventKind::Press,
1787 });
1788
1789 dialog.handle_event(&right, &mut state, None);
1790 assert!(state.input_focused);
1792 assert_eq!(state.focused_button, None);
1793 }
1794
1795 #[test]
1796 fn prompt_arrow_navigation_cancels_pressed_button() {
1797 let dialog = Dialog::prompt("Test", "Enter:").hit_id(HitId::new(1));
1798 let mut state = DialogState::new();
1799
1800 let down = Event::Mouse(MouseEvent::new(
1801 MouseEventKind::Down(MouseButton::Left),
1802 0,
1803 0,
1804 ));
1805 let hit0 = Some((HitId::new(1), HitRegion::Button, 0u64));
1806 dialog.handle_event(&down, &mut state, hit0);
1807 assert_eq!(state.focused_button, Some(0));
1808 assert_eq!(state.pressed_button, Some(0));
1809
1810 let right = Event::Key(KeyEvent {
1811 code: KeyCode::Right,
1812 modifiers: Modifiers::empty(),
1813 kind: KeyEventKind::Press,
1814 });
1815 dialog.handle_event(&right, &mut state, None);
1816 assert_eq!(state.focused_button, Some(1));
1817 assert_eq!(state.pressed_button, None);
1818
1819 let up = Event::Mouse(MouseEvent::new(MouseEventKind::Up(MouseButton::Left), 0, 0));
1820 let result = dialog.handle_event(&up, &mut state, hit0);
1821 assert_eq!(result, None);
1822 assert!(state.is_open());
1823 }
1824
1825 #[test]
1826 fn edge_input_backspace_on_empty() {
1827 let dialog = Dialog::prompt("Test", "Enter:");
1828 let mut state = DialogState::new();
1829 assert!(state.input_value.is_empty());
1830
1831 let backspace = Event::Key(KeyEvent {
1832 code: KeyCode::Backspace,
1833 modifiers: Modifiers::empty(),
1834 kind: KeyEventKind::Press,
1835 });
1836
1837 dialog.handle_event(&backspace, &mut state, None);
1839 assert!(state.input_value.is_empty());
1840 }
1841
1842 #[test]
1843 fn edge_input_backspace_removes_whole_grapheme_cluster() {
1844 let dialog = Dialog::prompt("Test", "Enter:");
1845 let mut state = DialogState::new();
1846 state.input_value = "e\u{301}".to_string();
1847
1848 let backspace = Event::Key(KeyEvent {
1849 code: KeyCode::Backspace,
1850 modifiers: Modifiers::empty(),
1851 kind: KeyEventKind::Press,
1852 });
1853
1854 dialog.handle_event(&backspace, &mut state, None);
1855 assert!(state.input_value.is_empty());
1856 }
1857
1858 #[test]
1859 fn edge_input_delete_clears_all() {
1860 let dialog = Dialog::prompt("Test", "Enter:");
1861 let mut state = DialogState::new();
1862 state.input_value = "hello world".to_string();
1863
1864 let delete = Event::Key(KeyEvent {
1865 code: KeyCode::Delete,
1866 modifiers: Modifiers::empty(),
1867 kind: KeyEventKind::Press,
1868 });
1869
1870 dialog.handle_event(&delete, &mut state, None);
1871 assert!(state.input_value.is_empty());
1872 }
1873
1874 #[test]
1875 fn edge_input_char_accumulation() {
1876 let dialog = Dialog::prompt("Test", "Enter:");
1877 let mut state = DialogState::new();
1878
1879 for c in ['h', 'e', 'l', 'l', 'o'] {
1880 let event = Event::Key(KeyEvent {
1881 code: KeyCode::Char(c),
1882 modifiers: Modifiers::empty(),
1883 kind: KeyEventKind::Press,
1884 });
1885 dialog.handle_event(&event, &mut state, None);
1886 }
1887 assert_eq!(state.input_value, "hello");
1888 }
1889
1890 #[test]
1891 fn edge_prompt_paste_appends_sanitized_single_line_text() {
1892 let dialog = Dialog::prompt("Test", "Enter:");
1893 let mut state = DialogState::new();
1894 state.input_value = "hello".to_string();
1895
1896 let paste = Event::Paste(ftui_core::event::PasteEvent::bracketed(
1897 " world\nnext\tline\u{0007}",
1898 ));
1899
1900 dialog.handle_event(&paste, &mut state, None);
1901 assert_eq!(state.input_value, "hello world next line");
1902 }
1903
1904 #[test]
1905 fn edge_prompt_paste_ignored_when_input_not_focused() {
1906 let dialog = Dialog::prompt("Test", "Enter:");
1907 let mut state = DialogState::new();
1908 state.input_focused = false;
1909 state.focused_button = Some(0);
1910
1911 let paste = Event::Paste(ftui_core::event::PasteEvent::bracketed("ignored"));
1912
1913 dialog.handle_event(&paste, &mut state, None);
1914 assert!(state.input_value.is_empty());
1915 }
1916
1917 #[test]
1918 fn edge_prompt_cancel_returns_cancel() {
1919 let dialog = Dialog::prompt("Test", "Enter:");
1920 let mut state = DialogState::new();
1921 state.input_value = "typed something".to_string();
1922 state.input_focused = false;
1923 state.focused_button = Some(1); let enter = Event::Key(KeyEvent {
1926 code: KeyCode::Enter,
1927 modifiers: Modifiers::empty(),
1928 kind: KeyEventKind::Press,
1929 });
1930
1931 let result = dialog.handle_event(&enter, &mut state, None);
1932 assert_eq!(result, Some(DialogResult::Cancel));
1933 assert!(!state.is_open());
1934 }
1935
1936 #[test]
1937 fn edge_custom_button_activation() {
1938 let dialog = Dialog::custom("Test", "Msg")
1939 .custom_button("Save", "save")
1940 .custom_button("Delete", "delete")
1941 .build();
1942 let mut state = DialogState::new();
1943 state.input_focused = false;
1944 state.focused_button = Some(1); let enter = Event::Key(KeyEvent {
1947 code: KeyCode::Enter,
1948 modifiers: Modifiers::empty(),
1949 kind: KeyEventKind::Press,
1950 });
1951
1952 let result = dialog.handle_event(&enter, &mut state, None);
1953 assert_eq!(result, Some(DialogResult::Custom("delete".to_string())));
1954 }
1955
1956 #[test]
1957 fn edge_render_zero_size_area() {
1958 let dialog = Dialog::alert("T", "M");
1959 let mut state = DialogState::new();
1960 let mut pool = GraphemePool::new();
1961 let mut frame = Frame::new(80, 24, &mut pool);
1962 dialog.render(Rect::new(0, 0, 0, 0), &mut frame, &mut state);
1964 dialog.render(Rect::new(0, 0, 80, 0), &mut frame, &mut state);
1966 dialog.render(Rect::new(0, 0, 0, 24), &mut frame, &mut state);
1968 }
1969
1970 #[test]
1971 fn edge_render_closed_dialog_is_noop() {
1972 let dialog = Dialog::alert("Test", "Msg");
1973 let mut state = DialogState::new();
1974 state.close(DialogResult::Dismissed);
1975
1976 let mut pool = GraphemePool::new();
1977 let mut frame = Frame::new(80, 24, &mut pool);
1978
1979 dialog.render(Rect::new(0, 0, 80, 24), &mut frame, &mut state);
1981 }
1982
1983 #[test]
1984 fn edge_builder_hit_id() {
1985 let dialog = Dialog::custom("T", "M")
1986 .ok_button()
1987 .hit_id(HitId::new(42))
1988 .build();
1989 assert_eq!(dialog.hit_id, Some(HitId::new(42)));
1990 }
1991
1992 #[test]
1993 fn edge_builder_modal_config() {
1994 let config = ModalConfig::default().position(ModalPosition::TopCenter { margin: 5 });
1995 let dialog = Dialog::custom("T", "M")
1996 .ok_button()
1997 .modal_config(config)
1998 .build();
1999 assert_eq!(
2000 dialog.config.modal_config.position,
2001 ModalPosition::TopCenter { margin: 5 }
2002 );
2003 }
2004
2005 #[test]
2006 fn edge_builder_modal_config_syncs_hit_id() {
2007 let dialog = Dialog::custom("T", "M")
2008 .ok_button()
2009 .modal_config(ModalConfig::default().hit_id(HitId::new(42)))
2010 .build();
2011 assert_eq!(dialog.hit_id, Some(HitId::new(42)));
2012 }
2013
2014 #[test]
2015 fn edge_content_height_alert() {
2016 let dialog = Dialog::alert("Title", "Message");
2017 let h = dialog.content_height();
2018 assert_eq!(h, 5);
2020 }
2021
2022 #[test]
2023 fn edge_content_height_prompt() {
2024 let dialog = Dialog::prompt("Title", "Message");
2025 let h = dialog.content_height();
2026 assert_eq!(h, 7);
2028 }
2029
2030 #[test]
2031 fn edge_content_height_empty_title_and_message() {
2032 let dialog = Dialog::alert("", "");
2033 let h = dialog.content_height();
2034 assert_eq!(h, 4);
2036 }
2037
2038 #[test]
2039 fn edge_button_display_width_unicode() {
2040 let button = DialogButton::new("保存", "save");
2041 assert_eq!(button.display_width(), 8);
2043 }
2044
2045 #[test]
2046 fn edge_dialog_result_equality() {
2047 assert_eq!(DialogResult::Ok, DialogResult::Ok);
2048 assert_eq!(DialogResult::Cancel, DialogResult::Cancel);
2049 assert_eq!(DialogResult::Dismissed, DialogResult::Dismissed);
2050 assert_eq!(
2051 DialogResult::Custom("a".into()),
2052 DialogResult::Custom("a".into())
2053 );
2054 assert_ne!(
2055 DialogResult::Custom("a".into()),
2056 DialogResult::Custom("b".into())
2057 );
2058 assert_eq!(
2059 DialogResult::Input("x".into()),
2060 DialogResult::Input("x".into())
2061 );
2062 assert_ne!(DialogResult::Ok, DialogResult::Cancel);
2063 }
2064
2065 #[test]
2066 fn edge_mouse_down_mismatched_hit_id() {
2067 let dialog = Dialog::confirm("Test", "Msg").hit_id(HitId::new(1));
2068 let mut state = DialogState::new();
2069
2070 let down = Event::Mouse(MouseEvent::new(
2071 MouseEventKind::Down(MouseButton::Left),
2072 0,
2073 0,
2074 ));
2075 let hit = Some((HitId::new(99), HitRegion::Button, 0u64));
2077 dialog.handle_event(&down, &mut state, hit);
2078 assert_eq!(state.pressed_button, None);
2079 assert_eq!(state.focused_button, None);
2080 }
2081
2082 #[test]
2083 fn mouse_down_outside_cancels_existing_pressed_button() {
2084 let dialog = Dialog::confirm("Test", "Msg").hit_id(HitId::new(1));
2085 let mut state = DialogState::new();
2086
2087 let down = Event::Mouse(MouseEvent::new(
2088 MouseEventKind::Down(MouseButton::Left),
2089 0,
2090 0,
2091 ));
2092 let hit0 = Some((HitId::new(1), HitRegion::Button, 0u64));
2093 dialog.handle_event(&down, &mut state, hit0);
2094 assert_eq!(state.pressed_button, Some(0));
2095
2096 dialog.handle_event(&down, &mut state, None);
2097 assert_eq!(state.pressed_button, None);
2098
2099 let up = Event::Mouse(MouseEvent::new(MouseEventKind::Up(MouseButton::Left), 0, 0));
2100 let result = dialog.handle_event(&up, &mut state, hit0);
2101 assert_eq!(result, None);
2102 assert!(state.is_open());
2103 }
2104
2105 #[test]
2106 fn mouse_down_mismatched_hit_id_cancels_existing_pressed_button() {
2107 let dialog = Dialog::confirm("Test", "Msg").hit_id(HitId::new(1));
2108 let mut state = DialogState::new();
2109
2110 let down = Event::Mouse(MouseEvent::new(
2111 MouseEventKind::Down(MouseButton::Left),
2112 0,
2113 0,
2114 ));
2115 let hit0 = Some((HitId::new(1), HitRegion::Button, 0u64));
2116 dialog.handle_event(&down, &mut state, hit0);
2117 assert_eq!(state.pressed_button, Some(0));
2118
2119 let wrong_hit = Some((HitId::new(99), HitRegion::Button, 1u64));
2120 dialog.handle_event(&down, &mut state, wrong_hit);
2121 assert_eq!(state.pressed_button, None);
2122 assert_eq!(state.focused_button, Some(0));
2123
2124 let up = Event::Mouse(MouseEvent::new(MouseEventKind::Up(MouseButton::Left), 0, 0));
2125 let result = dialog.handle_event(&up, &mut state, hit0);
2126 assert_eq!(result, None);
2127 assert!(state.is_open());
2128 }
2129
2130 #[test]
2131 fn edge_mouse_down_out_of_bounds_index() {
2132 let dialog = Dialog::confirm("Test", "Msg").hit_id(HitId::new(1));
2133 let mut state = DialogState::new();
2134
2135 let down = Event::Mouse(MouseEvent::new(
2136 MouseEventKind::Down(MouseButton::Left),
2137 0,
2138 0,
2139 ));
2140 let hit = Some((HitId::new(1), HitRegion::Button, 99u64));
2142 dialog.handle_event(&down, &mut state, hit);
2143 assert_eq!(state.pressed_button, None);
2144 }
2145
2146 #[test]
2147 fn edge_mouse_up_different_button_from_pressed() {
2148 let dialog = Dialog::confirm("Test", "Msg").hit_id(HitId::new(1));
2149 let mut state = DialogState::new();
2150
2151 let down = Event::Mouse(MouseEvent::new(
2153 MouseEventKind::Down(MouseButton::Left),
2154 0,
2155 0,
2156 ));
2157 let hit0 = Some((HitId::new(1), HitRegion::Button, 0u64));
2158 dialog.handle_event(&down, &mut state, hit0);
2159 assert_eq!(state.pressed_button, Some(0));
2160
2161 let up = Event::Mouse(MouseEvent::new(MouseEventKind::Up(MouseButton::Left), 0, 0));
2163 let hit1 = Some((HitId::new(1), HitRegion::Button, 1u64));
2164 let result = dialog.handle_event(&up, &mut state, hit1);
2165 assert_eq!(result, None);
2166 assert!(state.is_open());
2167 assert_eq!(state.pressed_button, None);
2169 }
2170
2171 #[test]
2172 fn edge_non_prompt_clears_input_focused() {
2173 let dialog = Dialog::alert("Test", "Msg");
2174 let mut state = DialogState::new();
2175 state.input_focused = true;
2177
2178 let tab = Event::Key(KeyEvent {
2179 code: KeyCode::Tab,
2180 modifiers: Modifiers::empty(),
2181 kind: KeyEventKind::Press,
2182 });
2183 dialog.handle_event(&tab, &mut state, None);
2184 assert!(!state.input_focused);
2186 }
2187
2188 #[test]
2189 fn edge_key_release_ignored() {
2190 let dialog = Dialog::prompt("Test", "Enter:");
2191 let mut state = DialogState::new();
2192 state.input_value.clear();
2193
2194 let release = Event::Key(KeyEvent {
2196 code: KeyCode::Char('x'),
2197 modifiers: Modifiers::empty(),
2198 kind: KeyEventKind::Release,
2199 });
2200 dialog.handle_event(&release, &mut state, None);
2201 assert!(state.input_value.is_empty());
2202 }
2203
2204 #[test]
2205 fn edge_enter_no_focused_no_primary_does_nothing() {
2206 let dialog = Dialog::custom("Test", "Msg")
2208 .custom_button("A", "a")
2209 .custom_button("B", "b")
2210 .build();
2211 let mut state = DialogState::new();
2212 state.input_focused = false;
2213 state.focused_button = None;
2214
2215 let enter = Event::Key(KeyEvent {
2216 code: KeyCode::Enter,
2217 modifiers: Modifiers::empty(),
2218 kind: KeyEventKind::Press,
2219 });
2220 let result = dialog.handle_event(&enter, &mut state, None);
2222 assert_eq!(result, None);
2223 assert!(state.is_open());
2224 }
2225
2226 #[test]
2227 fn edge_dialog_style_setters() {
2228 let style = Style::new().bold();
2229 let dialog = Dialog::alert("T", "M")
2230 .button_style(style)
2231 .primary_button_style(style)
2232 .focused_button_style(style);
2233 assert_eq!(dialog.config.button_style, style);
2234 assert_eq!(dialog.config.primary_button_style, style);
2235 assert_eq!(dialog.config.focused_button_style, style);
2236 }
2237
2238 #[test]
2239 fn edge_dialog_modal_config_setter() {
2240 let mc = ModalConfig::default().position(ModalPosition::Custom { x: 10, y: 20 });
2241 let dialog = Dialog::alert("T", "M").modal_config(mc);
2242 assert_eq!(
2243 dialog.config.modal_config.position,
2244 ModalPosition::Custom { x: 10, y: 20 }
2245 );
2246 }
2247
2248 #[test]
2249 fn edge_dialog_modal_config_setter_syncs_hit_id() {
2250 let dialog =
2251 Dialog::alert("T", "M").modal_config(ModalConfig::default().hit_id(HitId::new(9)));
2252 assert_eq!(dialog.hit_id, Some(HitId::new(9)));
2253 }
2254
2255 #[test]
2256 fn edge_dialog_clone_debug() {
2257 let dialog = Dialog::alert("T", "M");
2258 let cloned = dialog.clone();
2259 assert_eq!(cloned.title, dialog.title);
2260 assert_eq!(cloned.message, dialog.message);
2261 let _ = format!("{:?}", dialog);
2262 }
2263
2264 #[test]
2265 fn edge_dialog_builder_clone_debug() {
2266 let builder = Dialog::custom("T", "M").ok_button();
2267 let cloned = builder.clone();
2268 assert_eq!(cloned.title, builder.title);
2269 let _ = format!("{:?}", builder);
2270 }
2271
2272 #[test]
2273 fn edge_dialog_config_clone_debug() {
2274 let config = DialogConfig::default();
2275 let cloned = config.clone();
2276 assert_eq!(cloned.kind, config.kind);
2277 let _ = format!("{:?}", config);
2278 }
2279
2280 #[test]
2281 fn edge_dialog_state_clone_debug() {
2282 let mut state = DialogState::new();
2283 state.input_value = "test".to_string();
2284 state.focused_button = Some(1);
2285 let cloned = state.clone();
2286 assert_eq!(cloned.input_value, "test");
2287 assert_eq!(cloned.focused_button, Some(1));
2288 assert_eq!(cloned.open, state.open);
2289 let _ = format!("{:?}", state);
2290 }
2291
2292 #[test]
2293 fn edge_dialog_button_clone_debug() {
2294 let button = DialogButton::new("Save", "save").primary();
2295 let cloned = button.clone();
2296 assert_eq!(cloned.label, "Save");
2297 assert_eq!(cloned.id, "save");
2298 assert!(cloned.primary);
2299 let _ = format!("{:?}", button);
2300 }
2301
2302 #[test]
2303 fn edge_dialog_result_clone_debug() {
2304 let results = [
2305 DialogResult::Ok,
2306 DialogResult::Cancel,
2307 DialogResult::Dismissed,
2308 DialogResult::Custom("x".into()),
2309 DialogResult::Input("y".into()),
2310 ];
2311 for r in &results {
2312 let cloned = r.clone();
2313 assert_eq!(&cloned, r);
2314 let _ = format!("{:?}", r);
2315 }
2316 }
2317
2318 #[test]
2319 fn edge_dialog_kind_clone_debug_eq() {
2320 let kinds = [
2321 DialogKind::Alert,
2322 DialogKind::Confirm,
2323 DialogKind::Prompt,
2324 DialogKind::Custom,
2325 ];
2326 for k in &kinds {
2327 let cloned = *k;
2328 assert_eq!(cloned, *k);
2329 let _ = format!("{:?}", k);
2330 }
2331 assert_ne!(DialogKind::Alert, DialogKind::Confirm);
2332 }
2333}