aboutsummaryrefslogtreecommitdiff
path: root/src/widgets.rs
blob: 52eff3c0c2a17245fb019884640d86dc2e1aa5db (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
//! bevy_terminal_display widgets for dialog boxes

use bevy::prelude::*;
use bevy_terminal_display::{crossterm, ratatui::{layout::{Alignment, Constraint, Flex, Layout}, style::Style, text::{Line, Span}, widgets::{Block, Borders, Clear, HighlightSpacing, List, ListItem, ListState, Padding, Paragraph, Wrap}}, widgets::TerminalWidget};
use yarnspinner::runtime::DialogueOption;
use unicode_segmentation::UnicodeSegmentation as _;
use arbitrary_chunks::ArbitraryChunks as _;

/// Interaction tooltip widget marker
// TODO: Move tooltip out of this crate?
#[derive(Component)]
pub struct InteractTooltip;

/// Interaction tooltip widget
pub struct InteractTooltipWidget;

impl TerminalWidget for InteractTooltipWidget {
    fn render(
        &mut self,
        frame: &mut bevy_terminal_display::ratatui::Frame,
        rect: bevy_terminal_display::ratatui::prelude::Rect,
    ) {
        let text = Paragraph::new("E")
            .block(
                Block::new()
                    .borders(Borders::ALL)
                    .padding(Padding::horizontal(1)),
            )
            .alignment(Alignment::Center);
        let [area] = Layout::horizontal([Constraint::Length(5)])
            .flex(Flex::Center)
            .areas(rect);
        let [area] = Layout::vertical([Constraint::Length(3)])
            .flex(Flex::Center)
            .areas(area);
        frame.render_widget(Clear, area);
        frame.render_widget(text, area);
    }
}

/// Dialog box widget marker
#[derive(Component)]
pub struct DialogBox;

/// Dialog box widget
#[derive(Default)]
pub struct DialogBoxWidget {
    /// Name of speaking character
    pub character: Option<String>,
    /// Chunks of text and corresponding styles representing the currently spoken line
    pub text: Vec<(String, Style)>,
}

impl TerminalWidget for DialogBoxWidget {
    fn render(
        &mut self,
        frame: &mut bevy_terminal_display::ratatui::Frame,
        rect: bevy_terminal_display::ratatui::prelude::Rect,
    ) {
        let text = Paragraph::new(bevy_terminal_display::ratatui::text::Line::from(
            self.text
                .iter()
                .map(|(text, style)| Span::styled(text, *style))
                .collect::<Vec<_>>(),
        ))
        .wrap(Wrap { trim: true })
        .block({
            let mut block = Block::new()
                .borders(Borders::ALL)
                .padding(Padding::horizontal(1));
            if let Some(character) = &self.character {
                block = block.title(character.clone());
            }
            block
        });
        let [area] = Layout::horizontal([Constraint::Max(100)])
            .flex(Flex::Center)
            .areas(rect);
        let [area] = Layout::vertical([Constraint::Max(10)])
            .flex(Flex::End)
            .areas(area);
        frame.render_widget(Clear, area);
        frame.render_widget(text, area);
    }
}

/// Option selection box widget marker
#[derive(Component)]
pub struct OptionsBox;

/// Option selection box widget
#[derive(Default)]
pub struct OptionsBoxWidget {
    /// State of ratatui list widget
    pub state: ListState,
    /// Available dialog options
    pub options: Vec<(DialogueOption, Vec<(String, Style)>)>,
}

impl TerminalWidget for OptionsBoxWidget {
    fn render(
        &mut self,
        frame: &mut bevy_terminal_display::ratatui::Frame,
        rect: bevy_terminal_display::ratatui::prelude::Rect,
    ) {
        let terminal_size = crossterm::terminal::size().unwrap();
        let box_size: u16 = if terminal_size.0 > 40 { 20 } else { 10 };
        let items = self
            .options
            .iter()
            .map(|option| {
                let option_spans = option
                    .1
                    .iter()
                    .map(|(text, style)| Span::styled(text, *style))
                    .collect::<Vec<_>>();
                let string_chunks = textwrap::wrap(
                    &Line::from(option_spans.clone()).to_string(),
                    textwrap::Options::new(box_size as usize),
                )
                .into_iter()
                .map(|chunk| chunk.graphemes(true).count())
                .collect::<Vec<_>>();

                let line = Line::from(option_spans);
                let graphemes = line.styled_graphemes(Style::default()).collect::<Vec<_>>();

                let mut final_string_chunks = vec![];
                let mut i = 0;
                for string_chunk in string_chunks {
                    final_string_chunks.push(string_chunk);
                    i += string_chunk;
                    if let Some(grapheme) = graphemes.get(i) {
                        if grapheme.symbol == " " {
                            final_string_chunks.push(1);
                            i += 1;
                        }
                    }
                }

                let mut chunked_graphemes = graphemes
                    .arbitrary_chunks(&final_string_chunks)
                    .collect::<Vec<_>>();
                chunked_graphemes.retain(|chunk| !(chunk.len() == 1 && chunk[0].symbol == " "));

                let line = chunked_graphemes
                    .into_iter()
                    .map(|chunk| {
                        Line::from(
                            chunk
                                .iter()
                                .map(|grapheme| {
                                    Span::styled(grapheme.symbol.to_string(), grapheme.style)
                                })
                                .collect::<Vec<_>>(),
                        )
                    })
                    .collect::<Vec<_>>();
                ListItem::new(line)
            })
            .collect::<Vec<_>>();

        let height = items.iter().fold(0, |acc, item| acc + item.height());

        let outer_block = Block::bordered().padding(Padding::horizontal(1));
        let list = List::new(items)
            .block(outer_block)
            .highlight_symbol("-> ")
            .highlight_spacing(HighlightSpacing::Always);

        let [area] = Layout::horizontal([Constraint::Length(box_size + 7)])
            .flex(Flex::Center)
            .areas(rect);
        let [area] = Layout::vertical([Constraint::Length(height as u16 + 2)])
            .flex(Flex::Center)
            .areas(area);

        frame.render_widget(Clear, area);
        frame.render_stateful_widget(list, area, &mut self.state);
    }
}