altar 0.1.0

A TUI library in the style of SwiftUI
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
pub mod alignment;
pub mod background;
pub mod border;
pub mod context;
pub mod context_modifier;
pub mod frame;
pub mod geometry_reader;
pub mod identified_view;
pub mod padding;
pub mod stack;
pub mod text;
pub mod view_tuple;

use std::fmt::Debug;
use std::hash::{DefaultHasher, Hash, Hasher};

use crate::*;

pub use alignment::*;
pub use background::*;
pub use border::{Border, BorderStyle};
pub use buffer::*;
pub use context::*;
pub use context_modifier::*;
pub use frame::*;
pub use geometry_reader::*;
pub use identified_view::*;
pub use padding::*;
pub use stack::*;
pub use text::*;
pub use view_tuple::*;

/// Syntax Examples
/// ---------------
/// Example of a VStack with nested HStacks
/// ```
/// use altar::*;
/// let view = vstack((
///     hstack((text("1."), text("Eggs"))),
///     hstack((text("2."), text("Powders"))),
///     hstack((text("3."), text("Milk"))),
/// )).border();
///
/// let expected = vec![
///     "┌────────────┐",
///     "│ 1. Eggs    │",
///     "│ 2. Powders │",
///     "│ 3. Milk    │",
///     "└────────────┘",
/// ].join("\n");
///
/// assert_eq!(expected, view.as_plain_str());
/// ```
pub trait View: private::Sealed + 'static {
    fn size(&self, proposed: Size) -> Size;

    fn render(&self, id: &mut ViewId, context: Context, state: &mut AppState, buffer: &mut Buffer);
}

pub(crate) mod private {
    pub trait Sealed {}
}

pub trait ViewExtensions: View + Sized {
    fn frame(
        self,
        min_width: Option<u16>,
        min_height: Option<u16>,
        max_width: Option<u16>,
        max_height: Option<u16>,
        alignment: Alignment,
    ) -> Frame<Self> {
        Frame {
            child: self,
            min_width,
            min_height,
            max_width,
            max_height,
            alignment,
        }
    }

    fn center_horizontally(self) -> Frame<Self> {
        self.frame(None, None, Some(u16::MAX), None, Alignment::CENTER)
    }

    fn fill_horizontally(self) -> Frame<Self> {
        self.frame(None, None, Some(u16::MAX), None, Alignment::LEFT)
    }

    fn fill_vertically(self) -> Frame<Self> {
        self.frame(None, None, None, Some(u16::MAX), Alignment::TOP)
    }

    fn fill(self) -> Frame<Self> {
        self.frame(
            None,
            None,
            Some(u16::MAX),
            Some(u16::MAX),
            Alignment::TOP_LEFT,
        )
    }

    fn center_vertically(self) -> Frame<Self> {
        self.frame(None, None, None, Some(u16::MAX), Alignment::CENTER)
    }

    fn min_height(self, min_height: u16) -> Frame<Self> {
        self.frame(None, Some(min_height), None, None, Alignment::TOP)
    }

    fn min_width(self, min_width: u16) -> Frame<Self> {
        self.frame(Some(min_width), None, None, None, Alignment::LEFT)
    }

    fn center(self) -> Frame<Self> {
        self.frame(
            None,
            None,
            Some(u16::MAX),
            Some(u16::MAX),
            Alignment::CENTER,
        )
    }

    fn border(self) -> Border<Self> {
        Border {
            child: self,
            border_color: Color::Reset,
            border_style: BorderStyle::Single,
            title: None,
        }
    }

    fn padding(self, padding: u16) -> Padding<Self> {
        Padding {
            child: self,
            padding_top: padding,
            padding_bottom: padding,
            padding_left: padding,
            padding_right: padding,
        }
    }

    fn padding_h(self, padding: u16) -> Padding<Self> {
        Padding {
            child: self,
            padding_left: padding,
            padding_right: padding,
            padding_top: 0,
            padding_bottom: 0,
        }
    }

    fn padding_v(self, padding: u16) -> Padding<Self> {
        Padding {
            child: self,
            padding_top: padding,
            padding_bottom: padding,
            padding_left: 0,
            padding_right: 0,
        }
    }

    fn color(self, color: Color) -> ContextModifier<Self> {
        ContextModifier {
            child: self,
            fg: Some(color),
            modifier: None,
        }
    }

    fn green(self) -> ContextModifier<Self> {
        self.color(Color::DarkGreen)
    }

    fn red(self) -> ContextModifier<Self> {
        self.color(Color::DarkRed)
    }

    fn blue(self) -> ContextModifier<Self> {
        self.color(Color::DarkBlue)
    }

    fn yellow(self) -> ContextModifier<Self> {
        self.color(Color::DarkYellow)
    }

    fn white(self) -> ContextModifier<Self> {
        self.color(Color::White)
    }

    fn black(self) -> ContextModifier<Self> {
        self.color(Color::Black)
    }

    fn cyan(self) -> ContextModifier<Self> {
        self.color(Color::DarkCyan)
    }

    fn magenta(self) -> ContextModifier<Self> {
        self.color(Color::DarkMagenta)
    }

    fn background(self, color: Color) -> Background<Self, FillColor> {
        Background {
            view: self,
            background: FillColor { color },
        }
    }

    fn bold(self) -> ContextModifier<Self> {
        ContextModifier::modifier(self, Modifier::BOLD)
    }

    fn bold_when(self, condition: bool) -> ContextModifier<Self> {
        ContextModifier::modifier(
            self,
            if condition {
                Modifier::BOLD
            } else {
                Modifier::empty()
            },
        )
    }

    fn italic(self) -> ContextModifier<Self> {
        ContextModifier::modifier(self, Modifier::ITALIC)
    }

    fn italic_when(self, condition: bool) -> ContextModifier<Self> {
        ContextModifier::modifier_when(self, condition, Modifier::ITALIC)
    }

    fn underline(self) -> ContextModifier<Self> {
        ContextModifier::modifier(self, Modifier::UNDERLINE)
    }

    fn underline_when(self, condition: bool) -> ContextModifier<Self> {
        ContextModifier::modifier_when(self, condition, Modifier::UNDERLINE)
    }

    fn dim(self) -> ContextModifier<Self> {
        ContextModifier::modifier(self, Modifier::DIM)
    }

    fn dim_when(self, condition: bool) -> ContextModifier<Self> {
        ContextModifier::modifier_when(self, condition, Modifier::DIM)
    }

    fn inverse(self) -> ContextModifier<Self> {
        ContextModifier::modifier(self, Modifier::INVERSE)
    }

    fn inverse_when(self, condition: bool) -> ContextModifier<Self> {
        ContextModifier::modifier_when(self, condition, Modifier::INVERSE)
    }

    fn id<ID: Hash>(self, id: ID) -> IdentifiedView<Self> {
        IdentifiedView::new(id, self)
    }

    fn strikethrough(self) -> ContextModifier<Self> {
        ContextModifier::modifier(self, Modifier::STRIKETHROUGH)
    }

    fn strikethrough_when(self, condition: bool) -> ContextModifier<Self> {
        ContextModifier::modifier_when(self, condition, Modifier::STRIKETHROUGH)
    }

    fn visible(self, condition: bool) -> IfThenView<Self, EmptyView> {
        IfThenView {
            condition,
            true_view: self,
            false_view: empty(),
        }
    }

    fn as_any(self) -> AnyView
    where
        Self: 'static,
    {
        AnyView::new(self)
    }

    /// Returns the type ID of the underlying view.
    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    // TODO: Make private
    fn render_to_string<F>(&self, to_string: F) -> String
    where
        F: Fn(&Buffer) -> String,
    {
        let size = self.size(Size::max());
        let mut buffer = Buffer::new(size.width, size.height);
        self.render(
            &mut ViewId::empty(),
            Context::new(Rect::new(0, 0, size.width, size.height)),
            &mut AppState::new(),
            &mut buffer,
        );
        to_string(&buffer)
    }

    fn as_str(self) -> String {
        self.render_to_string(Buffer::as_str)
    }

    fn as_plain_str(&self) -> String {
        self.render_to_string(Buffer::as_plain_str)
    }
}

impl<T: View> ViewExtensions for T {}

impl<V> private::Sealed for Option<V> {}

impl<V: View> View for Option<V> {
    fn size(&self, proposed: Size) -> Size {
        match self {
            Some(view) => view.size(proposed),
            None => Size::zero(),
        }
    }

    fn render(&self, id: &mut ViewId, context: Context, state: &mut AppState, buffer: &mut Buffer) {
        if let Some(view) = self {
            view.render(id, context, state, buffer);
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EmptyView;

impl private::Sealed for EmptyView {}

impl View for EmptyView {
    fn size(&self, _proposed: Size) -> Size {
        Size::zero()
    }

    fn render(
        &self,
        _id: &mut ViewId,
        _context: Context,
        _state: &mut AppState,
        _buffer: &mut Buffer,
    ) {
        // Do nothing
    }
}

pub fn empty() -> EmptyView {
    EmptyView {}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IfThenView<T, F> {
    condition: bool,
    true_view: T,
    false_view: F,
}

pub fn if_then_view<T: View, F: View>(
    condition: bool,
    true_view: T,
    false_view: F,
) -> IfThenView<T, F> {
    IfThenView {
        condition,
        true_view,
        false_view,
    }
}

impl<T: View, F: View> private::Sealed for IfThenView<T, F> {}

impl<T: View, F: View> View for IfThenView<T, F> {
    fn size(&self, proposed: Size) -> Size {
        if self.condition {
            self.true_view.size(proposed)
        } else {
            self.false_view.size(proposed)
        }
    }

    fn render(&self, id: &mut ViewId, context: Context, state: &mut AppState, buffer: &mut Buffer) {
        if self.condition {
            id.push(1);
            self.true_view.render(id, context, state, buffer);
        } else {
            id.push(0);
            self.false_view.render(id, context, state, buffer);
        }
        id.pop();
    }
}

/// Pilfered, with love, from rui [[https://github.com/audulus/rui]]
///
/// let mut stateMap: Arc<RwLock<HashMap<ViewId, Box<dyn Any>>>>
///
/// vstack(
///     hstack(view1, view2),
///     view3,
/// )
///
/// vstack( []
///     hstack( [0]
///       view1,  [0,0]
///       view2,  [0,1]
///      ),
///     view3, [1]
/// )
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct ViewId {
    path: Vec<u64>,
}

fn do_hash<H: Hash>(id: H) -> u64 {
    let mut hasher = DefaultHasher::new();
    id.hash(&mut hasher);
    hasher.finish()
}

impl ViewId {
    pub(crate) fn empty() -> Self {
        Self { path: vec![] }
    }

    pub(crate) fn push_hashable<H: Hash>(&mut self, id: H) {
        self.path.push(do_hash(id));
    }

    pub(crate) fn push(&mut self, id: u64) {
        self.path.push(id);
    }

    pub(crate) fn pop(&mut self) {
        self.path.pop().unwrap();
    }
}

use std::any::{Any, TypeId};
use std::collections::HashMap;

#[derive(Debug)]
pub struct AppState {
    pub view_map: HashMap<ViewId, Box<dyn Any + Send>>,
}

impl AppState {
    pub fn new() -> Self {
        Self {
            view_map: HashMap::new(),
        }
    }

    pub fn get_mut<T: Any + 'static + Send>(
        &mut self,
        view_id: &ViewId,
        default: impl FnOnce() -> T,
    ) -> &mut T {
        let entry = self.view_map.entry(view_id.clone());
        let value = entry.or_insert_with(|| Box::new(default()));
        value.downcast_mut::<T>().unwrap()
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RenderCounter {}

impl private::Sealed for RenderCounter {}

impl View for RenderCounter {
    fn size(&self, proposed: Size) -> Size {
        Size::new(80, 1).min(proposed)
    }

    fn render(&self, id: &mut ViewId, context: Context, state: &mut AppState, buffer: &mut Buffer) {
        let count = state.get_mut(id, || 0);
        *count += 1;

        let rect = context.rect;
        buffer.set_string_at(
            rect.point.x,
            rect.point.y,
            rect.size.width,
            &format!("Render {:?}: {}", id.path, count),
            context.fg,
            None,
            context.modifier,
        );
    }
}