promkit-widgets 0.7.0

Widgets for promkit
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
use promkit_core::{
    crossterm::style::{Attribute, ContentStyle},
    grapheme::StyledGraphemes,
};

use super::jsonz::{JsonNode, Row};
use crate::structured::{ContainerNode, ContainerType};

/// Defines the behavior for handling lines that
/// exceed the available width in the terminal when rendering JSON data.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OverflowMode {
    #[default]
    /// Truncates lines that exceed the available width
    /// and appends an ellipsis character (…).
    Truncate,
    /// Wraps lines that exceed the available width
    /// onto the next line without truncation.
    Wrap,
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(default))]
#[derive(Clone)]
pub struct Config {
    /// Style for {}.
    #[cfg_attr(
        feature = "serde",
        serde(with = "termcfg::crossterm_config::content_style_serde")
    )]
    pub curly_brackets_style: ContentStyle,
    /// Style for [].
    #[cfg_attr(
        feature = "serde",
        serde(with = "termcfg::crossterm_config::content_style_serde")
    )]
    pub square_brackets_style: ContentStyle,
    /// Style for "key".
    #[cfg_attr(
        feature = "serde",
        serde(with = "termcfg::crossterm_config::content_style_serde")
    )]
    pub key_style: ContentStyle,
    /// Style for string values.
    #[cfg_attr(
        feature = "serde",
        serde(with = "termcfg::crossterm_config::content_style_serde")
    )]
    pub string_value_style: ContentStyle,
    /// Style for number values.
    #[cfg_attr(
        feature = "serde",
        serde(with = "termcfg::crossterm_config::content_style_serde")
    )]
    pub number_value_style: ContentStyle,
    /// Style for boolean values.
    #[cfg_attr(
        feature = "serde",
        serde(with = "termcfg::crossterm_config::content_style_serde")
    )]
    pub boolean_value_style: ContentStyle,
    /// Style for null values.
    #[cfg_attr(
        feature = "serde",
        serde(with = "termcfg::crossterm_config::content_style_serde")
    )]
    pub null_value_style: ContentStyle,

    /// Attribute for the selected line.
    #[cfg_attr(
        feature = "serde",
        serde(with = "termcfg::crossterm_config::attribute_serde")
    )]
    pub active_item_attribute: Attribute,
    /// Attribute for unselected lines.
    #[cfg_attr(
        feature = "serde",
        serde(with = "termcfg::crossterm_config::attribute_serde")
    )]
    pub inactive_item_attribute: Attribute,

    /// The number of spaces used for indentation in the rendered JSON structure.
    /// This value multiplies with the indentation level of a JSON element to determine
    /// the total indentation space. For example, an `indent` value of 4 means each
    /// indentation level will be 4 spaces wide.
    pub indent: usize,

    /// Rendering behavior when a line exceeds the terminal width.
    pub overflow_mode: OverflowMode,
    /// Number of lines available for rendering.
    pub lines: Option<usize>,
    /// Whether to display stable one-based line numbers to the left of the content.
    pub show_line_numbers: bool,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            curly_brackets_style: Default::default(),
            square_brackets_style: Default::default(),
            key_style: Default::default(),
            string_value_style: Default::default(),
            number_value_style: Default::default(),
            boolean_value_style: Default::default(),
            null_value_style: Default::default(),
            active_item_attribute: Attribute::NoBold,
            inactive_item_attribute: Attribute::NoBold,
            indent: Default::default(),
            overflow_mode: OverflowMode::default(),
            lines: Default::default(),
            show_line_numbers: false,
        }
    }
}

impl Config {
    /// Formats a `Vec<Row>` into `Vec<StyledGraphemes>` with styling and width limits.
    pub fn render_terminal_rows(&self, rows: &[Row], width: u16) -> Vec<StyledGraphemes> {
        self.render_rows(rows, 0, Some(width as usize))
    }

    /// Formats width-independent rows for the core renderer.
    pub fn render_content_rows(&self, rows: &[Row], active_row: usize) -> Vec<StyledGraphemes> {
        self.render_rows(rows, active_row, None)
    }

    fn render_rows(
        &self,
        rows: &[Row],
        active_row: usize,
        width: Option<usize>,
    ) -> Vec<StyledGraphemes> {
        let mut formatted = Vec::new();

        for (i, row) in rows.iter().enumerate() {
            let indent = StyledGraphemes::from(" ".repeat(self.indent * row.depth));
            let mut parts = Vec::new();

            if let Some(key) = &row.key {
                parts.push(
                    StyledGraphemes::from(format!("\"{}\"", key)).apply_style(self.key_style),
                );
                parts.push(StyledGraphemes::from(": "));
            }

            match &row.node {
                JsonNode::Null => {
                    parts.push(StyledGraphemes::from("null").apply_style(self.null_value_style));
                }
                JsonNode::Boolean(b) => {
                    parts.push(
                        StyledGraphemes::from(b.to_string()).apply_style(self.boolean_value_style),
                    );
                }
                JsonNode::Number(n) => {
                    parts.push(
                        StyledGraphemes::from(n.to_string()).apply_style(self.number_value_style),
                    );
                }
                JsonNode::String(s) => {
                    let escaped = s.replace('\n', "\\n");
                    parts.push(
                        StyledGraphemes::from(format!("\"{}\"", escaped))
                            .apply_style(self.string_value_style),
                    );
                }
                JsonNode::Container(node) => match node {
                    ContainerNode::Empty { typ } => {
                        let bracket_style = match typ {
                            ContainerType::Object => self.curly_brackets_style,
                            ContainerType::Array => self.square_brackets_style,
                        };
                        parts.push(
                            StyledGraphemes::from(typ.empty_str()).apply_style(bracket_style),
                        );
                    }
                    ContainerNode::Open { typ, collapsed, .. } => {
                        let bracket_style = match typ {
                            ContainerType::Object => self.curly_brackets_style,
                            ContainerType::Array => self.square_brackets_style,
                        };
                        if *collapsed {
                            parts.push(
                                StyledGraphemes::from(typ.collapsed_preview())
                                    .apply_style(bracket_style),
                            );
                        } else {
                            parts.push(
                                StyledGraphemes::from(typ.open_str()).apply_style(bracket_style),
                            );
                        }
                    }
                    ContainerNode::Close { typ, .. } => {
                        let bracket_style = match typ {
                            ContainerType::Object => self.curly_brackets_style,
                            ContainerType::Array => self.square_brackets_style,
                        };
                        // We don't need to check collapsed here because:
                        // 1. If the corresponding Open is collapsed, this Close will be skipped during `extract_rows`
                        // 2. If the Open is not collapsed, we want to show the closing bracket
                        parts.push(
                            StyledGraphemes::from(typ.close_str()).apply_style(bracket_style),
                        );
                    }
                },
            }

            if i + 1 < rows.len() {
                let next_is_close = matches!(
                    &rows[i + 1].node,
                    JsonNode::Container(ContainerNode::Close { .. })
                );
                let current_is_open = matches!(
                    &rows[i].node,
                    JsonNode::Container(ContainerNode::Open {
                        collapsed: false,
                        ..
                    })
                );
                if !next_is_close && !current_is_open {
                    parts.push(StyledGraphemes::from(","));
                }
            }

            let mut content: StyledGraphemes = parts.into_iter().collect();

            // Note that `extract_rows_from_current`
            // returns rows starting from the current position,
            // so the first row should always be highlighted as active
            content = content.apply_attribute(if i == active_row {
                self.active_item_attribute
            } else {
                self.inactive_item_attribute
            });

            let mut line: StyledGraphemes = vec![indent, content].into_iter().collect();

            if let Some(width) = width {
                match self.overflow_mode {
                    OverflowMode::Truncate => {
                        line =
                            line.truncated_line_with_ellipsis(width, &StyledGraphemes::from(""));
                        formatted.push(line);
                    }
                    OverflowMode::Wrap => {
                        formatted.extend(line.wrapped_lines(width));
                    }
                }
            } else {
                formatted.push(line);
            }
        }

        formatted
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    mod config {
        use super::*;

        mod render_terminal_rows {
            use super::*;

            use crate::structured::json::jsonz::create_rows;

            #[test]
            fn truncate_mode_appends_an_ellipsis() {
                let value = json!({
                    "very_long_key": "abcdefghijklmnopqrstuvwxyz",
                });
                let rows = create_rows([&value]);
                let width = 12;

                let lines = Config {
                    indent: 2,
                    overflow_mode: OverflowMode::Truncate,
                    ..Default::default()
                }
                .render_terminal_rows(&rows, width);

                assert_eq!(lines.len(), rows.len());
                assert!(lines.iter().all(|line| line.widths() <= width as usize));
                assert!(
                    lines
                        .iter()
                        .any(|line| line.chars().last().is_some_and(|ch| *ch == ''))
                );
            }

            #[test]
            fn wrap_mode_wraps_without_an_ellipsis() {
                let value = json!({
                    "very_long_key": "abcdefghijklmnopqrstuvwxyz",
                });
                let rows = create_rows([&value]);
                let width = 12;

                let lines = Config {
                    indent: 2,
                    overflow_mode: OverflowMode::Wrap,
                    ..Default::default()
                }
                .render_terminal_rows(&rows, width);

                assert!(lines.len() > rows.len());
                assert!(lines.iter().all(|line| line.widths() <= width as usize));
                assert!(
                    lines
                        .iter()
                        .all(|line| !matches!(line.chars().last(), Some('')))
                );
            }
        }

        #[cfg(feature = "serde")]
        mod deserialize {
            use super::*;
            use promkit_core::crossterm::style::{Attributes, Color};

            #[test]
            fn missing_new_fields_are_filled_by_default() {
                let mut value = serde_json::to_value(Config {
                    indent: 4,
                    ..Default::default()
                })
                .unwrap();
                let obj = value.as_object_mut().unwrap();
                obj.remove("active_item_attribute");
                obj.remove("inactive_item_attribute");
                obj.remove("overflow_mode");
                obj.remove("lines");
                obj.remove("show_line_numbers");

                let formatter: Config = serde_json::from_value(value).unwrap();

                assert_eq!(formatter.indent, 4);
                assert_eq!(formatter.active_item_attribute, Attribute::NoBold);
                assert_eq!(formatter.inactive_item_attribute, Attribute::NoBold);
                assert_eq!(formatter.overflow_mode, OverflowMode::Truncate);
                assert_eq!(formatter.lines, None);
                assert!(!formatter.show_line_numbers);
            }

            #[test]
            fn loads_all_fields_from_toml() {
                let input = r#"
                indent = 4
                lines = 7
                show_line_numbers = true
                curly_brackets_style = "attr=bold"
                square_brackets_style = "attr=bold"
                key_style = "fg=cyan"
                string_value_style = "fg=green"
                number_value_style = "fg=yellow"
                boolean_value_style = "fg=magenta"
                null_value_style = "fg=grey"
                active_item_attribute = "underlined"
                inactive_item_attribute = "dim"
                overflow_mode = "Wrap"
            "#;

                let formatter: Config = toml::from_str(input).unwrap();

                assert_eq!(formatter.indent, 4);
                assert_eq!(formatter.lines, Some(7));
                assert!(formatter.show_line_numbers);
                assert_eq!(
                    formatter.curly_brackets_style.attributes,
                    Attributes::from(Attribute::Bold),
                );
                assert_eq!(
                    formatter.square_brackets_style.attributes,
                    Attributes::from(Attribute::Bold),
                );
                assert_eq!(formatter.key_style.foreground_color, Some(Color::Cyan));
                assert_eq!(
                    formatter.string_value_style.foreground_color,
                    Some(Color::Green),
                );
                assert_eq!(
                    formatter.number_value_style.foreground_color,
                    Some(Color::Yellow)
                );
                assert_eq!(
                    formatter.boolean_value_style.foreground_color,
                    Some(Color::Magenta),
                );
                assert_eq!(
                    formatter.null_value_style.foreground_color,
                    Some(Color::Grey)
                );
                assert_eq!(formatter.active_item_attribute, Attribute::Underlined);
                assert_eq!(formatter.inactive_item_attribute, Attribute::Dim);
                assert_eq!(formatter.overflow_mode, OverflowMode::Wrap);
            }
        }
    }
}