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
#![doc(html_favicon_url = "https://raw.githubusercontent.com/zng-ui/zng/main/examples/image/res/zng-logo-icon.png")]
#![doc(html_logo_url = "https://raw.githubusercontent.com/zng-ui/zng/main/examples/image/res/zng-logo.png")]
//!
//! Base container widget and properties.
//!
//! # Crate
//!
#![doc = include_str!(concat!("../", std::env!("CARGO_PKG_README")))]
#![warn(unused_extern_crates)]
#![warn(missing_docs)]

use std::fmt;

use zng_wgt::{align, clip_to_bounds, margin, prelude::*};

/// Base container.
#[widget($crate::Container {
    ($child:expr) => {
        child = $child;
    }
})]
pub struct Container(WidgetBase);
impl Container {
    fn widget_intrinsic(&mut self) {
        self.widget_builder().push_build_action(|wgt| {
            if let Some(child) = wgt.capture_ui_node(property_id!(Self::child)) {
                wgt.set_child(child);
            }
        });
    }

    widget_impl! {
        /// Content overflow clipping.
        pub clip_to_bounds(clip: impl IntoVar<bool>);
    }
}

/// The content.
///
/// Can be any type that implements [`UiNode`], any widget.
///
/// [`UiNode`]: zng_app::widget::node::UiNode
#[property(CHILD, capture, default(FillUiNode), widget_impl(Container))]
pub fn child(child: impl UiNode) {}

/// Margin space around the content of a widget.
///
/// This property is [`margin`](fn@margin) with nest group `CHILD_LAYOUT`.
#[property(CHILD_LAYOUT, default(0), widget_impl(Container))]
pub fn padding(child: impl UiNode, padding: impl IntoVar<SideOffsets>) -> impl UiNode {
    margin(child, padding)
}

/// Aligns the widget *content* within the available space.
///
/// This property is [`align`](fn@align) with nest group `CHILD_LAYOUT`.
#[property(CHILD_LAYOUT, default(Align::FILL), widget_impl(Container))]
pub fn child_align(child: impl UiNode, alignment: impl IntoVar<Align>) -> impl UiNode {
    align(child, alignment)
}

/// Placement of a node inserted by the [`child_insert`] property.
///
/// [`child_insert`]: fn@child_insert
#[derive(Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ChildInsert {
    /// Insert node above the child.
    Top,
    /// Insert node to the right of child.
    Right,
    /// Insert node below the child.
    Bottom,
    /// Insert node to the left of child.
    Left,

    /// Insert node to the left of child in [`LayoutDirection::LTR`] contexts and to the right of child
    /// in [`LayoutDirection::RTL`] contexts.
    ///
    /// [`LayoutDirection::LTR`]: zng_wgt::prelude::LayoutDirection::LTR
    /// [`LayoutDirection::RTL`]: zng_wgt::prelude::LayoutDirection::RTL
    Start,
    /// Insert node to the right of child in [`LayoutDirection::LTR`] contexts and to the left of child
    /// in [`LayoutDirection::RTL`] contexts.
    ///
    /// [`LayoutDirection::LTR`]: zng_wgt::prelude::LayoutDirection::LTR
    /// [`LayoutDirection::RTL`]: zng_wgt::prelude::LayoutDirection::RTL
    End,

    /// Insert node over the child.
    ///
    /// Spacing is ignored for this placement.
    Over,
    /// Insert node under the child.
    ///
    /// Spacing is ignored for this placement.
    Under,
}
impl fmt::Debug for ChildInsert {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            write!(f, "ChildInsert::")?;
        }
        match self {
            Self::Top => write!(f, "Top"),
            Self::Right => write!(f, "Right"),
            Self::Bottom => write!(f, "Bottom"),
            Self::Left => write!(f, "Left"),
            Self::Start => write!(f, "Start"),
            Self::End => write!(f, "End"),
            Self::Over => write!(f, "Over"),
            Self::Under => write!(f, "Under"),
        }
    }
}
impl ChildInsert {
    /// Convert [`ChildInsert::Start`] and [`ChildInsert::End`] to the fixed place they represent in the `direction` context.
    pub fn resolve_direction(self, direction: LayoutDirection) -> Self {
        match self {
            Self::Start => match direction {
                LayoutDirection::LTR => Self::Left,
                LayoutDirection::RTL => Self::Right,
            },
            Self::End => match direction {
                LayoutDirection::LTR => Self::Right,
                LayoutDirection::RTL => Self::Left,
            },
            p => p,
        }
    }

    /// Inserted node is to the left or right of child.
    pub fn is_x_axis(self) -> bool {
        !matches!(self, Self::Top | Self::Bottom)
    }

    /// Inserted node is above or bellow the child node.
    pub fn is_y_axis(self) -> bool {
        matches!(self, Self::Top | Self::Bottom)
    }

    /// Inserted node is over or under the child node.
    pub fn is_z_axis(self) -> bool {
        matches!(self, Self::Over | Self::Under)
    }
}

/// Insert `node` in the `placement` relative to the widget's child.
///
/// This property disables inline layout for the widget.
#[property(CHILD, default(ChildInsert::Start, NilUiNode, 0), widget_impl(Container))]
pub fn child_insert(
    child: impl UiNode,
    placement: impl IntoVar<ChildInsert>,
    node: impl UiNode,
    spacing: impl IntoVar<Length>,
) -> impl UiNode {
    let placement = placement.into_var();
    let spacing = spacing.into_var();
    let offset_key = FrameValueKey::new_unique();
    let mut offset_child = 0;
    let mut offset = PxVector::zero();

    match_node_list(ui_vec![child, node], move |children, op| match op {
        UiNodeOp::Init => {
            WIDGET.sub_var_layout(&placement).sub_var_layout(&spacing);
        }
        UiNodeOp::Measure { wm, desired_size } => {
            let c = LAYOUT.constraints();
            let placement = placement.get();
            *desired_size = if placement.is_x_axis() {
                let mut spacing = spacing.layout_x();
                let insert_size = children.with_node(1, |n| {
                    LAYOUT.with_constraints(c.with_new_min(Px(0), Px(0)).with_fill_x(false), || wm.measure_block(n))
                });
                if insert_size.width == 0 {
                    spacing = Px(0);
                }
                let child_size = children.with_node(0, |n| {
                    LAYOUT.with_constraints(c.with_less_x(insert_size.width + spacing), || wm.measure_block(n))
                });

                PxSize::new(
                    insert_size.width + spacing + child_size.width,
                    insert_size.height.max(child_size.height),
                )
            } else if placement.is_y_axis() {
                let mut spacing = spacing.layout_y();
                let insert_size = children.with_node(1, |n| {
                    LAYOUT.with_constraints(c.with_new_min(Px(0), Px(0)).with_fill_y(false), || wm.measure_block(n))
                });
                if insert_size.height == 0 {
                    spacing = Px(0);
                }
                let child_size = children.with_node(0, |n| {
                    LAYOUT.with_constraints(c.with_less_y(insert_size.height + spacing), || wm.measure_block(n))
                });
                if child_size.height == 0 {
                    spacing = Px(0);
                }
                PxSize::new(
                    insert_size.width.max(child_size.width),
                    insert_size.height + spacing + child_size.height,
                )
            } else {
                children.with_node(0, |n| wm.measure_block(n))
            };
        }
        UiNodeOp::Layout { wl, final_size } => {
            wl.require_child_ref_frame();

            let placement = placement.get().resolve_direction(LAYOUT.direction());
            let c = LAYOUT.constraints();

            *final_size = match placement {
                ChildInsert::Left | ChildInsert::Right => {
                    let spacing = spacing.layout_x();

                    let mut constraints_y = LAYOUT.constraints().y;
                    if constraints_y.fill_or_exact().is_none() {
                        // measure to find fill height
                        let mut wm = wl.to_measure(None);
                        let wm = &mut wm;
                        let mut spacing = spacing;

                        let insert_size = children.with_node(1, |n| {
                            LAYOUT.with_constraints(c.with_new_min(Px(0), Px(0)).with_fill_x(false), || n.measure(wm))
                        });
                        if insert_size.width == 0 {
                            spacing = Px(0);
                        }
                        let child_size = children.with_node(0, |n| {
                            LAYOUT.with_constraints(c.with_less_x(insert_size.width + spacing), || n.measure(wm))
                        });

                        constraints_y = constraints_y.with_fill(true).with_max(child_size.height.max(insert_size.height));
                    }

                    let mut spacing = spacing;
                    let insert_size = children.with_node(1, |n| {
                        LAYOUT.with_constraints(
                            {
                                let mut c = c;
                                c.y = constraints_y;
                                c.with_new_min(Px(0), Px(0)).with_fill_x(false)
                            },
                            || n.layout(wl),
                        )
                    });
                    if insert_size.width == 0 {
                        spacing = Px(0);
                    }
                    let child_size = children.with_node(0, |n| {
                        LAYOUT.with_constraints(
                            {
                                let mut c = c;
                                c.y = constraints_y;
                                c.with_less_x(insert_size.width + spacing)
                            },
                            || n.layout(wl),
                        )
                    });
                    if child_size.width == 0 {
                        spacing = Px(0);
                    }

                    // position
                    let (child, o) = match placement {
                        ChildInsert::Left => (0, insert_size.width + spacing),
                        ChildInsert::Right => (1, child_size.width + spacing),
                        _ => unreachable!(),
                    };
                    let o = PxVector::new(o, Px(0));
                    if offset != o || offset_child != child {
                        offset_child = child;
                        offset = o;
                        WIDGET.render_update();
                    }

                    PxSize::new(
                        insert_size.width + spacing + child_size.width,
                        insert_size.height.max(child_size.height),
                    )
                }
                ChildInsert::Top | ChildInsert::Bottom => {
                    let spacing = spacing.layout_y();

                    let mut constraints_x = c.x;
                    if constraints_x.fill_or_exact().is_none() {
                        // measure fill width

                        let mut wm = wl.to_measure(None);
                        let wm = &mut wm;
                        let mut spacing = spacing;

                        let insert_size = children.with_node(1, |n| {
                            LAYOUT.with_constraints(c.with_new_min(Px(0), Px(0)).with_fill_y(false), || n.measure(wm))
                        });
                        if insert_size.height == 0 {
                            spacing = Px(0);
                        }
                        let child_size = children.with_node(0, |n| {
                            LAYOUT.with_constraints(c.with_less_y(insert_size.height + spacing), || n.measure(wm))
                        });

                        constraints_x = constraints_x.with_fill(true).with_max(child_size.width.max(insert_size.width));
                    }

                    let mut spacing = spacing;
                    let insert_size = children.with_node(1, |n| {
                        LAYOUT.with_constraints(
                            {
                                let mut c = c;
                                c.x = constraints_x;
                                c.with_new_min(Px(0), Px(0)).with_fill_y(false)
                            },
                            || n.layout(wl),
                        )
                    });
                    if insert_size.height == 0 {
                        spacing = Px(0);
                    }
                    let child_size = children.with_node(0, |n| {
                        LAYOUT.with_constraints(
                            {
                                let mut c = c;
                                c.x = constraints_x;
                                c.with_less_y(insert_size.height + spacing)
                            },
                            || n.layout(wl),
                        )
                    });

                    // position
                    let (child, o) = match placement {
                        ChildInsert::Top => (0, insert_size.height + spacing),
                        ChildInsert::Bottom => (1, child_size.height + spacing),
                        _ => unreachable!(),
                    };
                    let o = PxVector::new(Px(0), o);
                    if offset != o || offset_child != child {
                        offset_child = child;
                        offset = o;
                        WIDGET.render_update();
                    }

                    PxSize::new(
                        insert_size.width.max(child_size.width),
                        insert_size.height + spacing + child_size.height,
                    )
                }
                ChildInsert::Over | ChildInsert::Under => {
                    let child_size = children.with_node(0, |n| n.layout(wl));
                    children.with_node(1, |n| {
                        LAYOUT.with_constraints(PxConstraints2d::new_exact_size(child_size), || n.layout(wl));
                    });
                    child_size
                }
                ChildInsert::Start | ChildInsert::End => unreachable!(), // already resolved
            };
        }
        UiNodeOp::Render { frame } => match placement.get() {
            ChildInsert::Over => children.render_all(frame),
            ChildInsert::Under => {
                children.with_node(1, |n| n.render(frame));
                children.with_node(0, |n| n.render(frame));
            }
            _ => children.for_each(|i, child| {
                if i as u8 == offset_child {
                    frame.push_reference_frame(offset_key.into(), offset_key.bind(offset.into(), false), true, true, |frame| {
                        child.render(frame);
                    });
                } else {
                    child.render(frame);
                }
            }),
        },
        UiNodeOp::RenderUpdate { update } => match placement.get() {
            ChildInsert::Over => children.render_update_all(update),
            ChildInsert::Under => {
                children.with_node(1, |n| n.render_update(update));
                children.with_node(0, |n| n.render_update(update));
            }
            _ => {
                children.for_each(|i, child| {
                    if i as u8 == offset_child {
                        update.with_transform(offset_key.update(offset.into(), false), true, |update| {
                            child.render_update(update);
                        });
                    } else {
                        child.render_update(update);
                    }
                });
            }
        },
        _ => {}
    })
}

/// Insert `node` in the `placement` relative to the widget's child, outside of the child layout.
///
/// This is still *inside* the parent widget, but outside of properties like padding.
///
/// This property disables inline layout for the widget.
#[property(CHILD_LAYOUT - 1, default(ChildInsert::Start, NilUiNode, 0), widget_impl(Container))]
pub fn child_out_insert(
    child: impl UiNode,
    placement: impl IntoVar<ChildInsert>,
    node: impl UiNode,
    spacing: impl IntoVar<Length>,
) -> impl UiNode {
    child_insert(child, placement, node, spacing)
}

/// Insert `node` to the left of the widget's child.
///
/// This property disables inline layout for the widget. See [`child_insert`] for more details.
///
/// [`child_insert`]: fn@child_insert
#[property(CHILD, default(NilUiNode, 0), widget_impl(Container))]
pub fn child_left(child: impl UiNode, node: impl UiNode, spacing: impl IntoVar<Length>) -> impl UiNode {
    child_insert(child, ChildInsert::Left, node, spacing)
}

/// Insert `node` to the right of the widget's child.
///
/// This property disables inline layout for the widget. See [`child_insert`] for more details.
///
/// [`child_insert`]: fn@child_insert
#[property(CHILD, default(NilUiNode, 0), widget_impl(Container))]
pub fn child_right(child: impl UiNode, node: impl UiNode, spacing: impl IntoVar<Length>) -> impl UiNode {
    child_insert(child, ChildInsert::Right, node, spacing)
}

/// Insert `node` above the widget's child.
///
/// This property disables inline layout for the widget. See [`child_insert`] for more details.
///
/// [`child_insert`]: fn@child_insert
#[property(CHILD, default(NilUiNode, 0), widget_impl(Container))]
pub fn child_top(child: impl UiNode, node: impl UiNode, spacing: impl IntoVar<Length>) -> impl UiNode {
    child_insert(child, ChildInsert::Top, node, spacing)
}

/// Insert `node` below the widget's child.
///
/// This property disables inline layout for the widget. See [`child_insert`] for more details.
///
/// [`child_insert`]: fn@child_insert
#[property(CHILD, default(NilUiNode, 0), widget_impl(Container))]
pub fn child_bottom(child: impl UiNode, node: impl UiNode, spacing: impl IntoVar<Length>) -> impl UiNode {
    child_insert(child, ChildInsert::Bottom, node, spacing)
}

/// Insert `node` to the left of the widget's child in LTR contexts or to the right in RTL contexts.
///
/// This property disables inline layout for the widget. See [`child_insert`] for more details.
///
/// [`child_insert`]: fn@child_insert
#[property(CHILD, default(NilUiNode, 0), widget_impl(Container))]
pub fn child_start(child: impl UiNode, node: impl UiNode, spacing: impl IntoVar<Length>) -> impl UiNode {
    child_insert(child, ChildInsert::Start, node, spacing)
}

/// Insert `node` to the right of the widget's child in LTR contexts or to the right of the widget's child in RTL contexts.
///
/// This property disables inline layout for the widget. See [`child_insert`] for more details.
///
/// [`child_insert`]: fn@child_insert
#[property(CHILD, default(NilUiNode, 0), widget_impl(Container))]
pub fn child_end(child: impl UiNode, node: impl UiNode, spacing: impl IntoVar<Length>) -> impl UiNode {
    child_insert(child, ChildInsert::End, node, spacing)
}

/// Insert `node` over the widget's child.
///
/// This property disables inline layout for the widget. See [`child_insert`] for more details.
///
/// [`child_insert`]: fn@child_insert
#[property(CHILD, default(NilUiNode), widget_impl(Container))]
pub fn child_over(child: impl UiNode, node: impl UiNode) -> impl UiNode {
    child_insert(child, ChildInsert::Over, node, 0)
}

/// Insert `node` under the widget's child.
///
/// This property disables inline layout for the widget. See [`child_insert`] for more details.
///
/// [`child_insert`]: fn@child_insert
#[property(CHILD, default(NilUiNode), widget_impl(Container))]
pub fn child_under(child: impl UiNode, node: impl UiNode) -> impl UiNode {
    child_insert(child, ChildInsert::Under, node, 0)
}

/// Insert `node` to the left of the widget's child, outside of the child layout.
///
/// This property disables inline layout for the widget. See [`child_out_insert`] for more details.
///
/// [`child_out_insert`]: fn@child_insert
#[property(CHILD_LAYOUT - 1, default(NilUiNode, 0), widget_impl(Container))]
pub fn child_out_left(child: impl UiNode, node: impl UiNode, spacing: impl IntoVar<Length>) -> impl UiNode {
    child_out_insert(child, ChildInsert::Left, node, spacing)
}

/// Insert `node` to the right of the widget's child, outside of the child layout.
///
/// This property disables inline layout for the widget. See [`child_out_insert`] for more details.
///
/// [`child_out_insert`]: fn@child_out_insert
#[property(CHILD_LAYOUT - 1, default(NilUiNode, 0), widget_impl(Container))]
pub fn child_out_right(child: impl UiNode, node: impl UiNode, spacing: impl IntoVar<Length>) -> impl UiNode {
    child_out_insert(child, ChildInsert::Right, node, spacing)
}

/// Insert `node` above the widget's child, outside of the child layout.
///
/// This property disables inline layout for the widget. See [`child_out_insert`] for more details.
///
/// [`child_out_insert`]: fn@child_out_insert
#[property(CHILD_LAYOUT - 1, default(NilUiNode, 0), widget_impl(Container))]
pub fn child_out_top(child: impl UiNode, node: impl UiNode, spacing: impl IntoVar<Length>) -> impl UiNode {
    child_out_insert(child, ChildInsert::Top, node, spacing)
}

/// Insert `node` below the widget's child, outside of the child layout.
///
/// This property disables inline layout for the widget. See [`child_out_insert`] for more details.
///
/// [`child_out_insert`]: fn@child_out_insert
#[property(CHILD_LAYOUT - 1, default(NilUiNode, 0), widget_impl(Container))]
pub fn child_out_bottom(child: impl UiNode, node: impl UiNode, spacing: impl IntoVar<Length>) -> impl UiNode {
    child_out_insert(child, ChildInsert::Bottom, node, spacing)
}

/// Insert `node` to the left of the widget's child in LTR contexts or to the right in RTL contexts, outside of the child layout.
///
/// This property disables inline layout for the widget. See [`child_out_insert`] for more details.
///
/// [`child_out_insert`]: fn@child_out_insert
#[property(CHILD_LAYOUT - 1, default(NilUiNode, 0), widget_impl(Container))]
pub fn child_out_start(child: impl UiNode, node: impl UiNode, spacing: impl IntoVar<Length>) -> impl UiNode {
    child_out_insert(child, ChildInsert::Start, node, spacing)
}

/// Insert `node` to the right of the widget's child in LTR contexts or to the right of the widget's child in RTL contexts, outside of the child layout.
///
/// This property disables inline layout for the widget. See [`child_out_insert`] for more details.
///
/// [`child_out_insert`]: fn@child_out_insert
#[property(CHILD_LAYOUT - 1, default(NilUiNode, 0), widget_impl(Container))]
pub fn child_out_end(child: impl UiNode, node: impl UiNode, spacing: impl IntoVar<Length>) -> impl UiNode {
    child_out_insert(child, ChildInsert::End, node, spacing)
}

/// Insert `node` over the widget's child, not affected by child layout.
///
/// This property disables inline layout for the widget. See [`child_out_insert`] for more details.
///
/// [`child_out_insert`]: fn@child_out_insert
#[property(CHILD_LAYOUT - 1, default(NilUiNode), widget_impl(Container))]
pub fn child_out_over(child: impl UiNode, node: impl UiNode) -> impl UiNode {
    child_out_insert(child, ChildInsert::Over, node, 0)
}

/// Insert `node` under the widget's child, not affected by child layout.
///
/// This property disables inline layout for the widget. See [`child_out_insert`] for more details.
///
/// [`child_out_insert`]: fn@child_out_insert
#[property(CHILD_LAYOUT - 1, default(NilUiNode), widget_impl(Container))]
pub fn child_out_under(child: impl UiNode, node: impl UiNode) -> impl UiNode {
    child_out_insert(child, ChildInsert::Under, node, 0)
}