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
#![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")]
//!
//! Stack widgets, properties and nodes.
//!
//! # Crate
//!
#![doc = include_str!(concat!("../", std::env!("CARGO_PKG_README")))]

zng_wgt::enable_widget_macros!();

use zng_wgt::prelude::*;

mod types;
pub use types::*;

/// Stack layout.
///
/// Without [`direction`] this is a Z layering stack, with direction the traditional vertical and horizontal *stack panels*
/// can be created, other custom layouts are also supported, diagonal stacks, partially layered stacks and more. See
/// [`StackDirection`] for more details.
///
/// # Z-Index
///
/// By default the widgets are rendered in their logical order, the last widget renders in front of the others,
/// you can change this by setting the [`z_index`] property in the item widget.
///
/// # Shorthand
///
/// The `Stack!` macro provides shorthand syntax:
///
/// * `Stack!($children:expr)` creates a Z stack.
/// * `Stack!($direction:ident, $children:expr)` create stack on the given direction. The first parameter is
///   the name of one of the [`LayoutDirection`] associated functions.
/// * `Stack!($direction:ident, $spacing:expr, $children:expr)` create stack with the given direction, spacing between items and the items.
/// * `Stack!($direction:expr, $children:expr)` create stack on the given direction. The first parameter is an expression of
/// type [`LayoutDirection`]. Note that to avoid conflict with the alternative (`$direction:ident`) you can use braces `{my_direction}`.
/// * `Stack!($direction:expr, $spacing:expr, $children:expr)` create stack with the given direction expression, spacing between items
/// and the items.
///
/// # `stack_nodes`
///
/// If you only want to create an overlaying effect composed of multiple nodes you can use the [`stack_nodes`] function.
///
/// [`stack_nodes`]: fn@stack_nodes
///
/// [`direction`]: fn@direction
/// [`z_index`]: fn@zng_wgt::z_index
/// [`LayoutDirection`]: zng_wgt::prelude::LayoutDirection
#[widget($crate::Stack {
    ($children:expr) => {
        children = $children;
    };
    ($direction:ident, $children:expr) => {
        direction = $crate::StackDirection::$direction();
        children = $children;
    };
    ($direction:ident, $spacing:expr, $children:expr) => {
        direction = $crate::StackDirection::$direction();
        spacing = $spacing;
        children = $children;
    };
    ($direction:expr, $children:expr) => {
        direction = $direction;
        children = $children;
    };
    ($direction:expr, $spacing:expr, $children:expr) => {
        direction = $direction;
        spacing = $spacing;
        children = $children;
    };
})]
pub struct Stack(WidgetBase);
impl Stack {
    fn widget_intrinsic(&mut self) {
        self.widget_builder().push_build_action(|wgt| {
            let child = node(
                wgt.capture_ui_node_list_or_empty(property_id!(Self::children)),
                wgt.capture_var_or_default(property_id!(Self::direction)),
                wgt.capture_var_or_default(property_id!(Self::spacing)),
                wgt.capture_var_or_else(property_id!(Self::children_align), || Align::FILL),
            );
            wgt.set_child(child);
        });
    }
}

/// Stack items.
#[property(CHILD, capture, default(ui_vec![]), widget_impl(Stack))]
pub fn children(children: impl UiNodeList) {}

/// Stack direction.
#[property(LAYOUT, capture, widget_impl(Stack))]
pub fn direction(direction: impl IntoVar<StackDirection>) {}

/// Space in-between items.
///
/// The spacing is added along non-zero axis for each item offset after the first, the spacing is
/// scaled by the [direction factor].
///
/// [`direction`]: fn@direction
/// [direction factor]: StackDirection::direction_factor
#[property(LAYOUT, capture, widget_impl(Stack))]
pub fn spacing(spacing: impl IntoVar<Length>) {}

/// Items alignment.
///
/// The items are aligned along axis that don't change, as defined by the [`direction`].
///
/// The default is [`FILL`].
///
/// [`FILL`]: Align::FILL
/// [`direction`]: fn@direction
#[property(LAYOUT, capture, default(Align::FILL), widget_impl(Stack))]
pub fn children_align(align: impl IntoVar<Align>) {}

/// Stack node.
///
/// Can be used directly to stack widgets without declaring a stack widget info. This node is the child
/// of the `Stack!` widget.
pub fn node(
    children: impl UiNodeList,
    direction: impl IntoVar<StackDirection>,
    spacing: impl IntoVar<Length>,
    children_align: impl IntoVar<Align>,
) -> impl UiNode {
    let children = PanelList::new(children).track_info_range(*PANEL_LIST_ID);
    let direction = direction.into_var();
    let spacing = spacing.into_var();
    let children_align = children_align.into_var();

    match_node_list(children, move |c, op| match op {
        UiNodeOp::Init => {
            WIDGET
                .sub_var_layout(&direction)
                .sub_var_layout(&spacing)
                .sub_var_layout(&children_align);
        }
        UiNodeOp::Update { updates } => {
            let mut changed = false;
            c.update_all(updates, &mut changed);

            if changed {
                WIDGET.layout();
            }
        }
        UiNodeOp::Measure { wm, desired_size } => {
            c.delegated();
            *desired_size = measure(wm, c.children(), direction.get(), spacing.get(), children_align.get());
        }
        UiNodeOp::Layout { wl, final_size } => {
            c.delegated();
            *final_size = layout(wl, c.children(), direction.get(), spacing.get(), children_align.get());
        }
        _ => {}
    })
}

/// Create a node that estimates the size of stack panel children.
///
/// The estimation assumes that all items have a size of `child_size`.
pub fn lazy_size(
    children_len: impl IntoVar<usize>,
    direction: impl IntoVar<StackDirection>,
    spacing: impl IntoVar<Length>,
    child_size: impl IntoVar<Size>,
) -> impl UiNode {
    lazy_sample(children_len, direction, spacing, zng_wgt_size_offset::size(NilUiNode, child_size))
}

/// Create a node that estimates the size of stack panel children.
///
/// The estimation assumes that all items have the size of `child_sample`.
pub fn lazy_sample(
    children_len: impl IntoVar<usize>,
    direction: impl IntoVar<StackDirection>,
    spacing: impl IntoVar<Length>,
    child_sample: impl UiNode,
) -> impl UiNode {
    let children_len = children_len.into_var();
    let direction = direction.into_var();
    let spacing = spacing.into_var();

    match_node(child_sample, move |child, op| match op {
        UiNodeOp::Init => {
            WIDGET
                .sub_var_layout(&children_len)
                .sub_var_layout(&direction)
                .sub_var_layout(&spacing);
        }
        op @ UiNodeOp::Measure { .. } | op @ UiNodeOp::Layout { .. } => {
            let mut measure = |wm| {
                let constraints = LAYOUT.constraints();
                if let Some(known) = constraints.fill_or_exact() {
                    child.delegated();
                    return known;
                }

                let len = Px(children_len.get() as i32);
                if len.0 == 0 {
                    child.delegated();
                    return PxSize::zero();
                }

                let child_size = child.measure(wm);

                let direction = direction.get();
                let dv = direction.direction_factor(LayoutDirection::LTR);
                let ds = if dv.x == 0.fct() && dv.y != 0.fct() {
                    // vertical stack
                    let spacing = spacing.layout_y();
                    PxSize::new(child_size.width, (len - Px(1)) * (child_size.height + spacing) + child_size.height)
                } else if dv.x != 0.fct() && dv.y == 0.fct() {
                    // horizontal stack
                    let spacing = spacing.layout_x();
                    PxSize::new((len - Px(1)) * (child_size.width + spacing) + child_size.width, child_size.height)
                } else {
                    // unusual stack
                    let spacing = spacing_from_direction(dv, spacing.get());

                    let mut item_rect = PxRect::from_size(child_size);
                    let mut item_bounds = euclid::Box2D::zero();
                    let mut child_spacing = PxVector::zero();
                    for _ in 0..len.0 {
                        let offset = direction.layout(item_rect, child_size) + child_spacing;
                        item_rect.origin = offset.to_point();
                        let item_box = item_rect.to_box2d();
                        item_bounds.min = item_bounds.min.min(item_box.min);
                        item_bounds.max = item_bounds.max.max(item_box.max);
                        child_spacing = spacing;
                    }

                    item_bounds.size()
                };

                constraints.fill_size_or(ds)
            };

            match op {
                UiNodeOp::Measure { wm, desired_size } => {
                    *desired_size = measure(wm);
                }
                UiNodeOp::Layout { wl, final_size } => {
                    *final_size = measure(&mut wl.to_measure(None));
                }
                _ => unreachable!(),
            }
        }
        _ => {}
    })
}

fn measure(wm: &mut WidgetMeasure, children: &mut PanelList, direction: StackDirection, spacing: Length, children_align: Align) -> PxSize {
    let metrics = LAYOUT.metrics();
    let constraints = metrics.constraints();
    if let Some(known) = constraints.fill_or_exact() {
        return known;
    }

    let child_align = children_align * direction.direction_scale();

    let spacing = layout_spacing(&metrics, &direction, spacing);
    let max_size = child_max_size(wm, children, child_align);

    // layout children, size, raw position + spacing only.
    let mut item_bounds = euclid::Box2D::zero();
    LAYOUT.with_constraints(
        constraints
            .with_fill(child_align.is_fill_x(), child_align.is_fill_y())
            .with_max_size(max_size)
            .with_new_min(Px(0), Px(0)),
        || {
            // parallel measure full widgets first
            children.measure_each(
                wm,
                |_, c, _, wm| {
                    if c.is_widget() {
                        c.measure(wm)
                    } else {
                        PxSize::zero()
                    }
                },
                |_, _| PxSize::zero(),
            );

            let mut item_rect = PxRect::zero();
            let mut child_spacing = PxVector::zero();
            children.for_each(|_, c, _| {
                // already parallel measured widgets, only measure other nodes.
                let size = match c.with_context(WidgetUpdateMode::Ignore, || WIDGET.bounds().measure_outer_size()) {
                    Some(wgt_size) => wgt_size,
                    None => c.measure(wm),
                };
                if size.is_empty() {
                    return; // continue, skip collapsed
                }

                let offset = direction.layout(item_rect, size) + child_spacing;

                item_rect.origin = offset.to_point();
                item_rect.size = size;

                let item_box = item_rect.to_box2d();
                item_bounds.min = item_bounds.min.min(item_box.min);
                item_bounds.max = item_bounds.max.max(item_box.max);
                child_spacing = spacing;
            });
        },
    );

    constraints.fill_size_or(item_bounds.size())
}
fn layout(wl: &mut WidgetLayout, children: &mut PanelList, direction: StackDirection, spacing: Length, children_align: Align) -> PxSize {
    let metrics = LAYOUT.metrics();
    let constraints = metrics.constraints();
    let child_align = children_align * direction.direction_scale();

    let spacing = layout_spacing(&metrics, &direction, spacing);
    let max_size = child_max_size(&mut wl.to_measure(None), children, child_align);

    // layout children, size, raw position + spacing only.
    let mut item_bounds = euclid::Box2D::zero();
    LAYOUT.with_constraints(
        constraints
            .with_fill(child_align.is_fill_x(), child_align.is_fill_y())
            .with_max_size(max_size)
            .with_new_min(Px(0), Px(0)),
        || {
            // parallel layout widgets
            children.layout_each(
                wl,
                |_, c, o, wl| {
                    if c.is_widget() {
                        let (size, define_ref_frame) = wl.with_child(|wl| c.layout(wl));
                        debug_assert!(!define_ref_frame); // is widget, should define own frame.
                        o.define_reference_frame = define_ref_frame;
                        size
                    } else {
                        PxSize::zero()
                    }
                },
                |_, _| PxSize::zero(),
            );

            // layout other nodes and position everything.
            let mut item_rect = PxRect::zero();
            let mut child_spacing = PxVector::zero();
            children.for_each(|_, c, o| {
                let size = match c.with_context(WidgetUpdateMode::Ignore, || WIDGET.bounds().outer_size()) {
                    Some(wgt_size) => wgt_size,
                    None => {
                        let (size, define_ref_frame) = wl.with_child(|wl| c.layout(wl));
                        o.define_reference_frame = define_ref_frame;
                        size
                    }
                };

                if size.is_empty() {
                    o.child_offset = PxVector::zero();
                    o.define_reference_frame = false;
                    return; // continue, skip collapsed
                }

                let offset = direction.layout(item_rect, size) + child_spacing;
                o.child_offset = offset;

                item_rect.origin = offset.to_point();
                item_rect.size = size;

                let item_box = item_rect.to_box2d();
                item_bounds.min = item_bounds.min.min(item_box.min);
                item_bounds.max = item_bounds.max.max(item_box.max);
                child_spacing = spacing;
            });
        },
    );

    // final position, align child inside item_bounds and item_bounds in the panel area.
    let items_size = item_bounds.size();
    let panel_size = constraints.fill_size_or(items_size);
    let children_offset = -item_bounds.min.to_vector() + (panel_size - items_size).to_vector() * children_align.xy(LAYOUT.direction());
    let align_baseline = children_align.is_baseline();
    let child_align = child_align.xy(LAYOUT.direction());

    children.for_each(|_, c, o| {
        if let Some((size, baseline)) = c.with_context(WidgetUpdateMode::Ignore, || {
            let bounds = WIDGET.bounds();
            (bounds.outer_size(), bounds.final_baseline())
        }) {
            let child_offset = (items_size - size).to_vector() * child_align;
            o.child_offset += children_offset + child_offset;

            if align_baseline {
                o.child_offset.y += baseline;
            }
        } else {
            // non-widgets only align with item_bounds
            o.child_offset += children_offset;
        }
    });

    children.commit_data().request_render();

    panel_size
}

/// Spacing to add on each axis.
fn layout_spacing(ctx: &LayoutMetrics, direction: &StackDirection, spacing: Length) -> PxVector {
    let factor = direction.direction_factor(ctx.direction());
    spacing_from_direction(factor, spacing)
}
fn spacing_from_direction(factor: Factor2d, spacing: Length) -> PxVector {
    PxVector::new(spacing.layout_x(), spacing.layout_y()) * factor
}

/// Max size to layout each child with.
fn child_max_size(wm: &mut WidgetMeasure, children: &mut PanelList, child_align: Align) -> PxSize {
    let constraints = LAYOUT.constraints();

    // need measure when children fill, but the panel does not.
    let mut need_measure = false;
    let mut max_size = PxSize::zero();
    let mut measure_constraints = constraints;
    match (constraints.x.fill_or_exact(), constraints.y.fill_or_exact()) {
        (None, None) => {
            need_measure = child_align.is_fill_x() || child_align.is_fill_y();
            if !need_measure {
                max_size = constraints.max_size().unwrap_or_else(|| PxSize::new(Px::MAX, Px::MAX));
            }
        }
        (None, Some(h)) => {
            max_size.height = h;
            need_measure = child_align.is_fill_x();

            if need_measure {
                measure_constraints = constraints.with_fill_x(false);
            } else {
                max_size.width = Px::MAX;
            }
        }
        (Some(w), None) => {
            max_size.width = w;
            need_measure = child_align.is_fill_y();

            if need_measure {
                measure_constraints = constraints.with_fill_y(false);
            } else {
                max_size.height = Px::MAX;
            }
        }
        (Some(w), Some(h)) => max_size = PxSize::new(w, h),
    }

    // find largest child, the others will fill to its size.
    if need_measure {
        let max_items = LAYOUT.with_constraints(measure_constraints.with_new_min(Px(0), Px(0)), || {
            children.measure_each(wm, |_, c, _, wm| c.measure(wm), PxSize::max)
        });

        max_size = constraints.clamp_size(max_size.max(max_items));
    }

    max_size
}

/// Basic z-stack node.
///
/// Creates a node that updates and layouts the `nodes` in the logical order they appear in the list
/// and renders them one on top of the other from back(0) to front(len-1). The layout size is the largest item width and height,
/// the parent constraints are used for the layout of each item.
///
/// This is the most simple *z-stack* implementation possible, it is a building block useful for quickly declaring
/// overlaying effects composed of multiple nodes, it does not do any alignment layout or z-sorting render.
///
/// [`Stack!`]: struct@Stack
pub fn stack_nodes(nodes: impl UiNodeList) -> impl UiNode {
    match_node_list(nodes, |_, _| {})
}

/// Basic z-stack node sized by one of the items.
///
/// Creates a node that updates the `nodes` in the logical order they appear, renders them one on top of the other from back(0)
/// to front(len-1), but layouts the `index` item first and uses its size to get `constraints` for the other items.
///
/// The layout size is the largest item width and height, usually the `index` size.
///
/// If the `index` is out of range the node logs an error and behaves like [`stack_nodes`].
pub fn stack_nodes_layout_by(
    nodes: impl UiNodeList,
    index: impl IntoVar<usize>,
    constraints: impl Fn(PxConstraints2d, usize, PxSize) -> PxConstraints2d + Send + 'static,
) -> impl UiNode {
    #[cfg(feature = "dyn_closure")]
    let constraints: Box<dyn Fn(PxConstraints2d, usize, PxSize) -> PxConstraints2d + Send> = Box::new(constraints);
    stack_nodes_layout_by_impl(nodes, index, constraints)
}

fn stack_nodes_layout_by_impl(
    nodes: impl UiNodeList,
    index: impl IntoVar<usize>,
    constraints: impl Fn(PxConstraints2d, usize, PxSize) -> PxConstraints2d + Send + 'static,
) -> impl UiNode {
    let index = index.into_var();

    match_node_list(nodes, move |children, op| match op {
        UiNodeOp::Init => {
            WIDGET.sub_var_layout(&index);
        }
        UiNodeOp::Measure { wm, desired_size } => {
            let index = index.get();
            let len = children.len();
            *desired_size = if index >= len {
                tracing::error!(
                    "index {} out of range for length {} in `{:?}#stack_nodes_layout_by`",
                    index,
                    len,
                    WIDGET.id()
                );

                children.measure_each(wm, |_, n, wm| n.measure(wm), PxSize::max)
            } else {
                let index_size = children.with_node(index, |n| n.measure(wm));
                let constraints = constraints(LAYOUT.metrics().constraints(), index, index_size);
                LAYOUT.with_constraints(constraints, || {
                    children.measure_each(
                        wm,
                        |i, n, wm| {
                            if i != index {
                                n.measure(wm)
                            } else {
                                index_size
                            }
                        },
                        PxSize::max,
                    )
                })
            };
        }
        UiNodeOp::Layout { wl, final_size } => {
            let index = index.get();
            let len = children.len();
            *final_size = if index >= len {
                tracing::error!(
                    "index {} out of range for length {} in `{:?}#stack_nodes_layout_by`",
                    index,
                    len,
                    WIDGET.id()
                );

                children.layout_each(wl, |_, n, wl| n.layout(wl), PxSize::max)
            } else {
                let index_size = children.with_node(index, |n| n.layout(wl));
                let constraints = constraints(LAYOUT.metrics().constraints(), index, index_size);
                LAYOUT.with_constraints(constraints, || {
                    children.layout_each(
                        wl,
                        |i, n, wl| {
                            if i != index {
                                n.layout(wl)
                            } else {
                                index_size
                            }
                        },
                        PxSize::max,
                    )
                })
            };
        }
        _ => {}
    })
}

static_id! {
    static ref PANEL_LIST_ID: StateId<zng_app::widget::node::PanelListRange>;
}

/// Get the child index in the parent stack.
///
/// The child index is zero-based.
#[property(CONTEXT)]
pub fn get_index(child: impl UiNode, state: impl IntoVar<usize>) -> impl UiNode {
    let state = state.into_var();
    zng_wgt::node::with_index_node(child, *PANEL_LIST_ID, move |id| {
        let _ = state.set(id.unwrap_or(0));
    })
}

/// Get the child index and number of children.
#[property(CONTEXT)]
pub fn get_index_len(child: impl UiNode, state: impl IntoVar<(usize, usize)>) -> impl UiNode {
    let state = state.into_var();
    zng_wgt::node::with_index_len_node(child, *PANEL_LIST_ID, move |id_len| {
        let _ = state.set(id_len.unwrap_or((0, 0)));
    })
}

/// Get the child index, starting from the last child at `0`.
#[property(CONTEXT)]
pub fn get_rev_index(child: impl UiNode, state: impl IntoVar<usize>) -> impl UiNode {
    let state = state.into_var();
    zng_wgt::node::with_rev_index_node(child, *PANEL_LIST_ID, move |id| {
        let _ = state.set(id.unwrap_or(0));
    })
}

/// If the child index is even.
///
/// Child index is zero-based, so the first is even, the next [`is_odd`].
///
/// [`is_odd`]: fn@is_odd
#[property(CONTEXT)]
pub fn is_even(child: impl UiNode, state: impl IntoVar<bool>) -> impl UiNode {
    let state = state.into_var();
    zng_wgt::node::with_index_node(child, *PANEL_LIST_ID, move |id| {
        let _ = state.set(id.map(|i| i % 2 == 0).unwrap_or(false));
    })
}

/// If the child index is odd.
///
/// Child index is zero-based, so the first [`is_even`], the next one is odd.
///
/// [`is_even`]: fn@is_even
#[property(CONTEXT)]
pub fn is_odd(child: impl UiNode, state: impl IntoVar<bool>) -> impl UiNode {
    let state = state.into_var();
    zng_wgt::node::with_index_node(child, *PANEL_LIST_ID, move |id| {
        let _ = state.set(id.map(|i| i % 2 != 0).unwrap_or(false));
    })
}

/// If the child is the first.
#[property(CONTEXT)]
pub fn is_first(child: impl UiNode, state: impl IntoVar<bool>) -> impl UiNode {
    let state = state.into_var();
    zng_wgt::node::with_index_node(child, *PANEL_LIST_ID, move |id| {
        let _ = state.set(id == Some(0));
    })
}

/// If the child is the last.
#[property(CONTEXT)]
pub fn is_last(child: impl UiNode, state: impl IntoVar<bool>) -> impl UiNode {
    let state = state.into_var();
    zng_wgt::node::with_rev_index_node(child, *PANEL_LIST_ID, move |id| {
        let _ = state.set(id == Some(0));
    })
}

/// Extension methods for [`WidgetInfo`] that may represent a [`Stack!`] instance.
///
/// [`Stack!`]: struct@Stack
/// [`WidgetInfo`]: zng_app::widget::info::WidgetInfo
pub trait WidgetInfoStackExt {
    /// Gets the stack children, if this widget is a [`Stack!`] instance.
    ///
    /// [`Stack!`]: struct@Stack
    fn stack_children(&self) -> Option<zng_app::widget::info::iter::Children>;
}
impl WidgetInfoStackExt for zng_app::widget::info::WidgetInfo {
    fn stack_children(&self) -> Option<zng_app::widget::info::iter::Children> {
        zng_app::widget::node::PanelListRange::get(self, *PANEL_LIST_ID)
    }
}