a3s-tui 0.1.14

TEA (The Elm Architecture) framework for terminal user interfaces
Documentation
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use super::Markdown;
use crate::element::{BoxElement, Element, FlexDirection, TextElement, TextStyle};
use crate::style::{
    ansi_escape_sequence_end, next_display_cell_boundary, osc8_link_target,
    split_lines_preserving_trailing_blank, Color, Style,
};

#[derive(Clone)]
struct StyledGrapheme {
    text: String,
    style: RenderStyle,
    width: usize,
}

#[derive(Clone, Default)]
struct RenderStyle {
    text: crate::element::TextStyle,
    hyperlink: Option<String>,
}

pub(super) fn wrap_styled_text(text: &str, width: usize) -> Vec<String> {
    if width == 0 {
        return vec![text.to_string()];
    }

    let mut words = Vec::<(Vec<StyledGrapheme>, Option<RenderStyle>)>::new();
    let mut word = Vec::new();
    let mut separator_before = None;
    let mut pending_separator = None;
    for segment in ansi_segments(text) {
        let segment_style = RenderStyle {
            text: segment.style.clone(),
            hyperlink: segment.hyperlink.clone(),
        };
        let mut offset = 0usize;
        while offset < segment.text.len() {
            let Some((end, cluster_width)) = next_display_cell_boundary(&segment.text, offset)
            else {
                break;
            };
            let cluster = &segment.text[offset..end];
            offset = end;
            if cluster.chars().all(char::is_whitespace) {
                if !word.is_empty() {
                    words.push((std::mem::take(&mut word), separator_before.take()));
                }
                pending_separator.get_or_insert_with(|| segment_style.clone());
            } else {
                if word.is_empty() {
                    separator_before = pending_separator.take();
                }
                word.push(StyledGrapheme {
                    text: cluster.to_string(),
                    style: segment_style.clone(),
                    width: cluster_width,
                });
            }
        }
    }
    if !word.is_empty() {
        words.push((word, separator_before));
    }
    if words.is_empty() {
        return vec![String::new()];
    }

    let mut rows = Vec::<Vec<StyledGrapheme>>::new();
    let mut row = Vec::new();
    let mut row_width = 0usize;
    for (word, separator_style) in words {
        let word_width = word.iter().map(|cluster| cluster.width).sum::<usize>();
        let separator_width = usize::from(!row.is_empty());
        if !row.is_empty() && row_width + separator_width + word_width > width {
            rows.push(std::mem::take(&mut row));
            row_width = 0;
        }
        if word_width <= width {
            if !row.is_empty() {
                row.push(StyledGrapheme {
                    text: " ".to_string(),
                    style: separator_style.unwrap_or_default(),
                    width: 1,
                });
                row_width += 1;
            }
            row_width += word_width;
            row.extend(word);
            continue;
        }

        if !row.is_empty() {
            rows.push(std::mem::take(&mut row));
            row_width = 0;
        }
        for cluster in word {
            if row_width > 0 && row_width + cluster.width > width {
                rows.push(std::mem::take(&mut row));
                row_width = 0;
            }
            row_width += cluster.width;
            row.push(cluster);
        }
    }
    if !row.is_empty() {
        rows.push(row);
    }
    rows.into_iter().map(render_styled_graphemes).collect()
}

fn render_styled_graphemes(graphemes: Vec<StyledGrapheme>) -> String {
    let mut rendered = String::new();
    let mut run = String::new();
    let mut run_style = RenderStyle::default();
    let mut has_run = false;
    for grapheme in graphemes {
        if has_run && !same_render_style(&run_style, &grapheme.style) {
            rendered.push_str(&render_text_style(&run_style, &run));
            run.clear();
        }
        if !has_run || !same_render_style(&run_style, &grapheme.style) {
            run_style = grapheme.style;
            has_run = true;
        }
        run.push_str(&grapheme.text);
    }
    if has_run {
        rendered.push_str(&render_text_style(&run_style, &run));
    }
    rendered
}

fn same_render_style(a: &RenderStyle, b: &RenderStyle) -> bool {
    same_text_style(&a.text, &b.text) && a.hyperlink == b.hyperlink
}

fn same_text_style(a: &crate::element::TextStyle, b: &crate::element::TextStyle) -> bool {
    a.fg == b.fg
        && a.bg == b.bg
        && a.bold == b.bold
        && a.italic == b.italic
        && a.underline == b.underline
        && a.reverse == b.reverse
        && a.dim == b.dim
        && a.strikethrough == b.strikethrough
}

fn render_text_style(style: &RenderStyle, text: &str) -> String {
    let mut terminal_style = Style::new();
    if let Some(color) = style.text.fg {
        terminal_style = terminal_style.fg(color);
    }
    if let Some(color) = style.text.bg {
        terminal_style = terminal_style.bg(color);
    }
    if style.text.bold {
        terminal_style = terminal_style.bold();
    }
    if style.text.italic {
        terminal_style = terminal_style.italic();
    }
    if style.text.underline {
        terminal_style = terminal_style.underline();
    }
    if style.text.reverse {
        terminal_style = terminal_style.reverse();
    }
    if style.text.dim {
        terminal_style = terminal_style.dim();
    }
    if style.text.strikethrough {
        terminal_style = terminal_style.strikethrough();
    }
    let rendered = if same_text_style(&style.text, &crate::element::TextStyle::default()) {
        text.to_string()
    } else {
        terminal_style.render(text)
    };
    if let Some(target) = &style.hyperlink {
        format!("\x1b]8;;{target}\x1b\\{rendered}\x1b]8;;\x1b\\")
    } else {
        rendered
    }
}

pub(super) struct StyledSegment {
    pub(super) text: String,
    pub(super) style: TextStyle,
    hyperlink: Option<String>,
}

impl Markdown {
    pub fn render_element<Msg>(&self, input: &str) -> Element<Msg> {
        let rendered = self.render(input);
        rendered_markdown_element(&rendered)
    }
}

pub(crate) fn rendered_markdown_element<Msg>(rendered: &str) -> Element<Msg> {
    let children: Vec<Element<Msg>> = split_rendered_lines(rendered)
        .into_iter()
        .map(ansi_line_element)
        .collect();

    Element::Box(
        BoxElement::new()
            .direction(FlexDirection::Column)
            .children(children),
    )
}

pub(crate) fn split_rendered_lines(rendered: &str) -> Vec<&str> {
    if rendered.is_empty() {
        Vec::new()
    } else {
        split_lines_preserving_trailing_blank(rendered)
    }
}

fn ansi_line_element<Msg>(line: &str) -> Element<Msg> {
    let segments = ansi_segments(line);
    if segments.len() == 1 {
        let Some(segment) = segments.into_iter().next() else {
            return Element::Text(TextElement::new(""));
        };
        return Element::Text(segment_text(segment));
    }

    Element::Box(
        BoxElement::new().direction(FlexDirection::Row).children(
            segments
                .into_iter()
                .map(|segment| Element::Text(segment_text(segment)))
                .collect(),
        ),
    )
}

fn segment_text(segment: StyledSegment) -> TextElement {
    let mut text = TextElement::new(segment.text);
    text.style = segment.style;
    text
}

pub(super) fn ansi_segments(line: &str) -> Vec<StyledSegment> {
    let mut segments = Vec::new();
    let mut current = String::new();
    let mut style = TextStyle::default();
    let mut hyperlink = None;
    let mut index = 0usize;

    while index < line.len() {
        if let Some(end) = ansi_escape_sequence_end(line, index) {
            let sequence = &line[index..end];
            if let Some(params) = sequence
                .strip_prefix("\x1b[")
                .and_then(|value| value.strip_suffix('m'))
            {
                push_segment(&mut segments, &mut current, &style, &hyperlink);
                apply_sgr_sequence(&mut style, params);
            } else if let Some(target) = osc8_link_target(sequence) {
                push_segment(&mut segments, &mut current, &style, &hyperlink);
                hyperlink = (!target.is_empty()).then(|| target.to_string());
            }
            index = end;
            continue;
        }
        let ch = line[index..].chars().next().unwrap_or_default();
        current.push(ch);
        index += ch.len_utf8();
    }

    push_segment(&mut segments, &mut current, &style, &hyperlink);
    if segments.is_empty() {
        segments.push(StyledSegment {
            text: String::new(),
            style: TextStyle::default(),
            hyperlink: None,
        });
    }
    segments
}

pub(super) fn trailing_background(line: &str) -> Option<Color> {
    ansi_segments(line)
        .into_iter()
        .rev()
        .find(|segment| {
            segment
                .text
                .chars()
                .any(|ch| !ch.is_control() && ch != '\u{200b}')
        })
        .and_then(|segment| segment.style.bg)
}

fn push_segment(
    segments: &mut Vec<StyledSegment>,
    current: &mut String,
    style: &TextStyle,
    hyperlink: &Option<String>,
) {
    if current.is_empty() {
        return;
    }

    segments.push(StyledSegment {
        text: std::mem::take(current),
        style: style.clone(),
        hyperlink: hyperlink.clone(),
    });
}

fn apply_sgr_sequence(style: &mut TextStyle, sequence: &str) {
    if sequence.is_empty() {
        *style = TextStyle::default();
        return;
    }

    let codes: Vec<u16> = sequence
        .split(';')
        .filter_map(|part| {
            if part.is_empty() {
                Some(0)
            } else {
                part.parse().ok()
            }
        })
        .collect();
    if codes.is_empty() {
        *style = TextStyle::default();
        return;
    }

    let mut index = 0usize;
    while index < codes.len() {
        match codes[index] {
            0 => *style = TextStyle::default(),
            1 => style.bold = true,
            2 => style.dim = true,
            3 => style.italic = true,
            4 => style.underline = true,
            7 => style.reverse = true,
            9 => style.strikethrough = true,
            22 => {
                style.bold = false;
                style.dim = false;
            }
            23 => style.italic = false,
            24 => style.underline = false,
            27 => style.reverse = false,
            29 => style.strikethrough = false,
            30..=37 | 90..=97 => style.fg = basic_sgr_color(codes[index]),
            39 => style.fg = None,
            40..=47 | 100..=107 => style.bg = basic_sgr_color(codes[index] - 10),
            49 => style.bg = None,
            38 | 48 => {
                let is_fg = codes[index] == 38;
                if let Some((color, consumed)) = extended_sgr_color(&codes[index + 1..]) {
                    if is_fg {
                        style.fg = Some(color);
                    } else {
                        style.bg = Some(color);
                    }
                    index += consumed;
                }
            }
            _ => {}
        }
        index += 1;
    }
}

fn basic_sgr_color(code: u16) -> Option<Color> {
    match code {
        30 => Some(Color::Black),
        31 => Some(Color::Red),
        32 => Some(Color::Green),
        33 => Some(Color::Yellow),
        34 => Some(Color::Blue),
        35 => Some(Color::Magenta),
        36 => Some(Color::Cyan),
        37 => Some(Color::White),
        90 => Some(Color::BrightBlack),
        91 => Some(Color::BrightRed),
        92 => Some(Color::BrightGreen),
        93 => Some(Color::BrightYellow),
        94 => Some(Color::BrightBlue),
        95 => Some(Color::BrightMagenta),
        96 => Some(Color::BrightCyan),
        97 => Some(Color::BrightWhite),
        _ => None,
    }
}

fn extended_sgr_color(codes: &[u16]) -> Option<(Color, usize)> {
    match codes {
        [5, value, ..] => Some((Color::Ansi256((*value).min(u8::MAX as u16) as u8), 2)),
        [2, r, g, b, ..] => Some((
            Color::Rgb(
                (*r).min(u8::MAX as u16) as u8,
                (*g).min(u8::MAX as u16) as u8,
                (*b).min(u8::MAX as u16) as u8,
            ),
            4,
        )),
        _ => None,
    }
}