Popup screen can display large texts

This commit is contained in:
2022-10-08 14:54:07 +02:00
parent dc634fc6bc
commit 7e6d18c252
4 changed files with 47 additions and 8 deletions

View File

@ -16,4 +16,5 @@ lazy_static = "1.4.0"
tokio = "1.21.2"
num = "0.4.0"
num-traits = "0.2.15"
num-derive = "0.3.3"
num-derive = "0.3.3"
textwrap = "0.15.1"

View File

@ -22,7 +22,7 @@ async fn run_app<B: Backend>(terminal: &mut Terminal<B>) -> Result<(), Box<dyn E
/*let mut rules = GameRules::default();
rules.boats_can_touch = true;
let res = set_boats_layout::set_boat_layout(&rules, terminal)?; // select_bot_type::select_bot_type(terminal)?;*/
let res = popup_screen::popup_screen("Hello you are my guest today!", terminal);
let res = popup_screen::popup_screen("Hi\nWelcome there", terminal);
Err(io::Error::new(
ErrorKind::Other,
format!("result: {:?}", res),

View File

@ -5,7 +5,6 @@ use crossterm::event;
use crossterm::event::{Event, KeyCode};
use tui::backend::Backend;
use tui::layout::*;
use tui::style::*;
use tui::text::*;
use tui::widgets::*;
use tui::{Frame, Terminal};
@ -55,7 +54,11 @@ pub fn popup_screen<B: Backend>(
}
fn ui<B: Backend>(f: &mut Frame<B>, model: &mut PopupScreen) {
let area = centered_rect_size(model.msg.len() as u16 + 2, 5, &f.size());
// Preprocess message
let lines = textwrap::wrap(model.msg, f.size().width as usize - 20);
let line_max_len = lines.iter().map(|l| l.len()).max().unwrap();
let area = centered_rect_size(line_max_len as u16 + 4, 5 + lines.len() as u16, &f.size());
let block = Block::default().borders(Borders::ALL).title(model.title);
f.render_widget(block, area);
@ -63,14 +66,24 @@ fn ui<B: Backend>(f: &mut Frame<B>, model: &mut PopupScreen) {
// Create two chunks with equal horizontal screen space
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Percentage(70), Constraint::Percentage(30)].as_ref())
.constraints(
[
Constraint::Length(lines.len() as u16),
Constraint::Length(3),
]
.as_ref(),
)
.split(area.inner(&Margin {
horizontal: 1,
horizontal: 2,
vertical: 1,
}));
let text = Paragraph::new(model.msg);
f.render_widget(text, chunks[0]);
let text = lines
.iter()
.map(|s| Spans::from(s.as_ref()))
.collect::<Vec<_>>();
let paragraph = Paragraph::new(text);
f.render_widget(paragraph, chunks[0]);
let ok_button = ButtonWidget::new("OK", true);
f.render_widget(ok_button, chunks[1]);