prism2 0.1.6

A GUI abstraction library for building UI kits
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
use std::sync::{Mutex, Arc};

#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub struct Area {
    pub offset: (f32, f32),
    pub size: (f32, f32)
}

/// Trait for layouts that determine the offset and allotted sizes of its children
pub trait Layout: std::fmt::Debug {

    /// Given a list of children size requests calculate the size request for the total layout
    fn request_size(&self, children: Vec<SizeRequest>) -> SizeRequest;

    /// Given an allotted size and the list of chlidren size requests (which may respect the size request),
    /// calculate the actual offsets and allotted sizes for its children
    fn build(&self, size: (f32, f32), children: Vec<SizeRequest>) -> Vec<Area>;
}

/// Structure used to designate space to a component or drawable.
///
/// A `SizeRequest` specifies the minimum and maximum dimensions that a
/// component is able to occupy. Layout systems can use this
/// information to determine how to allocate space during rendering.
#[derive(Debug, Clone, Copy, Default, PartialEq, PartialOrd)]
pub struct SizeRequest {
    min_width: f32,
    min_height: f32,
    max_width: f32,
    max_height: f32,
}
impl SizeRequest {
    /// Returns the minimum width.
    pub fn min_width(&self) -> f32 { self.min_width }

    /// Returns the minimum height.
    pub fn min_height(&self) -> f32 { self.min_height }

    /// Returns the maximum width.
    pub fn max_width(&self) -> f32 { self.max_width }

    /// Returns the maximum height.
    pub fn max_height(&self) -> f32 { self.max_height }

    /// Creates a new `SizeRequest`, panicking if min > max for either dimension.
    pub fn new(min_width: f32, min_height: f32, max_width: f32, max_height: f32) -> Self {
        if min_width > max_width { panic!("Min Width was Greater Than Max Width"); }
        if min_height > max_height { panic!("Min Height was Greater Than Max Height"); }
        SizeRequest { min_width, min_height, max_width, max_height }
    }

    /// Creates a fixed-size `SizeRequest` where min and max are equal.
    pub fn fixed(size: (f32, f32)) -> Self {
        SizeRequest { min_width: size.0, min_height: size.1, max_width: size.0, max_height: size.1 }
    }

    /// Creates a `SizeRequest` that can expand to fill all available space.
    pub fn fill() -> Self {
        SizeRequest { min_width: 0.0, min_height: 0.0, max_width: f32::MAX, max_height: f32::MAX }
    }

    /// Clamps a given size into this request's min/max bounds.
    pub fn get(&self, size: (f32, f32)) -> (f32, f32) {
        (
            self.max_width.min(self.min_width.max(size.0)),
            self.max_height.min(self.min_height.max(size.1))
        )
    }

    /// Returns a new request with both width and height increased.
    pub fn add(&self, w: f32, h: f32) -> SizeRequest {
        self.add_width(w).add_height(h)
    }

    /// Returns a new request with width increased.
    pub fn add_width(&self, w: f32) -> SizeRequest {
        SizeRequest::new(self.min_width + w, self.min_height, self.max_width + w, self.max_height)
    }

    /// Returns a new request with height increased.
    pub fn add_height(&self, h: f32) -> SizeRequest {
        SizeRequest::new(self.min_width, self.min_height + h, self.max_width, self.max_height + h)
    }

    /// Returns a new request with height decreased.
    pub fn remove_height(&self, h: f32) -> SizeRequest {
        SizeRequest::new(self.min_width, self.min_height - h, self.max_width, self.max_height - h)
    }

    /// Returns the combined maximum of two requests.
    pub fn max(&self, other: &Self) -> SizeRequest {
        SizeRequest::new(
            self.min_width.max(other.min_width),
            self.min_height.max(other.min_height),
            self.max_width.max(other.max_width),
            self.max_height.max(other.max_height)
        )
    }

    pub fn combine(&self, other: &Self) -> SizeRequest {
        SizeRequest::new(
            self.min_width+other.min_width,
            self.min_height+other.min_height,
            self.max_width+other.max_width,
            self.max_height+other.max_height
        )  
    }
}

/// A simple stack layout that overlays children on top of each other.
#[derive(Debug, Clone, Copy)]
pub struct DefaultStack;
impl Layout for DefaultStack {
    fn request_size(&self, children: Vec<SizeRequest>) -> SizeRequest {
        children.into_iter().reduce(|c, o| c.max(&o)).unwrap()
    }

    fn build(&self, size: (f32, f32), children: Vec<SizeRequest>) -> Vec<Area> {
        children.into_iter().map(|c| Area{offset: (0.0, 0.0), size: c.get(size)}).collect()
    }
}

#[derive(Clone, Copy, Default, Debug, PartialEq)]
pub enum Offset {
    #[default]
    Start,
    Center,
    End,
    Static(f32)
}

impl Offset {
    pub fn get(&self, max_size: f32, item_size: f32) -> f32 {
        match self {
            Self::Start => 0.0,
            Self::Center => (max_size - item_size) / 2.0,
            Self::End => max_size - item_size,
            Self::Static(offset) => *offset,
        }
    }

    pub fn size(&self) -> Option<f32> {
        match self {
            Self::Start => Some(0.0),
            Self::Center | Self::End => None,
            Self::Static(offset) => Some(*offset),
        }
    }
}

// type CustomFunc = dyn Fn(Vec<(f32, f32)>) -> (f32, f32);
type FitFunc = fn(Vec<(f32, f32)>) -> (f32, f32);

pub trait CustomFunc: Fn(Vec<(f32, f32)>) -> (f32, f32) + 'static {
    fn clone_box(&self) -> Box<dyn CustomFunc>;
}

impl<F> CustomFunc for F where F: Fn(Vec<(f32, f32)>) -> (f32, f32) + Clone + 'static {
    fn clone_box(&self) -> Box<dyn CustomFunc> { Box::new(self.clone()) }
}

impl Clone for Box<dyn CustomFunc> {fn clone(&self) -> Self {self.as_ref().clone_box()}}

impl std::fmt::Debug for dyn CustomFunc {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Page Builder...")
    }
}

/// Enum specifying how a layout should size and resize its content.
#[derive(Default, Clone)]
pub enum Size {
    #[default]
    /// Layout automatically fits the size of its children.
    Fit,
    /// The layout expands to fill the available space but stays within the parent’s maximum size and the minimum size required by its children.    
    Fill,
    /// Layout uses a fixed, static size.
    Static(f32),
    //// Layout size is determined by a custom function.
    Custom(Box<dyn CustomFunc>),
}

impl PartialEq for Size {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Size::Fit, Size::Fit) => true,
            (Size::Fill, Size::Fill) => true,
            (Size::Static(a), Size::Static(b)) => a == b,
            (Size::Custom(_), Size::Custom(_)) => false, // intentional
            _ => false,
        }
    }
}

impl Size {
    pub fn custom(func: impl Fn(Vec<(f32, f32)>) -> (f32, f32) + Clone + 'static) -> Self {
        Size::Custom(Box::new(func))
    }

    pub fn get(&self, items: Vec<(f32, f32)>, fit: FitFunc) -> (f32, f32) {
        match self {
            Size::Fit => fit(items),
            Size::Fill => (items.iter().fold(f32::MIN, |a, b| a.max(b.0)), f32::MAX),
            Size::Static(s) => (*s, *s),
            Size::Custom(f) => f(items)
        }
    }

    pub fn max(items: Vec<(f32, f32)>) -> (f32, f32) {
        items.into_iter().reduce(|s, i| (s.0.max(i.0), s.1.max(i.1))).unwrap_or_default()
    }

    pub fn add(items: Vec<(f32, f32)>) -> (f32, f32) {
        items.into_iter().reduce(|s, i| (s.0+i.0, s.1+i.1)).unwrap_or_default()
    }
}

impl std::fmt::Debug for Size {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Size::Fit => write!(f, "Size::Fit"),
            Size::Fill => write!(f, "Size::Fill"),
            Size::Static(val) => write!(f, "Size::Static({val})"),
            Size::Custom(_) => write!(f, "Size::Custom(<function>)"),
        }
    }
}

/// Structure used to define top, left, bottom, and right padding of an UI element.
///```rust
/// let padding = Padding(24.0, 16.0, 24.0, 16.0);
///```
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct Padding(pub f32, pub f32, pub f32, pub f32);

impl Padding {
    pub fn new(p: f32) -> Self {Padding(p, p, p, p)}

    pub fn adjust_size(&self, size: (f32, f32)) -> (f32, f32) {
        let wp = self.0+self.2;
        let hp = self.1+self.3;
        (size.0-wp, size.1-hp)
    }

    pub fn adjust_offset(&self, offset: (f32, f32)) -> (f32, f32) {
        (offset.0+self.0, offset.1+self.1)
    }

    pub fn adjust_request(&self, request: SizeRequest) -> SizeRequest {
        let wp = self.0+self.2;
        let hp = self.1+self.3;
        request.add(wp, hp)
    }
}

pub struct UniformExpand;

impl UniformExpand {
    pub fn get(sizes: Vec<(f32, f32)>, max_size: f32, spacing: f32) -> Vec<f32> {
        if sizes.is_empty() {return vec![];}
        let spacing = sizes.len().saturating_sub(1) as f32 * spacing;
        let min_size = sizes.iter().fold(0.0, |s, i| s + i.0) + spacing;

        let mut sizes = sizes.into_iter().map(|s| (s.0, s.1)).collect::<Vec<_>>();

        let mut free_space = (max_size - min_size).max(0.0);
        while free_space > 0.0 {
            let (min_exp, count, next) = sizes.iter().fold((None, 0.0, free_space), |(mut me, mut c, mut ne), size| {
                let min = size.0;
                let max = size.1;
                if min < max { // Item can expand
                    match me {
                        Some(w) if w < min => {
                            ne = ne.min(min - w); // Next size could be the min size of the next expandable block
                        },
                        Some(w) if w == min => {
                            ne = ne.min(max - min); // Next size could be the max size of one of the smallest items
                            c += 1.0;
                        },
                        Some(w) if w > min => {
                            ne = ne.min(max - min).min(w - min); // Next size could be the max size of one of the smallest items
                            me = Some(min);
                            c = 1.0;
                        },
                        _ => {
                            ne = ne.min(max - min); // Next size could be the max size of one of the smallest items
                            me = Some(min);
                            c = 1.0;
                        }
                    }
                }
                (me, c, ne)
            });

            if min_exp.is_none() { break; }
            let min_exp = min_exp.unwrap();

            let expand = (next * count).min(free_space); // Next size could be the rest of the free space
            free_space -= expand;
            let expand = expand / count;

            sizes.iter_mut().for_each(|size| {
                if size.0 < size.1 && size.0 == min_exp {
                    size.0 += expand;
                }
            });
        }

        sizes.into_iter().map(|s| s.0).collect()
    }
}

/// Horizontal layout of items.
///
/// <img src="https://raw.githubusercontent.com/ramp-stack/pelican_ui_std/main/src/examples/row.png"
///      alt="Row Example"
///      width="250">
///
///```rust
/// let layout = Row::new(24.0, Offset::Center, Size::Fit, Padding::new(8.0));
///```
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Row(f32, Offset, Size, Padding);

impl Row {
    pub fn new(spacing: f32, offset: Offset, size: Size, padding: Padding) -> Self {
        Row(spacing, offset, size, padding)
    }

    pub fn center(spacing: f32) -> Self {
        Row::new(spacing, Offset::Center, Size::Fit, Padding::default())
    }

    pub fn start(spacing: f32) -> Self {
        Row::new(spacing, Offset::Start, Size::Fit, Padding::default())
    }

    pub fn end(spacing: f32) -> Self {
        Row::new(spacing, Offset::End, Size::Fit, Padding::default())
    }

    pub fn padding(&mut self) -> &mut Padding {&mut self.3}
}

impl Layout for Row {
    fn request_size(&self, children: Vec<SizeRequest>) -> SizeRequest {
        let (widths, heights): (Vec<_>, Vec<_>) = children.into_iter().map(|i|
            ((i.min_width(), i.max_width()), (i.min_height(), i.max_height()))
        ).unzip();
        let spacing = self.0 * (widths.len() - 1) as f32;
        let width = Size::add(widths);
        let height = self.2.get(heights, Size::max);
        self.3.adjust_request(SizeRequest::new(width.0, height.0, width.1, height.1).add_width(spacing))
    }

    fn build(&self, row_size: (f32, f32), children: Vec<SizeRequest>) -> Vec<Area> {
        let row_size = self.3.adjust_size(row_size);
        let widths = UniformExpand::get(children.iter().map(|i| (i.min_width(), i.max_width())).collect::<Vec<_>>(), row_size.0, self.0);
        let mut offset = 0.0;
        children.into_iter().zip(widths).map(|(i, width)| {
            let size = i.get((width, row_size.1));
            let off = self.3.adjust_offset((offset, self.1.get(row_size.1, size.1)));
            if size.0 > 0.0 {offset += size.0+self.0;}
            Area{offset: off, size}
        }).collect()
    }
}

/// Vertical layout of items.
///
/// <img src="https://raw.githubusercontent.com/ramp-stack/pelican_ui_std/main/src/examples/column.png"
///      alt="Column Example"
///      width="250">
///
///```rust
/// let layout = Column::new(24.0, Offset::Center, Size::Fit, Padding::new(8.0));
///```
#[derive(Debug, Default, Clone)]
pub struct Column(f32, Offset, Size, Padding, Option<Arc<Mutex<f32>>>, ScrollAnchor);

impl PartialEq for Column {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
        && self.1 == other.1
        && self.2 == other.2
        && self.3 == other.3
        && self.5 == other.5
    }
}

impl Column {
    pub fn new(spacing: f32, offset: Offset, size: Size, padding: Padding, scroll: Option<ScrollAnchor>) -> Self {
        Column(spacing, offset, size, padding, scroll.is_some().then_some(Arc::new(Mutex::new(0.0))), scroll.unwrap_or_default())
    }

    pub fn center(spacing: f32) -> Self {
        Column(spacing, Offset::Center, Size::Fill, Padding::default(), None, ScrollAnchor::default())
    }

    pub fn start(spacing: f32) -> Self {
        Column(spacing, Offset::Start, Size::Fill, Padding::default(), None, ScrollAnchor::default())
    }

    pub fn end(spacing: f32) -> Self {
        Column(spacing, Offset::End, Size::Fill, Padding::default(), None, ScrollAnchor::default())
    }

    pub fn padding(&mut self) -> &mut Padding {&mut self.3}

    pub fn adjust_scroll(&mut self, delta: f32) { 
        if let Some(s) = &mut self.4 { 
            match self.5 {
                ScrollAnchor::Start => **s.lock().as_mut().unwrap() += delta,
                ScrollAnchor::End => **s.lock().as_mut().unwrap() -= delta,
            }
        }
    }

    pub fn set_scroll(&mut self, val: f32) { if let Some(s) = &mut self.4 { **s.lock().as_mut().unwrap() = val; } }
}

impl Layout for Column {
    fn request_size(&self, children: Vec<SizeRequest>) -> SizeRequest {
        if children.is_empty() { return SizeRequest::default() };
        let (widths, heights): (Vec<_>, Vec<_>) = children.into_iter().map(|i|
            ((i.min_width(), i.max_width()), (i.min_height(), i.max_height()))
        ).unzip();
        let spacing = self.0*(heights.len()-1) as f32;
        let width = self.2.get(widths, Size::max);
        let height = Size::add(heights.clone());
        let size_request = match self.4.is_some() {
            true => SizeRequest::new(0.0, 0.0, width.1, height.1),
            false => SizeRequest::new(width.0, height.0, width.1, height.1)
        };
        self.3.adjust_request(size_request.add_height(spacing))
    }

    fn build(&self, col_size: (f32, f32), mut children: Vec<SizeRequest>) -> Vec<Area> {
        let col_size = self.3.adjust_size(col_size);

        let spacing = self.0 * children.len().saturating_sub(1) as f32;
        let ranges: Vec<_> = children.iter().map(|c| (c.min_height(), c.max_height())).collect();
        let heights = UniformExpand::get(ranges, col_size.1, self.0);
        let content_height = heights.iter().sum::<f32>() + spacing;

        let mut offset = 0.0; //Offset::Start.get(col_size.1, content_height).max(0.0);

        let max_scroll = (content_height - col_size.1).max(0.0);
        let scroll = self.4.as_ref().map(|s| {
            let mut v = s.lock().unwrap();
            *v = v.clamp(0.0, max_scroll);
            *v
        }).unwrap_or(0.0);

        let is_end = self.5 == ScrollAnchor::End;
        if is_end { children.reverse(); }

        let mut areas: Vec<_> = children.into_iter().zip(heights).map(|(child, h)| {
            let size = child.get((col_size.0, h));
            let off_y = { let o = offset; offset += size.1 + self.0; o };
            let n = if is_end {col_size.1 - h + scroll} else {off_y - scroll};
            Area { offset: self.3.adjust_offset((self.1.get(col_size.0, size.0), n)), size }
        }).collect();

        if is_end { areas.reverse(); }
        areas
    }

}


/// Items stacked on top of each other
///
/// <img src="https://raw.githubusercontent.com/ramp-stack/pelican_ui_std/main/src/examples/stack.png"
///      alt="Stack Example"
///      width="250">
///
///```rust
/// let layout = Stack(Offset::Center, Offset::Center, Size::Fit, Size::Fit, Padding::new(8.0));
///```
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Stack(pub Offset, pub Offset, pub Size, pub Size, pub Padding);

impl Stack {
    pub fn new(x_offset: Offset, y_offset: Offset, x_size: Size, y_size: Size, padding: Padding) -> Self {
        Stack(x_offset, y_offset, x_size, y_size, padding)
    }

    pub fn center() -> Self {
        Stack(Offset::Center, Offset::Center, Size::Fit, Size::Fit, Padding::default())
    }

    pub fn start() -> Self {
        Stack(Offset::Start, Offset::Start, Size::Fit, Size::Fit, Padding::default())
    }

    pub fn end() -> Self {
        Stack(Offset::End, Offset::End, Size::Fit, Size::Fit, Padding::default())
    }

    pub fn fill() -> Self {
        Stack(Offset::Center, Offset::Center, Size::Fill, Size::Fill, Padding::default())
    }
}

impl Layout for Stack {
    fn request_size(&self, children: Vec<SizeRequest>) -> SizeRequest {
        let (widths, heights): (Vec<_>, Vec<_>) = children.into_iter().map(|r|
            ((r.min_width(), r.max_width()), (r.min_height(), r.max_height()))
        ).unzip();
        let width = self.2.get(widths, Size::max);
        let height = self.3.get(heights, Size::max);
        self.4.adjust_request(SizeRequest::new(width.0, height.0, width.1, height.1))
    }

    fn build(&self, stack_size: (f32, f32), children: Vec<SizeRequest>) -> Vec<Area> {
        let stack_size = self.4.adjust_size(stack_size);
        children.into_iter().map(|i| {
            let size = i.get(stack_size);
            let offset = (self.0.get(stack_size.0, size.0), self.1.get(stack_size.1, size.1));
            Area{offset: self.4.adjust_offset(offset), size}
        }).collect()
    }
}

/// Horizontal layout that automatically wraps items to the next row when the maximum width is exceeded.
///
/// <img src="https://raw.githubusercontent.com/ramp-stack/pelican_ui_std/main/src/examples/wrap.png"
///      alt="Wrap Example"
///      width="350">
///
///```rust
/// let layout = Wrap::new(8.0, 8.0);
///```
#[derive(Debug, Clone)]
pub struct Wrap(pub f32, pub f32, pub Offset, pub Offset, pub Padding, Arc<Mutex<f32>>);

impl Wrap {
    pub fn new(w_spacing: f32, h_spacing: f32) -> Self {
        Wrap(w_spacing, h_spacing, Offset::Center, Offset::Center, Padding::default(), Arc::new(Mutex::new(0.0)))
    }

    pub fn start(w_spacing: f32, h_spacing: f32) -> Self {
        Wrap(w_spacing, h_spacing, Offset::Start, Offset::Center, Padding::default(), Arc::new(Mutex::new(0.0)))
    }

    pub fn end(w_spacing: f32, h_spacing: f32) -> Self {
        Wrap(w_spacing, h_spacing, Offset::End, Offset::Center, Padding::default(), Arc::new(Mutex::new(0.0)))
    }

    pub fn center(w_spacing: f32, h_spacing: f32) -> Self {
        Wrap(w_spacing, h_spacing, Offset::Center, Offset::Center, Padding::default(), Arc::new(Mutex::new(0.0)))
    }
}


impl PartialEq for Wrap {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
        && self.1 == other.1
        && self.2 == other.2
        && self.3 == other.3
        && self.4 == other.4
    }
}

impl Layout for Wrap {
    fn request_size(&self, children: Vec<SizeRequest>) -> SizeRequest {
        let available_width = *self.5.lock().unwrap();

        let left = self.4.1;
        let right = self.4.2;
        let top = self.4.0;
        let bottom = self.4.3;

        if children.is_empty() {
            let w = left + right;
            let h = top + bottom;
            return SizeRequest::fixed((w, h));
        }

        let widest_child = children
            .iter()
            .map(|c| c.min_width())
            .fold(0.0_f32, f32::max);

        let tallest_child = children
            .iter()
            .map(|c| c.min_height())
            .fold(0.0_f32, f32::max);

        let min_width = widest_child + left + right;

        if available_width <= 0.0 {
            let min_height = tallest_child + top + bottom;
            return SizeRequest::new(min_width, min_height, f32::MAX, f32::MAX);
        }

        let content_width = (available_width - left - right).max(0.0);

        let mut line_w = 0.0_f32;
        let mut line_h = 0.0_f32;
        let mut total_h = top;
        let mut max_used_w = 0.0_f32;
        let mut has_any = false;

        for child in &children {
            let w = child.min_width();
            let h = child.min_height();

            let projected_w = if line_w == 0.0 { w } else { line_w + self.0 + w };

            if line_w > 0.0 && projected_w > content_width {
                max_used_w = max_used_w.max(line_w);
                total_h += line_h + self.1;

                line_w = w;
                line_h = h;
            } else {
                line_w = projected_w;
                line_h = line_h.max(h);
            }

            has_any = true;
        }

        if has_any {
            max_used_w = max_used_w.max(line_w);
            total_h += line_h;
        }

        let min_height = total_h + bottom;
        let max_width = available_width.max(min_width);
        let max_height = min_height;

        let _used_width_with_padding = max_used_w + left + right;

        SizeRequest::new(min_width, min_height, max_width, max_height)
    }

    fn build(&self, maximum_size: (f32, f32), children: Vec<SizeRequest>) -> Vec<Area> {
        let left = self.4.1;
        let right = self.4.2;
        let top = self.4.0;
        let _bottom = self.4.3;

        let content_width = (maximum_size.0 - left - right).max(0.0);

        if let Ok(mut stored) = self.5.lock() {
            *stored = maximum_size.0;
        }

        if children.is_empty() {
            return Vec::new();
        }

        #[derive(Clone, Copy)]
        struct Item {
            w: f32,
            h: f32,
        }

        let mut lines: Vec<Vec<Item>> = Vec::new();
        let mut line_widths: Vec<f32> = Vec::new();
        let mut line_heights: Vec<f32> = Vec::new();

        let mut current_line: Vec<Item> = Vec::new();
        let mut current_w = 0.0_f32;
        let mut current_h = 0.0_f32;

        for child in children {
            let item = Item {
                w: child.min_width(),
                h: child.min_height(),
            };

            let projected_w = if current_line.is_empty() {
                item.w
            } else {
                current_w + self.0 + item.w
            };

            if !current_line.is_empty() && projected_w > content_width {
                lines.push(current_line);
                line_widths.push(current_w);
                line_heights.push(current_h);

                current_line = vec![item];
                current_w = item.w;
                current_h = item.h;
            } else {
                if current_line.is_empty() {
                    current_w = item.w;
                } else {
                    current_w += self.0 + item.w;
                }
                current_h = current_h.max(item.h);
                current_line.push(item);
            }
        }

        if !current_line.is_empty() {
            lines.push(current_line);
            line_widths.push(current_w);
            line_heights.push(current_h);
        }

        let mut areas = Vec::new();
        let mut y = top;

        for ((line, &line_w), &line_h) in lines.iter().zip(&line_widths).zip(&line_heights) {
            let extra_x = (content_width - line_w).max(0.0);

            let start_x = match self.2 {
                Offset::Start => left,
                Offset::End => left + extra_x,
                Offset::Center => left + extra_x / 2.0,
                Offset::Static(x) => left + x,
            };

            let mut x = start_x;

            for item in line {
                let child_y = match self.3 {
                    Offset::Start => y,
                    Offset::End => y + (line_h - item.h).max(0.0),
                    Offset::Center => y + (line_h - item.h).max(0.0) / 2.0,
                    Offset::Static(v) => y + v,
                };

                areas.push(Area {
                    offset: (x, child_y),
                    size: (item.w, item.h),
                });

                x += item.w + self.0;
            }

            y += line_h + self.1;
        }

        areas
    }
}

/// Defines the reference point for scrolling content.
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub enum ScrollAnchor {
    #[default]
    Start,
    End,
}