use accesskit::{Node, Role};
use tracing::{Span, trace_span};
use crate::core::{
AccessCtx, ChildrenIds, LayoutCtx, MeasureCtx, NewWidget, NoAction, PaintCtx, PropertiesRef,
RegisterCtx, Widget, WidgetId, WidgetMut, WidgetPod,
};
use crate::imaging::Painter;
use crate::kurbo::{Axis, Point, Size};
use crate::layout::{LenReq, Length};
pub struct Passthrough {
inner: WidgetPod<dyn Widget>,
}
impl Passthrough {
pub fn new(child: NewWidget<impl Widget + ?Sized>) -> Self {
Self {
inner: child.erased().to_pod(),
}
}
}
impl Passthrough {
pub fn inner_id(&self) -> WidgetId {
self.inner.id()
}
}
impl Passthrough {
pub fn set_child(this: &mut WidgetMut<'_, Self>, child: NewWidget<impl Widget + ?Sized>) {
let old = std::mem::replace(&mut this.widget.inner, child.erased().to_pod());
this.ctx.remove_child(old);
}
pub fn child_mut<'t>(this: &'t mut WidgetMut<'_, Self>) -> WidgetMut<'t, dyn Widget> {
this.ctx.get_mut(&mut this.widget.inner)
}
}
impl Widget for Passthrough {
type Action = NoAction;
fn register_children(&mut self, ctx: &mut RegisterCtx<'_>) {
ctx.register_child(&mut self.inner);
}
fn measure(
&mut self,
ctx: &mut MeasureCtx<'_>,
_props: &PropertiesRef<'_>,
axis: Axis,
_len_req: LenReq,
cross_length: Option<Length>,
) -> Length {
ctx.redirect_measurement(&mut self.inner, axis, cross_length)
}
fn layout(&mut self, ctx: &mut LayoutCtx<'_>, _props: &PropertiesRef<'_>, size: Size) {
ctx.run_layout(&mut self.inner, size);
ctx.place_child(&mut self.inner, Point::ORIGIN);
ctx.derive_baselines(&self.inner);
}
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 {
ChildrenIds::from_slice(&[self.inner.id()])
}
fn make_trace_span(&self, id: WidgetId) -> Span {
trace_span!("Passthrough", 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::Label;
#[test]
fn passthrough_replaces_child() {
let widget = Passthrough::new(Label::new("A").prepare())
.prepare()
.with_props(Dimensions::MAX);
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (30, 30));
assert_render_snapshot!(harness, "passthrough_initial_label_A");
harness.edit_root_widget(|mut host| {
let mut child = Passthrough::child_mut(&mut host);
let _ = child.downcast::<Label>();
});
harness.edit_root_widget(|mut host| {
Passthrough::set_child(&mut host, Label::new("B").prepare());
});
assert_render_snapshot!(harness, "passthrough_replaced_label_B");
}
}