ori_core/views/
stack.rs

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
use std::ops::Deref;

use ori_macro::{example, Build};

use crate::{
    context::{BuildCx, DrawCx, EventCx, LayoutCx, RebuildCx},
    event::Event,
    layout::{Align, Axis, Justify, Size, Space},
    rebuild::Rebuild,
    style::{Stylable, Style, StyleBuilder},
    view::{AnyView, PodSeq, SeqState, View, ViewSeq},
};

pub use crate::{hstack, vstack};

use super::Flex;

/// Create a horizontal [`Stack`].
#[macro_export]
macro_rules! hstack {
    ($($child:expr),* $(,)?) => {
        $crate::views::hstack(($($child,)*))
    };
}

/// Create a vertical [`Stack`].
#[macro_export]
macro_rules! vstack {
    ($($child:expr),* $(,)?) => {
        $crate::views::vstack(($($child,)*))
    };
}

/// Create a horizontal [`Stack`].
pub fn hstack<V>(view: V) -> Stack<V> {
    Stack::horizontal(view)
}

/// Create a vertical [`Stack`].
pub fn vstack<V>(view: V) -> Stack<V> {
    Stack::vertical(view)
}

/// Create a horizontal [`Stack`], with vector content.
pub fn hstack_vec<V>() -> Stack<Vec<V>> {
    Stack::vec_horizontal()
}

/// Create a vertical [`Stack`], with vector content.
pub fn vstack_vec<V>() -> Stack<Vec<V>> {
    Stack::vec_vertical()
}

/// Create a horizontal [`Stack`], with dynamic content.
pub fn hstack_any<'a, T>() -> Stack<Vec<Box<dyn AnyView<T> + 'a>>> {
    Stack::any_horizontal()
}

/// Create a vertical [`Stack`], with dynamic content.
pub fn vstack_any<'a, T>() -> Stack<Vec<Box<dyn AnyView<T> + 'a>>> {
    Stack::any_vertical()
}

/// A style for a [`Stack`].
#[derive(Clone, Rebuild)]
pub struct StackStyle {
    /// How to justify the content along the main axis.
    #[rebuild(layout)]
    pub justify: Justify,

    /// How to align the content along the cross axis, within each line.
    #[rebuild(layout)]
    pub align: Align,

    /// The gap between children.
    #[rebuild(layout)]
    pub gap: f32,
}

impl Style for StackStyle {
    fn default_style() -> StyleBuilder<Self> {
        StyleBuilder::new(|| Self {
            justify: Justify::Start,
            align: Align::Center,
            gap: 0.0,
        })
    }
}

/// A view that stacks it's content in a line.
#[example(name = "stack", width = 400, height = 600)]
#[derive(Build, Rebuild)]
pub struct Stack<V> {
    /// The content of the stack.
    #[build(ignore)]
    pub content: PodSeq<V>,

    /// The axis of the stack.
    #[rebuild(layout)]
    pub axis: Axis,

    /// How to justify the content along the main axis.
    #[rebuild(layout)]
    #[style(default)]
    pub justify: Option<Justify>,

    /// How to align the content along the cross axis, within each line.
    #[rebuild(layout)]
    #[style(default = Align::Center)]
    pub align: Option<Align>,

    /// The gap between children.
    #[rebuild(layout)]
    #[style(default)]
    pub gap: Option<f32>,
}

impl<V> Stack<V> {
    /// Create a new [`Stack`].
    pub fn new(axis: Axis, content: V) -> Self {
        Self {
            content: PodSeq::new(content),
            axis,
            justify: None,
            align: None,
            gap: None,
        }
    }

    /// Create a new horizontal [`Stack`].
    pub fn horizontal(content: V) -> Self {
        Self::new(Axis::Horizontal, content)
    }

    /// Create a new vertical [`Stack`].
    pub fn vertical(content: V) -> Self {
        Self::new(Axis::Vertical, content)
    }
}

impl<T> Stack<Vec<T>> {
    /// Create a new [`Stack`], with vector content.
    pub fn vec(axis: Axis) -> Self {
        Self::new(axis, Vec::new())
    }

    /// Create a new horizontal [`Stack`], with vector content.
    pub fn vec_horizontal() -> Self {
        Self::horizontal(Vec::new())
    }

    /// Create a new vertical [`Stack`], with vector content.
    pub fn vec_vertical() -> Self {
        Self::vertical(Vec::new())
    }

    /// Push a view to the stack.
    pub fn push(&mut self, view: T) {
        self.content.push(view);
    }

    /// Push a view to the stack.
    pub fn with(mut self, view: T) -> Self {
        self.push(view);
        self
    }

    /// Get whether the stack is empty.
    pub fn is_empty(&self) -> bool {
        self.content.deref().is_empty()
    }

    /// Get the number of views in the stack.
    pub fn len(&self) -> usize {
        self.content.deref().len()
    }
}

impl<T> Stack<Vec<Box<dyn AnyView<T> + '_>>> {
    /// Create a new [`Stack`], with dynamic content.
    pub fn any(axis: Axis) -> Self {
        Self::new(axis, Vec::new())
    }

    /// Create a new horizontal [`Stack`], with dynamic content.
    pub fn any_horizontal() -> Self {
        Self::horizontal(Vec::new())
    }

    /// Create a new vertical [`Stack`], with dynamic content.
    pub fn any_vertical() -> Self {
        Self::vertical(Vec::new())
    }
}

impl<V> Stylable for Stack<V> {
    type Style = StackStyle;

    fn style(&self, style: &Self::Style) -> Self::Style {
        StackStyle {
            justify: self.justify.unwrap_or(style.justify),
            align: self.align.unwrap_or(style.align),
            gap: self.gap.unwrap_or(style.gap),
        }
    }
}

#[doc(hidden)]
pub struct StackState {
    style: StackStyle,
    flex_sum: f32,
    majors: Vec<f32>,
    minors: Vec<f32>,
}

impl StackState {
    fn new<T, V: ViewSeq<T>>(stack: &Stack<V>, style: &StackStyle) -> Self {
        Self {
            style: stack.style(style),
            flex_sum: 0.0,
            majors: vec![0.0; stack.content.len()],
            minors: vec![0.0; stack.content.len()],
        }
    }

    fn resize(&mut self, len: usize) {
        self.majors.resize(len, 0.0);
        self.minors.resize(len, 0.0);
    }

    fn major(&self) -> f32 {
        self.majors.iter().copied().sum()
    }

    fn minor(&self) -> f32 {
        let mut total = 0.0;

        for minor in self.minors.iter().copied() {
            total = f32::max(total, minor);
        }

        total
    }
}

impl<T, V: ViewSeq<T>> View<T> for Stack<V> {
    type State = (StackState, SeqState<T, V>);

    fn build(&mut self, cx: &mut BuildCx, data: &mut T) -> Self::State {
        (
            StackState::new(self, cx.style()),
            self.content.build(cx, data),
        )
    }

    fn rebuild(
        &mut self,
        (state, content): &mut Self::State,
        cx: &mut RebuildCx,
        data: &mut T,
        old: &Self,
    ) {
        Rebuild::rebuild(self, cx, old);
        self.rebuild_style(cx, &mut state.style);

        if self.content.len() != old.content.len() {
            state.resize(self.content.len());
            cx.layout();
        }

        (self.content).rebuild(content, &mut cx.as_build_cx(), data, &old.content);

        for i in 0..self.content.len() {
            self.content.rebuild_nth(i, content, cx, data, &old.content)
        }
    }

    fn event(
        &mut self,
        (_, content): &mut Self::State,
        cx: &mut EventCx,
        data: &mut T,
        event: &Event,
    ) -> bool {
        self.content.event(content, cx, data, event)
    }

    fn layout(
        &mut self,
        (state, content): &mut Self::State,
        cx: &mut LayoutCx,
        data: &mut T,
        space: Space,
    ) -> Size {
        let (min_major, min_minor) = self.axis.unpack(space.min);
        let (max_major, max_minor) = self.axis.unpack(space.max);

        // this avoids a panic in later clamp calls
        let min_major = min_major.min(max_major);
        let min_minor = min_minor.min(max_minor);

        let total_gap = state.style.gap * (self.content.len() as f32 - 1.0);

        /* measure the content */

        let stretch_full = state.style.align == Align::Stretch && min_minor == max_minor;

        if state.style.align == Align::Fill || stretch_full {
            layout(
                self, cx, content, state, data, max_major, max_minor, max_minor, total_gap,
            );
        } else {
            layout(
                self, cx, content, state, data, max_major, 0.0, max_minor, total_gap,
            );

            /* stretch the content */

            if state.style.align == Align::Stretch {
                let minor = f32::clamp(state.minor(), min_minor, max_minor);
                layout(
                    self, cx, content, state, data, max_major, minor, minor, total_gap,
                );
            }
        }

        /* position content */

        let major = f32::clamp(state.major() + total_gap, min_major, max_major);
        let minor = f32::clamp(state.minor(), min_minor, max_minor);

        for (i, child_major) in (state.style.justify)
            .layout(&state.majors, major, state.style.gap)
            .enumerate()
        {
            let child_align = state.style.align.align(minor, state.minors[i]);
            let offset = self.axis.pack(child_major, child_align);
            content[i].translate(offset);
        }

        self.axis.pack(major, minor)
    }

    fn draw(&mut self, (_, content): &mut Self::State, cx: &mut DrawCx, data: &mut T) {
        for i in 0..self.content.len() {
            self.content.draw_nth(i, content, cx, data);
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn layout<T, V: ViewSeq<T>>(
    stack: &mut Stack<V>,
    cx: &mut LayoutCx,
    content: &mut SeqState<T, V>,
    state: &mut StackState,
    data: &mut T,
    max_major: f32,
    min_minor: f32,
    max_minor: f32,
    total_gap: f32,
) {
    state.flex_sum = 0.0;

    /* measure the non-flex content */

    for i in 0..stack.content.len() {
        if let Some(flex) = content[i].get_property::<Flex>() {
            state.flex_sum += flex.amount;
            state.majors[i] = 0.0;
            continue;
        }

        let space = Space::new(
            stack.axis.pack(0.0, min_minor),
            stack.axis.pack(f32::INFINITY, max_minor),
        );

        let size = stack.content.layout_nth(i, content, cx, data, space);
        state.majors[i] = stack.axis.major(size);
        state.minors[i] = stack.axis.minor(size);
    }

    /* measure the expanded content */

    let remaining = f32::max(max_major - total_gap - state.major(), 0.0);
    let per_flex = remaining / state.flex_sum;

    for i in 0..stack.content.len() {
        let Some(flex) = content[i].get_property::<Flex>() else {
            continue;
        };

        if !flex.is_tight {
            continue;
        }

        let major = per_flex * flex.amount;

        let space = Space::new(
            stack.axis.pack(0.0, min_minor),
            stack.axis.pack(major, max_minor),
        );

        let size = stack.content.layout_nth(i, content, cx, data, space);
        state.majors[i] = stack.axis.major(size);
        state.minors[i] = stack.axis.minor(size);
    }

    /* measure the flex content */

    let remaining = f32::max(max_major - total_gap - state.major(), 0.0);
    let per_flex = remaining / state.flex_sum;

    for i in 0..stack.content.len() {
        let Some(flex) = content[i].get_property::<Flex>() else {
            continue;
        };

        if flex.is_tight {
            continue;
        }

        let major = per_flex * flex.amount;

        let space = Space::new(
            stack.axis.pack(major, min_minor),
            stack.axis.pack(major, max_minor),
        );

        let size = stack.content.layout_nth(i, content, cx, data, space);
        state.majors[i] = stack.axis.major(size);
        state.minors[i] = stack.axis.minor(size);
    }
}