zi 0.3.2

A declarative library for building monospace 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
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
//! The `Layout` type and flexbox-like utilities for laying out components.

use smallvec::SmallVec;
use std::{
    cmp,
    collections::hash_map::DefaultHasher,
    hash::{Hash, Hasher},
};

use super::{
    template::{ComponentDef, DynamicTemplate},
    Component,
};
use crate::terminal::{Canvas, Position, Rect, Size};

pub trait ComponentExt: Component {
    /// Creates a component definition from its `Properties`.
    fn with(properties: Self::Properties) -> Layout {
        Layout(LayoutNode::Component(DynamicTemplate(Box::new(
            ComponentDef::<Self>::new(None, properties),
        ))))
    }

    /// Creates a component definition from its `Properties`, using a custom
    /// identity specified by a key (in addition to the component's ancestors).
    ///
    /// Useful to avoid rerendering components of the same type in a container
    /// when changing the number of items in the container.
    fn with_key(key: impl Into<ComponentKey>, properties: Self::Properties) -> Layout {
        Layout(LayoutNode::Component(DynamicTemplate(Box::new(
            ComponentDef::<Self>::new(Some(key.into()), properties),
        ))))
    }

    fn item_with(flex: FlexBasis, properties: Self::Properties) -> Item {
        Item {
            flex,
            node: Layout(LayoutNode::Component(DynamicTemplate(Box::new(
                ComponentDef::<Self>::new(None, properties),
            )))),
        }
    }

    fn item_with_key(
        flex: FlexBasis,
        key: impl Into<ComponentKey>,
        properties: Self::Properties,
    ) -> Item {
        Item {
            flex,
            node: Layout(LayoutNode::Component(DynamicTemplate(Box::new(
                ComponentDef::<Self>::new(Some(key.into()), properties),
            )))),
        }
    }
}

impl<T: Component> ComponentExt for T {}

/// Wrapper type for user defined component identity.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ComponentKey(usize);

impl From<usize> for ComponentKey {
    fn from(key: usize) -> Self {
        Self(key)
    }
}

impl From<&str> for ComponentKey {
    fn from(key: &str) -> Self {
        let mut hasher = DefaultHasher::new();
        key.hash(&mut hasher);
        Self(hasher.finish() as usize)
    }
}

/// Represents a layout tree which is the main building block of a UI in Zi.
///
/// Each node in the layout tree is one
///   1. A component, any type implementing [`Component`](./Component).
///   2. A flex container that groups multiple `Layout`s, represented by
///      [`Container`](./Container).
///   3. A canvas which corresponds to the raw content in a region, represented
///      by [`Canvas`](./Canvas).
pub struct Layout(pub(crate) LayoutNode);

impl Layout {
    /// Creates a new flex container with a specified direction and containing
    /// the provided items.
    ///
    /// This is a utility function that builds a container and converts it to a `Layout`.
    /// It is equivalent to calling `Container::new(direction, items).into()`.
    #[inline]
    pub fn container(direction: FlexDirection, items: impl IntoIterator<Item = Item>) -> Self {
        Container::new(direction, items).into()
    }

    /// Creates a container with column (vertical) layout.
    ///
    /// Child components are laid out from top to bottom. Pass in the children as an
    /// something that can be converted to an iterator of items, e.g. an array of
    /// items.
    ///
    /// This is a utility function that builds a container and converts it to a `Layout`.
    /// It is equivalent to calling `Container::column(items).into()`.
    #[inline]
    pub fn column(items: impl IntoIterator<Item = Item>) -> Self {
        Container::column(items).into()
    }

    /// Creates a container with reversed column (vertical) layout.
    ///
    /// Child components are laid out from bottom to top. Pass in the children as an
    /// something that can be converted to an iterator of items, e.g. an array of
    /// items.
    ///
    /// This is a utility function that builds a container and converts it to a `Layout`.
    /// It is equivalent to calling `Container::column_reverse(items).into()`.
    #[inline]
    pub fn column_reverse(items: impl IntoIterator<Item = Item>) -> Self {
        Container::column_reverse(items).into()
    }

    /// Creates a container with row (horizontal) layout.
    ///
    /// Child components are laid out from left to right. Pass in the children as an
    /// something that can be converted to an iterator of items, e.g. an array of
    /// items.
    ///
    /// This is a utility function that builds a container and converts it to a `Layout`.
    /// It is equivalent to calling `Container::row(items).into()`.
    #[inline]
    pub fn row(items: impl IntoIterator<Item = Item>) -> Self {
        Container::row(items).into()
    }

    /// Creates a container with reversed row (horizontal) layout.
    ///
    /// Child components are laid out from right to left. Pass in the children as an
    /// something that can be converted to an iterator of items, e.g. an array of
    /// items.
    ///
    /// This is a utility function that builds a container and converts it to a `Layout`.
    /// It is equivalent to calling `Container::row_reverse(items).into()`.
    #[inline]
    pub fn row_reverse(items: impl IntoIterator<Item = Item>) -> Self {
        Container::row_reverse(items).into()
    }
}

pub(crate) enum LayoutNode {
    Container(Box<Container>),
    Component(DynamicTemplate),
    Canvas(Canvas),
}

impl LayoutNode {
    pub(crate) fn crawl(
        &mut self,
        frame: Rect,
        position_hash: u64,
        view_fn: &mut impl FnMut(LaidComponent),
        draw_fn: &mut impl FnMut(LaidCanvas),
    ) {
        let mut hasher = DefaultHasher::new();
        hasher.write_u64(position_hash);
        match self {
            Self::Container(container) => {
                hasher.write_u64(Self::CONTAINER_HASH);
                if container.direction.is_reversed() {
                    let frames: SmallVec<[_; ITEMS_INLINE_SIZE]> =
                        splits_iter(frame, container.direction, container.children.iter().rev())
                            .collect();
                    for (child, frame) in container.children.iter_mut().rev().zip(frames) {
                        // hasher.write_u64(Self::CONTAINER_ITEM_HASH);
                        child.node.0.crawl(frame, hasher.finish(), view_fn, draw_fn);
                    }
                } else {
                    let frames: SmallVec<[_; ITEMS_INLINE_SIZE]> =
                        splits_iter(frame, container.direction, container.children.iter())
                            .collect();
                    for (child, frame) in container.children.iter_mut().zip(frames) {
                        // hasher.write_u64(Self::CONTAINER_ITEM_HASH);
                        child.node.0.crawl(frame, hasher.finish(), view_fn, draw_fn);
                    }
                }
            }
            Self::Component(template) => {
                template.component_type_id().hash(&mut hasher);
                if let Some(key) = template.key() {
                    key.hash(&mut hasher);
                }
                view_fn(LaidComponent {
                    frame,
                    position_hash: hasher.finish(),
                    template,
                });
            }
            Self::Canvas(canvas) => {
                draw_fn(LaidCanvas { frame, canvas });
            }
        };
    }

    // Some random number to initialise the hash (0 would also do, but hopefully
    // this is less pathological if a simpler hash function is used for
    // `DefaultHasher`).
    const CONTAINER_HASH: u64 = 0x5aa2d5349a05cde8;
}

impl From<Canvas> for Layout {
    fn from(canvas: Canvas) -> Self {
        Self(LayoutNode::Canvas(canvas))
    }
}

const ITEMS_INLINE_SIZE: usize = 4;
type Items = SmallVec<[Item; ITEMS_INLINE_SIZE]>;

/// A flex container with a specified direction and items.
pub struct Container {
    children: Items,
    direction: FlexDirection,
}

impl Container {
    /// Creates a new flex container with a specified direction and containing
    /// the provided items.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use zi::prelude::*;
    /// # use zi::components::text::{Text, TextProperties};
    /// # fn main() {
    /// let container = Container::new(
    ///     FlexDirection::Column,
    ///     [
    ///         Item::auto(Text::with(TextProperties::new().content("Item 1"))),
    ///         Item::auto(Text::with(TextProperties::new().content("Item 2"))),
    ///     ],
    /// );
    /// # }
    /// ```
    #[inline]
    pub fn new(direction: FlexDirection, items: impl IntoIterator<Item = Item>) -> Self {
        Self {
            children: items.into_iter().collect(),
            direction,
        }
    }

    /// Creates a new empty flex container with a specified direction.
    #[inline]
    pub fn empty(direction: FlexDirection) -> Self {
        Self {
            children: SmallVec::new(),
            direction,
        }
    }

    /// Adds an item to the end of the container.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use zi::prelude::*;
    /// # use zi::components::text::{Text, TextProperties};
    /// # fn main() {
    /// let mut container = Container::empty(FlexDirection::Row);
    /// container
    ///     .push(Item::auto(Text::with(TextProperties::new().content("Item 1"))))
    ///     .push(Item::auto(Text::with(TextProperties::new().content("Item 2"))));
    /// # }
    /// ```
    #[inline]
    pub fn push(&mut self, item: Item) -> &mut Self {
        self.children.push(item);
        self
    }

    /// Creates a container with column (vertical) layout.
    ///
    /// Child components are laid out from top to bottom. Pass in the children as an
    /// something that can be converted to an iterator of items, e.g. an array of
    /// items.
    ///
    /// This is a utility function and it is equivalent to calling
    /// `Container::new(FlexDirection::Column, items)`.
    #[inline]
    pub fn column(items: impl IntoIterator<Item = Item>) -> Self {
        Self::new(FlexDirection::Column, items)
    }

    /// Creates a container with reversed column (vertical) layout.
    ///
    /// Child components are laid out from bottom to top. Pass in the children as an
    /// something that can be converted to an iterator of items, e.g. an array of
    /// items.
    #[inline]
    pub fn column_reverse(items: impl IntoIterator<Item = Item>) -> Self {
        Self::new(FlexDirection::ColumnReverse, items)
    }

    /// Creates a container with row (horizontal) layout.
    ///
    /// Child components are laid out from left to right. Pass in the children as an
    /// something that can be converted to an iterator of items, e.g. an array of
    /// items.
    #[inline]
    pub fn row(items: impl IntoIterator<Item = Item>) -> Self {
        Self::new(FlexDirection::Row, items)
    }

    /// Creates a container with reversed row (horizontal) layout.
    ///
    /// Child components are laid out from right to left. Pass in the children as an
    /// something that can be converted to an iterator of items, e.g. an array of
    /// items.
    #[inline]
    pub fn row_reverse(items: impl IntoIterator<Item = Item>) -> Self {
        Self::new(FlexDirection::RowReverse, items)
    }
}

impl From<Container> for Layout {
    fn from(container: Container) -> Self {
        Layout(LayoutNode::Container(Box::new(container)))
    }
}

/// Represents a flex item, a layout tree nested inside a container.
///
/// An `Item` consists of a `Layout` and an associated `FlexBasis`. The latter
/// specifies how much space the layout should take along the main axis of the
/// container.
pub struct Item {
    node: Layout,
    flex: FlexBasis,
}

impl Item {
    /// Creates an item that will share the available space equally with other
    /// sibling items with `FlexBasis::auto`.
    #[inline]
    pub fn auto(layout: impl Into<Layout>) -> Item {
        Item {
            node: layout.into(),
            flex: FlexBasis::Auto,
        }
    }

    /// Creates an item that will have a fixed size.
    #[inline]
    pub fn fixed<LayoutT>(size: usize) -> impl FnOnce(LayoutT) -> Item
    where
        LayoutT: Into<Layout>,
    {
        move |layout| Item {
            node: layout.into(),
            flex: FlexBasis::Fixed(size),
        }
    }
}

/// Enum to control the size of an item inside a container.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FlexBasis {
    Auto,
    Fixed(usize),
}

/// Enum to control how items are placed in a container. It defines the main
/// axis and the direction (normal or reversed).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FlexDirection {
    Column,
    ColumnReverse,
    Row,
    RowReverse,
}

impl FlexDirection {
    #[inline]
    pub fn is_reversed(&self) -> bool {
        match self {
            FlexDirection::Column | FlexDirection::Row => false,
            FlexDirection::ColumnReverse | FlexDirection::RowReverse => true,
        }
    }

    #[inline]
    pub(crate) fn dimension(self, size: Size) -> usize {
        match self {
            FlexDirection::Row => size.width,
            FlexDirection::RowReverse => size.width,
            FlexDirection::Column => size.height,
            FlexDirection::ColumnReverse => size.height,
        }
    }
}

pub(crate) struct LaidComponent<'a> {
    pub frame: Rect,
    pub position_hash: u64,
    pub template: &'a mut DynamicTemplate,
}

pub(crate) struct LaidCanvas<'a> {
    pub frame: Rect,
    pub canvas: &'a Canvas,
}

#[inline]
fn splits_iter<'a>(
    frame: Rect,
    direction: FlexDirection,
    children: impl Iterator<Item = &'a Item> + Clone + 'a,
) -> impl Iterator<Item = Rect> + 'a {
    let total_size = direction.dimension(frame.size);

    // Compute how much space is available for stretched components
    let (stretched_budget, num_stretched_children, total_fixed_size) = {
        let mut stretched_budget = total_size;
        let mut num_stretched_children = 0;
        let mut total_fixed_size = 0;
        for child in children.clone() {
            match child.flex {
                FlexBasis::Auto => {
                    num_stretched_children += 1;
                }
                FlexBasis::Fixed(size) => {
                    stretched_budget = stretched_budget.saturating_sub(size);
                    total_fixed_size += size;
                }
            }
        }
        (stretched_budget, num_stretched_children, total_fixed_size)
    };

    // Divvy up the space equaly between stretched components.
    let stretched_size = if num_stretched_children > 0 {
        stretched_budget / num_stretched_children
    } else {
        0
    };
    let mut remainder =
        total_size.saturating_sub(num_stretched_children * stretched_size + total_fixed_size);
    let mut remaining_size = total_size;

    children
        .map(move |child| match child.flex {
            FlexBasis::Auto => {
                let offset = total_size - remaining_size;
                let size = if remainder > 0 {
                    remainder -= 1;
                    stretched_size + 1
                } else {
                    stretched_size
                };
                remaining_size -= size;
                (offset, size)
            }
            FlexBasis::Fixed(size) => {
                let offset = total_size - remaining_size;
                let size = cmp::min(remaining_size, size);
                remaining_size -= size;
                (offset, size)
            }
        })
        .map(move |(offset, size)| match direction {
            FlexDirection::Row | FlexDirection::RowReverse => Rect::new(
                Position::new(frame.origin.x + offset, frame.origin.y),
                Size::new(size, frame.size.height),
            ),
            FlexDirection::Column | FlexDirection::ColumnReverse => Rect::new(
                Position::new(frame.origin.x, frame.origin.y + offset),
                Size::new(frame.size.width, size),
            ),
        })
}