use std::any::TypeId;
use accesskit::{Node, Role};
use include_doc_path::include_doc_path;
use tracing::{Span, trace_span};
use crate::core::{
AccessCtx, ChildrenIds, CollectionWidget, LayoutCtx, MeasureCtx, NewWidget, NoAction, PaintCtx,
PropertiesRef, RegisterCtx, UpdateCtx, Widget, WidgetId, WidgetMut, WidgetPod,
};
use crate::imaging::Painter;
use crate::kurbo::{Axis, Point, Size};
use crate::layout::{LayoutSize, LenReq, Length, SizeDef};
#[doc = concat!(
",
")",
)]
#[derive(Default)]
pub struct IndexedStack {
children: Vec<WidgetPod<dyn Widget>>,
active_child: usize,
}
impl IndexedStack {
pub fn new() -> Self {
Self::default()
}
pub fn with(mut self, child: NewWidget<impl Widget + ?Sized>) -> Self {
self.children.push(child.erased().to_pod());
self
}
pub fn with_active_child(mut self, idx: usize) -> Self {
if self.children.is_empty() {
assert!(
idx == 0,
"Called set_active on empty IndexedStack with non-zero index {idx}"
);
} else {
assert!(
idx < self.children.len(),
"Called set_active with invalid index {idx}"
);
}
self.active_child = idx;
self
}
}
impl IndexedStack {
pub fn active_child(&self) -> usize {
self.active_child
}
}
impl IndexedStack {
pub fn set_active_child(this: &mut WidgetMut<'_, Self>, idx: usize) {
if this.widget.children.is_empty() {
assert!(
idx == 0,
"Called set_active_child on empty IndexedStack with non-zero index {idx}"
);
} else {
assert!(
idx < this.widget.children.len(),
"Called set_active_child with invalid index {idx}"
);
}
this.widget.active_child = idx;
this.ctx.request_layout();
}
}
impl CollectionWidget<()> for IndexedStack {
fn len(&self) -> usize {
self.children.len()
}
fn is_empty(&self) -> bool {
self.children.is_empty()
}
fn get_mut<'t>(this: &'t mut WidgetMut<'_, Self>, idx: usize) -> WidgetMut<'t, dyn Widget> {
let child = &mut this.widget.children[idx];
this.ctx.get_mut(child)
}
fn add(
this: &mut WidgetMut<'_, Self>,
child: NewWidget<impl Widget + ?Sized>,
_params: impl Into<()>,
) {
this.widget.children.push(child.erased().to_pod());
this.ctx.children_changed();
}
fn insert(
this: &mut WidgetMut<'_, Self>,
idx: usize,
child: NewWidget<impl Widget + ?Sized>,
_params: impl Into<()>,
) {
this.widget.children.insert(idx, child.erased().to_pod());
if this.widget.active_child >= idx {
this.widget.active_child += 1;
}
this.ctx.children_changed();
}
fn set(
this: &mut WidgetMut<'_, Self>,
idx: usize,
child: NewWidget<impl Widget + ?Sized>,
_params: impl Into<()>,
) {
let old_child = std::mem::replace(&mut this.widget.children[idx], child.erased().to_pod());
this.ctx.remove_child(old_child);
}
fn set_params(_this: &mut WidgetMut<'_, Self>, _idx: usize, _params: impl Into<()>) {}
fn swap(this: &mut WidgetMut<'_, Self>, a: usize, b: usize) {
this.widget.children.swap(a, b);
this.ctx.children_changed();
}
fn remove(this: &mut WidgetMut<'_, Self>, idx: usize) {
let child = this.widget.children.remove(idx);
if idx == this.widget.active_child {
this.widget.active_child = 0;
} else if this.widget.active_child > idx {
this.widget.active_child -= 1;
}
this.ctx.remove_child(child);
}
fn clear(this: &mut WidgetMut<'_, Self>) {
for child in this.widget.children.drain(..) {
this.ctx.remove_child(child);
}
this.widget.active_child = 0; }
}
impl Widget for IndexedStack {
type Action = NoAction;
fn register_children(&mut self, ctx: &mut RegisterCtx<'_>) {
for child in self.children.iter_mut() {
ctx.register_child(child);
}
}
fn property_changed(&mut self, _ctx: &mut UpdateCtx<'_>, _property_type: TypeId) {}
fn measure(
&mut self,
ctx: &mut MeasureCtx<'_>,
_props: &PropertiesRef<'_>,
axis: Axis,
len_req: LenReq,
cross_length: Option<Length>,
) -> Length {
if !self.children.is_empty() {
let auto_length = len_req.into();
let context_size = LayoutSize::maybe(axis.cross(), cross_length);
ctx.compute_length(
&mut self.children[self.active_child],
auto_length,
context_size,
axis,
cross_length,
)
} else {
Length::ZERO
}
}
fn layout(&mut self, ctx: &mut LayoutCtx<'_>, _props: &PropertiesRef<'_>, size: Size) {
if self.children.is_empty() {
return;
}
for (idx, child) in self.children.iter_mut().enumerate() {
ctx.set_stashed(child, idx != self.active_child);
}
let child_size = ctx.compute_size(
&mut self.children[self.active_child],
SizeDef::fit(size),
size.into(),
);
ctx.run_layout(&mut self.children[self.active_child], child_size);
let child_origin = Point::ORIGIN;
ctx.place_child(&mut self.children[self.active_child], child_origin);
ctx.derive_baselines(&self.children[self.active_child]);
}
fn paint(
&mut self,
_ctx: &mut PaintCtx<'_>,
_props: &PropertiesRef<'_>,
_painter: &mut Painter<'_>,
) {
}
fn accessibility_role(&self) -> Role {
Role::GenericContainer
}
fn accessibility(
&mut self,
_ctx: &mut AccessCtx<'_>,
_props: &PropertiesRef<'_>,
_node: &mut Node,
) {
}
fn children_ids(&self) -> ChildrenIds {
self.children.iter().map(WidgetPod::id).collect()
}
fn make_trace_span(&self, id: WidgetId) -> Span {
trace_span!("IndexedStack", id = id.trace())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::properties::Dimensions;
use crate::testing::{TestHarness, assert_render_snapshot};
use crate::theme::test_property_set;
use crate::widgets::Button;
#[test]
fn test_indexed_stack_basics() {
let widget = IndexedStack::new().prepare();
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (50, 50));
assert_render_snapshot!(harness, "indexed_stack_empty");
harness.edit_root_widget(|mut stack| {
IndexedStack::add(
&mut stack,
Button::with_text("A")
.prepare()
.with_props(Dimensions::STRETCH),
(),
);
});
assert_render_snapshot!(harness, "indexed_stack_single");
harness.edit_root_widget(|mut stack| {
IndexedStack::add(
&mut stack,
Button::with_text("B")
.prepare()
.with_props(Dimensions::STRETCH),
(),
);
IndexedStack::add(
&mut stack,
Button::with_text("C")
.prepare()
.with_props(Dimensions::STRETCH),
(),
);
IndexedStack::add(
&mut stack,
Button::with_text("D")
.prepare()
.with_props(Dimensions::STRETCH),
(),
);
});
assert_render_snapshot!(harness, "indexed_stack_single");
harness.edit_root_widget(|mut stack| {
IndexedStack::set_active_child(&mut stack, 2);
});
assert_render_snapshot!(harness, "indexed_stack_many_2");
}
#[test]
fn test_widget_removal_and_modification() {
let widget = IndexedStack::new()
.with(
Button::with_text("A")
.prepare()
.with_props(Dimensions::STRETCH),
)
.with(
Button::with_text("B")
.prepare()
.with_props(Dimensions::STRETCH),
)
.with(
Button::with_text("C")
.prepare()
.with_props(Dimensions::STRETCH),
)
.with_active_child(1)
.prepare();
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (50, 50));
assert_render_snapshot!(harness, "indexed_stack_initial_builder");
harness.edit_root_widget(|mut stack| {
IndexedStack::remove(&mut stack, 0);
});
assert_render_snapshot!(harness, "indexed_stack_initial_builder");
harness.edit_root_widget(|mut stack| {
IndexedStack::remove(&mut stack, 0);
});
assert_render_snapshot!(harness, "indexed_stack_builder_removed_widget");
harness.edit_root_widget(|mut stack| {
IndexedStack::add(
&mut stack,
Button::with_text("D")
.prepare()
.with_props(Dimensions::STRETCH),
(),
);
});
assert_render_snapshot!(harness, "indexed_stack_builder_removed_widget");
harness.edit_root_widget(|mut stack| {
IndexedStack::set_active_child(&mut stack, 1);
});
assert_render_snapshot!(harness, "indexed_stack_builder_new_widget");
harness.edit_root_widget(|mut stack| {
IndexedStack::insert(
&mut stack,
0,
Button::with_text("A")
.prepare()
.with_props(Dimensions::STRETCH),
(),
);
IndexedStack::insert(
&mut stack,
1,
Button::with_text("B")
.prepare()
.with_props(Dimensions::STRETCH),
(),
);
});
assert_render_snapshot!(harness, "indexed_stack_builder_new_widget");
harness.edit_root_widget(|mut stack| {
IndexedStack::set_active_child(&mut stack, 1);
});
assert_render_snapshot!(harness, "indexed_stack_initial_builder");
harness.edit_root_widget(|mut stack| {
IndexedStack::set(
&mut stack,
1,
Button::with_text("D")
.prepare()
.with_props(Dimensions::STRETCH),
(),
);
});
assert_render_snapshot!(harness, "indexed_stack_builder_new_widget");
}
}