datui-lib 0.4.4

Data Exploration in the Terminal (library)
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//! Chart export dialog: where, in what format, style and size, with what legend,
//! and the words around the chart. Its keys are the shared form keys
//! (`crate::app::form`).

use crate::chart::chart_export::{
    ChartExportFormat, ExportStyle, LegendPlace, LineWidth, PointOpacity, PointSize, SizePreset,
};
use crate::chart::chart_modal::Mark;
use crate::widgets::text_input::TextInput;
use std::path::Path;

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum ChartExportFocus {
    #[default]
    PathInput,
    Format,
    Style,
    Size,
    WidthInput,
    HeightInput,
    Legend,
    PointOpacity,
    PointSize,
    LineWidth,
    YFromZero,
    TitleInput,
    DescriptionInput,
    NotesInput,
    SourceInput,
    BylineInput,
    Recipe,
}

impl ChartExportFocus {
    /// Whether the field is typed into; every other one is a choice. Every field is
    /// named, so a new one has to say which it is.
    pub fn is_text(self) -> bool {
        match self {
            Self::PathInput
            | Self::WidthInput
            | Self::HeightInput
            | Self::TitleInput
            | Self::DescriptionInput
            | Self::NotesInput
            | Self::SourceInput
            | Self::BylineInput => true,
            Self::Format
            | Self::Style
            | Self::Size
            | Self::Legend
            | Self::PointOpacity
            | Self::PointSize
            | Self::LineWidth
            | Self::YFromZero
            | Self::Recipe => false,
        }
    }

    /// The field's label.
    pub fn label(self) -> &'static str {
        FIELDS
            .iter()
            .find(|(field, _)| *field == self)
            .map_or("", |(_, label)| label)
    }
}

/// The fields in order, top to bottom, with their labels; the marks' rows show only
/// for the chart types they change ([`ChartExportModal::shows`]).
pub const FIELDS: [(ChartExportFocus, &str); 17] = [
    (ChartExportFocus::PathInput, "Path:"),
    (ChartExportFocus::Format, "Format:"),
    (ChartExportFocus::Style, "Style:"),
    (ChartExportFocus::Size, "Size:"),
    (ChartExportFocus::WidthInput, "Width:"),
    (ChartExportFocus::HeightInput, "Height:"),
    (ChartExportFocus::Legend, "Legend:"),
    (ChartExportFocus::PointOpacity, "Opacity:"),
    (ChartExportFocus::PointSize, "Point size:"),
    (ChartExportFocus::LineWidth, "Line width:"),
    (ChartExportFocus::YFromZero, "Y from zero:"),
    (ChartExportFocus::TitleInput, "Title:"),
    (ChartExportFocus::DescriptionInput, "Description:"),
    (ChartExportFocus::NotesInput, "Notes:"),
    (ChartExportFocus::SourceInput, "Source:"),
    (ChartExportFocus::BylineInput, "Byline:"),
    (ChartExportFocus::Recipe, "Recipe:"),
];

/// What the chart being exported brings to the dialog.
#[derive(Debug, Clone, Default)]
pub struct ExportDefaults {
    /// What the chart is: the description, until it is changed.
    pub description: String,
    /// Where the data comes from: the catalog entry's publisher and license.
    pub source: String,
    /// Whether the chart shows its legend; off carries over to the file.
    pub legend: bool,
    /// The chart's type: which mark rows the dialog offers.
    pub mark: Mark,
    /// A line chart's Y from zero, as drawn.
    pub y_from_zero: bool,
}

pub struct ChartExportModal {
    pub focus: ChartExportFocus,
    pub format: ChartExportFormat,
    pub style: ExportStyle,
    pub size: SizePreset,
    /// Pixels per inch: the last preset's, which a custom size keeps, so typing a
    /// width does not change the text's size on the page.
    pub dpi: f32,
    pub legend: LegendPlace,
    /// The chart being exported, for which mark rows apply.
    pub mark: Mark,
    pub point_opacity: PointOpacity,
    pub point_size: PointSize,
    pub line_width: LineWidth,
    pub y_from_zero: bool,
    pub path_input: TextInput,
    pub width_input: TextInput,
    pub height_input: TextInput,
    pub title_input: TextInput,
    pub description_input: TextInput,
    pub notes_input: TextInput,
    pub source_input: TextInput,
    pub byline_input: TextInput,
    /// Whether the file carries how the chart was made: the source path, query,
    /// chart and sample. Starts from `chart.export_recipe`, then stays as last set.
    pub recipe: bool,
    /// A view's export settings, put in place the next time the dialog opens.
    pub restore: Option<crate::view::SavedChartExport>,
    /// Why Enter did not write: a blank path, or the failed write's reason. Said
    /// on the dialog's status line; cleared by typing in the path.
    pub error: Option<String>,
}

impl ChartExportModal {
    pub fn new() -> Self {
        Self::default()
    }

    /// Open the dialog for a chart. The format, style, size and byline stay as
    /// they were last used; the words about the chart start from `defaults`.
    pub fn open(
        &mut self,
        theme: &crate::config::Theme,
        history_limit: usize,
        defaults: ExportDefaults,
    ) {
        self.focus = ChartExportFocus::PathInput;
        self.error = None;
        let input = || TextInput::new().with_theme(theme);
        // Ctrl+P / Ctrl+N recall the paths exported to before.
        self.path_input = TextInput::new()
            .with_history("chart_export_path".to_string())
            .with_history_limit(history_limit)
            .with_theme(theme);
        self.title_input = input();
        self.description_input = input();
        self.description_input.set_value(defaults.description);
        self.notes_input = input();
        self.source_input = input();
        self.source_input.set_value(defaults.source);
        let byline = self.byline_input.value().to_string();
        self.byline_input = input();
        self.byline_input.set_value(byline);
        let (width, height) = (
            self.width_input.value().to_string(),
            self.height_input.value().to_string(),
        );
        self.width_input = input();
        self.height_input = input();
        self.width_input.set_value(width);
        self.height_input.set_value(height);
        self.legend = if defaults.legend {
            LegendPlace::LineEnds
        } else {
            LegendPlace::Off
        };
        // The marks' sizes stay as last used; the axis follows the chart.
        self.mark = defaults.mark;
        self.y_from_zero = defaults.y_from_zero;
        self.apply_size();
        if let Some(saved) = self.restore.take() {
            self.put_back(saved);
        }
    }

    /// The dialog as a view keeps it: everything but the path.
    pub fn saved(&self) -> crate::view::SavedChartExport {
        let (width, height) = self.export_dimensions();
        crate::view::SavedChartExport {
            format: self.format,
            style: self.style,
            size: self.size,
            width,
            height,
            dpi: self.dpi,
            legend: self.legend,
            point_opacity: self.point_opacity,
            point_size: self.point_size,
            line_width: self.line_width,
            y_from_zero: self.y_from_zero,
            title: self.title_input.value().to_string(),
            description: self.description_input.value().to_string(),
            notes: self.notes_input.value().to_string(),
            source: self.source_input.value().to_string(),
            byline: self.byline_input.value().to_string(),
            recipe: self.recipe,
        }
    }

    /// Put back a view's settings. Words it left blank keep the chart's own.
    fn put_back(&mut self, saved: crate::view::SavedChartExport) {
        self.format = saved.format;
        self.style = saved.style;
        self.size = saved.size;
        self.dpi = saved.dpi;
        self.width_input.set_value(saved.width.to_string());
        self.height_input.set_value(saved.height.to_string());
        self.legend = saved.legend;
        self.point_opacity = saved.point_opacity;
        self.point_size = saved.point_size;
        self.line_width = saved.line_width;
        self.y_from_zero = saved.y_from_zero;
        self.recipe = saved.recipe;
        for (input, text) in [
            (&mut self.title_input, saved.title),
            (&mut self.description_input, saved.description),
            (&mut self.notes_input, saved.notes),
            (&mut self.source_input, saved.source),
            (&mut self.byline_input, saved.byline),
        ] {
            if !text.is_empty() {
                input.set_value(text);
            }
        }
    }

    /// Whether `field` applies to the chart being exported: the points' rows to a
    /// scatter, the line's width and Y from zero to a line. Bars always start at
    /// zero: a bar's length is its value.
    pub fn shows(&self, field: ChartExportFocus) -> bool {
        match field {
            ChartExportFocus::PointOpacity | ChartExportFocus::PointSize => {
                self.mark == Mark::Scatter
            }
            ChartExportFocus::LineWidth | ChartExportFocus::YFromZero => self.mark == Mark::Line,
            _ => true,
        }
    }

    /// The fields on screen, top to bottom.
    pub fn shown(&self) -> Vec<ChartExportFocus> {
        FIELDS
            .into_iter()
            .map(|(field, _)| field)
            .filter(|f| self.shows(*f))
            .collect()
    }

    /// What a choice row shows.
    pub fn choice(&self, field: ChartExportFocus) -> Option<&'static str> {
        Some(match field {
            ChartExportFocus::Format => self.format.as_str(),
            ChartExportFocus::Style => self.style.label(),
            ChartExportFocus::Size => self.size.label(),
            ChartExportFocus::Legend => self.legend.label(),
            ChartExportFocus::PointOpacity => self.point_opacity.label(),
            ChartExportFocus::PointSize => self.point_size.label(),
            ChartExportFocus::LineWidth => self.line_width.label(),
            ChartExportFocus::YFromZero => {
                if self.y_from_zero {
                    "On"
                } else {
                    "Off"
                }
            }
            // What is embedded is said with the choice, so nobody is surprised by it.
            ChartExportFocus::Recipe => {
                if self.recipe {
                    "Include: source path, query, chart, sample"
                } else {
                    "Omit: no datui metadata"
                }
            }
            _ => return None,
        })
    }

    /// Y from zero for the file: what the dialog says, on a line chart.
    pub fn y_from_zero_option(&self) -> Option<bool> {
        self.shows(ChartExportFocus::YFromZero)
            .then_some(self.y_from_zero)
    }

    /// Reopen after an overwrite declined or a failed write: the form as it was,
    /// focus on the path.
    pub fn reopen_with_path(&mut self, path: &Path, format: ChartExportFormat) {
        self.focus = ChartExportFocus::PathInput;
        self.format = format;
        self.path_input.set_value(path.display().to_string());
    }

    pub fn close(&mut self) {
        self.focus = ChartExportFocus::PathInput;
        self.path_input.clear();
        self.error = None;
    }

    /// ←/→ on a choice.
    pub fn step(&mut self, field: ChartExportFocus, delta: i8) {
        use crate::app::form::step_value;
        match field {
            ChartExportFocus::Format => {
                self.format = step_value(&ChartExportFormat::ALL, self.format, delta)
            }
            ChartExportFocus::Style => {
                self.style = step_value(&ExportStyle::ALL, self.style, delta)
            }
            ChartExportFocus::Size => {
                self.size = step_value(&SizePreset::ALL, self.size, delta);
                self.apply_size();
            }
            ChartExportFocus::Legend => {
                self.legend = step_value(&LegendPlace::ALL, self.legend, delta)
            }
            ChartExportFocus::PointOpacity => {
                self.point_opacity = step_value(&PointOpacity::ALL, self.point_opacity, delta)
            }
            ChartExportFocus::PointSize => {
                self.point_size = step_value(&PointSize::ALL, self.point_size, delta)
            }
            ChartExportFocus::LineWidth => {
                self.line_width = step_value(&LineWidth::ALL, self.line_width, delta)
            }
            ChartExportFocus::YFromZero => self.y_from_zero = !self.y_from_zero,
            ChartExportFocus::Recipe => self.recipe = !self.recipe,
            _ => {}
        }
    }

    /// Fill the width and height from the preset; a custom size keeps what is typed.
    fn apply_size(&mut self) {
        if let Some((w, h)) = self.size.size() {
            self.width_input.set_value(w.to_string());
            self.height_input.set_value(h.to_string());
            self.dpi = self.size.dpi();
        }
    }

    /// A width or height typed: the size is custom from then on.
    pub fn size_typed(&mut self) {
        if self.size.size() != Some(self.export_dimensions()) {
            self.size = SizePreset::Custom;
        }
    }

    /// A text field's input; `None` for a choice.
    pub fn input(&self, field: ChartExportFocus) -> Option<&TextInput> {
        Some(match field {
            ChartExportFocus::PathInput => &self.path_input,
            ChartExportFocus::WidthInput => &self.width_input,
            ChartExportFocus::HeightInput => &self.height_input,
            ChartExportFocus::TitleInput => &self.title_input,
            ChartExportFocus::DescriptionInput => &self.description_input,
            ChartExportFocus::NotesInput => &self.notes_input,
            ChartExportFocus::SourceInput => &self.source_input,
            ChartExportFocus::BylineInput => &self.byline_input,
            _ => return None,
        })
    }

    /// [`Self::input`], to edit.
    pub fn input_mut(&mut self, field: ChartExportFocus) -> Option<&mut TextInput> {
        Some(match field {
            ChartExportFocus::PathInput => &mut self.path_input,
            ChartExportFocus::WidthInput => &mut self.width_input,
            ChartExportFocus::HeightInput => &mut self.height_input,
            ChartExportFocus::TitleInput => &mut self.title_input,
            ChartExportFocus::DescriptionInput => &mut self.description_input,
            ChartExportFocus::NotesInput => &mut self.notes_input,
            ChartExportFocus::SourceInput => &mut self.source_input,
            ChartExportFocus::BylineInput => &mut self.byline_input,
            _ => return None,
        })
    }

    /// The width and height typed, each 16 to 8,192 px; the preset's where a field
    /// does not read as a number.
    pub fn export_dimensions(&self) -> (u32, u32) {
        const MIN: u32 = 16;
        const MAX: u32 = 8192;
        let (dw, dh) = self.size.size().unwrap_or((1600, 1000));
        let read = |input: &TextInput, default: u32| {
            input
                .value()
                .trim()
                .parse::<u32>()
                .map(|n| n.clamp(MIN, MAX))
                .unwrap_or(default)
        };
        (read(&self.width_input, dw), read(&self.height_input, dh))
    }
}

impl crate::app::form::Form for ChartExportModal {
    type Field = ChartExportFocus;

    fn fields(&self) -> Vec<(ChartExportFocus, crate::app::form::FieldKind)> {
        use crate::app::form::FieldKind::{Choice, Text};
        self.shown()
            .into_iter()
            .map(|f| {
                let kind = if f.is_text() { Text } else { Choice };
                (f, kind)
            })
            .collect()
    }

    fn focused(&self) -> ChartExportFocus {
        self.focus
    }

    fn set_focused(&mut self, field: ChartExportFocus) {
        self.focus = field;
    }
}

impl Default for ChartExportModal {
    fn default() -> Self {
        let size = SizePreset::Document;
        let (w, h) = size.size().unwrap_or((1600, 1000));
        let mut width_input = TextInput::new();
        width_input.set_value(w.to_string());
        let mut height_input = TextInput::new();
        height_input.set_value(h.to_string());
        Self {
            focus: ChartExportFocus::PathInput,
            format: ChartExportFormat::Png,
            style: ExportStyle::Light,
            size,
            dpi: size.dpi(),
            legend: LegendPlace::LineEnds,
            mark: Mark::default(),
            point_opacity: PointOpacity::default(),
            point_size: PointSize::default(),
            line_width: LineWidth::default(),
            y_from_zero: false,
            path_input: TextInput::new(),
            width_input,
            height_input,
            title_input: TextInput::new(),
            description_input: TextInput::new(),
            notes_input: TextInput::new(),
            source_input: TextInput::new(),
            byline_input: TextInput::new(),
            recipe: true,
            restore: None,
            error: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::form::Form;

    fn opened() -> ChartExportModal {
        let config = crate::config::AppConfig::default();
        let theme = crate::config::Theme::from_config(&config.theme).unwrap();
        let mut modal = ChartExportModal::new();
        modal.open(
            &theme,
            10,
            ExportDefaults {
                description: "Mean by month".to_string(),
                source: "NYC flights · CC0".to_string(),
                legend: false,
                mark: Mark::Line,
                y_from_zero: false,
            },
        );
        modal
    }

    #[test]
    fn presets_set_the_size_and_typing_makes_it_custom() {
        let mut modal = opened();
        assert_eq!(modal.export_dimensions(), (1600, 1000));
        modal.step(ChartExportFocus::Size, -1);
        assert_eq!(modal.size, SizePreset::Slide);
        assert_eq!(modal.export_dimensions(), (1920, 1080));
        modal.step(ChartExportFocus::Size, 3);
        assert_eq!(modal.size, SizePreset::SingleColumn);
        assert_eq!(modal.width_input.value(), "1050");
        modal.width_input.set_value("800");
        modal.size_typed();
        assert_eq!(modal.size, SizePreset::Custom);
        assert_eq!(modal.dpi, 300.0, "the column's resolution stays");
        assert_eq!(modal.export_dimensions(), (800, 788));
    }

    #[test]
    fn the_chart_fills_the_words_and_legend_off_carries_over() {
        let modal = opened();
        assert_eq!(modal.description_input.value(), "Mean by month");
        assert_eq!(modal.source_input.value(), "NYC flights · CC0");
        assert_eq!(modal.legend, LegendPlace::Off);
        // A line takes its width and Y from zero, not the points' rows.
        assert_eq!(modal.fields().len(), FIELDS.len() - 2);
    }

    /// A text field has an input and no choice; every other field, a choice.
    #[test]
    fn a_field_is_text_or_a_choice() {
        let mut modal = opened();
        for (field, _) in FIELDS {
            assert_eq!(modal.choice(field).is_none(), field.is_text(), "{field:?}");
            assert_eq!(
                modal.input_mut(field).is_some(),
                field.is_text(),
                "{field:?}"
            );
        }
    }

    /// A mark row shows only for the chart types it changes, so focus never lands
    /// on one that would do nothing.
    #[test]
    fn mark_rows_follow_the_chart_type() {
        use ChartExportFocus::*;
        let mut modal = opened();
        let has = |modal: &ChartExportModal, f| modal.fields().iter().any(|(g, _)| *g == f);
        assert!(has(&modal, LineWidth) && has(&modal, YFromZero));
        assert!(!has(&modal, PointOpacity) && !has(&modal, PointSize));
        modal.mark = Mark::Scatter;
        assert!(has(&modal, PointOpacity) && has(&modal, PointSize));
        assert!(!has(&modal, LineWidth) && !has(&modal, YFromZero));
        assert_eq!(modal.y_from_zero_option(), None, "a scatter keeps its axis");
        modal.mark = Mark::Histogram;
        for f in [PointOpacity, PointSize, LineWidth, YFromZero] {
            assert!(!has(&modal, f), "{f:?}");
        }
        modal.mark = Mark::Bar;
        assert!(!has(&modal, YFromZero) && !has(&modal, LineWidth));
        assert_eq!(modal.y_from_zero_option(), None, "bars start at zero");
        modal.mark = Mark::Line;
        modal.y_from_zero = true;
        modal.step(YFromZero, 1);
        assert_eq!(modal.y_from_zero_option(), Some(false));
        modal.mark = Mark::Scatter;
        assert_eq!(
            modal.point_opacity,
            crate::chart::chart_export::PointOpacity::Auto
        );
        modal.step(PointOpacity, 1);
        assert_eq!(modal.choice(PointOpacity), Some("100%"));
        modal.step(PointSize, -1);
        assert_eq!(modal.choice(PointSize), Some("Small"));
    }
}