Files
craft-libs/crates/ui-contract/tests/it/contract/fixes.rs
T
aiongg bddc593180 Merge storytold next into memo-audit-fix
Memoized views stay the one change mechanism: next's settling-path additions (modifier reads as bind keys, given-edit
and keymap unsettling, settle counters) give way to the tracked inputs that cover them, and request_own_repaint calls
become request_repaint. next's command board, node facts after the node check, the guide drag out of a ruler and the
CommandStates input are taken; the trials next wrote on Lazy::settles run on memoized views. The ruler guide env value
keys a view under the canvas in every pass of a drag. The replay audit's run in the gate takes next's target selection.
2026-11-20 10:26:06 +00:00

363 lines
12 KiB
Rust

//! Rules of the pipeline's steps: the order the hooks run in, sizing passes, `measure_in`, activation, ids, focus
//! on a part that goes away, the body size and the ink and app values a body hands down.
use craft_behavior::Sense;
use craft_ui::contract::{
Common, Component, Container, ContainerProps, Cx, MeasureCx, OverlayUi, PaintUi, PartsCx, Props as _, Role, Show as _, ShowContainer as _, Sizing,
};
use craft_ui::runtime::env::{AppValues, EnvValue};
use craft_ui::style::StyleCx;
use craft_ui::testing::contract::{findings, steps};
use craft_ui::testing::focus::named_id;
use craft_ui::testing::memory::scoped;
use craft_ui::testing::{Frames, is_measuring, trial};
use craft_ui_test_kit::contract::{PlainStyle, Probe, Seen};
use egui::{Rect, Response, UiBuilder, Vec2};
use std::cell::RefCell;
type Log = RefCell<Vec<&'static str>>;
/// A style-affecting app value the body hands to its children.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, EnvValue, craft_ui::contract::MemoProps)]
#[env(style, root = Tone(1))]
struct Tone(u8);
/// A body that logs every hook the pipeline calls and can hand `Tone` to its body.
#[derive(Component)]
#[component(container, overlay)]
struct Hooked<'a> {
#[common]
common: Common,
#[container]
props: ContainerProps,
log: &'a Log,
/// Where the calls of a measuring run go, when the trial tells the runs apart.
measured: Option<(&'a Log, egui::Context)>,
tone: Option<u8>,
}
impl<'a> Hooked<'a> {
fn new(log: &'a Log) -> Self {
Hooked { common: Common::new(), props: ContainerProps::new().sizing(Sizing::Content), log, measured: None, tone: None }
}
fn telling_runs_apart(mut self, measured: &'a Log, ctx: &egui::Context) -> Self {
self.measured = Some((measured, ctx.clone()));
self
}
fn mark(&self, hook: &'static str) {
match &self.measured {
Some((measured, ctx)) if is_measuring(ctx) => measured.borrow_mut().push(hook),
_ => self.log.borrow_mut().push(hook),
}
}
}
impl Component for Hooked<'_> {
const ROLE: Role = Role::GROUP;
type Style = PlainStyle;
type Output = Response;
fn style(_: &StyleCx<'_>, _: HookedStyleKey) -> PlainStyle {
PlainStyle::default()
}
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
self.mark("measure");
Vec2::ZERO
}
fn sense(&self) -> Sense {
Sense::empty()
}
fn parts(&mut self, _: Rect, _: &mut PartsCx<'_, Self>) {
self.mark("parts");
}
fn content_env(&self, _: &Cx<'_, Self>, values: &mut AppValues) {
self.mark("content_env");
if let Some(tone) = self.tone {
values.set(Tone(tone));
}
}
fn update(&mut self, _: &mut Cx<'_, Self>) {
self.mark("update");
}
fn overlay(&mut self, _: &mut OverlayUi<'_>, _: &mut Cx<'_, Self>) {
self.mark("overlay");
}
fn flags(&self) -> craft_ui::style::Flags {
self.mark("flags");
craft_ui::style::Flags::empty()
}
fn activated(&self, _: &Cx<'_, Self>) -> bool {
self.mark("activated");
false
}
fn paint(&mut self, _: &mut PaintUi<'_>, _: &Cx<'_, Self>) {
self.mark("paint");
}
fn paint_over(&mut self, _: &mut PaintUi<'_>, _: &Cx<'_, Self>) {
self.mark("paint_over");
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
self.mark("finish");
cx.response.clone()
}
}
impl Container for Hooked<'_> {}
#[trial]
fn hooks_run_in_pipeline_order_with_the_body_between_paint_and_paint_over() {
let mut frames = Frames::new();
let log: Log = RefCell::new(Vec::new());
let measured: Log = RefCell::new(Vec::new());
frames.frame(vec![], |ui| {
log.borrow_mut().clear();
measured.borrow_mut().clear();
let ctx = ui.ctx().clone();
Hooked::new(&log).telling_runs_apart(&measured, &ctx).show(ui, |ui, _| {
let into = if is_measuring(ui.ctx()) { &measured } else { &log };
into.borrow_mut().push("body");
});
});
assert_eq!(
*log.borrow(),
["measure", "parts", "update", "overlay", "flags", "paint", "content_env", "body", "paint_over", "activated", "finish"],
"the real run"
);
let mut order = ["content_env", "body", "measure"].into_iter();
assert!(!measured.borrow().is_empty(), "the measuring run called the hooks");
assert!(
measured.borrow().iter().all(|call| order.any(|allowed| allowed == *call)),
"a measuring run calls only content_env, body, measure, in this order: {:?}",
measured.borrow()
);
}
/// A sizing pass of the parent `Ui` allocates the size and runs nothing else.
#[trial]
fn a_sizing_pass_registers_nothing_and_its_id_is_the_real_passs() {
let sized_id = {
let mut frames = Frames::new();
let seen = RefCell::new(Seen::default());
let mut id = None;
frames.frame(vec![], |ui| {
id = Some(ui.scope_builder(UiBuilder::new().sizing_pass(), |ui| Probe::new(&seen).show(ui)).inner.id);
});
assert_eq!(seen.borrow().updates, 0, "a sizing pass runs no update");
id
};
let mut frames = Frames::new();
let seen = RefCell::new(Seen::default());
let mut real_id = None;
frames.frame(vec![], |ui| {
real_id = Some(scoped(ui, |ui| Probe::new(&seen).show(ui)).id);
});
assert_eq!(sized_id, real_id, "the Auto ordinal of a sizing pass is the real pass's");
// The id a sizing pass used is free for the real show in the same pass.
let mut frames = Frames::new();
let seen = RefCell::new(Seen::default());
let shared = named_id("shared");
frames.frame(vec![], |ui| {
ui.scope_builder(UiBuilder::new().sizing_pass(), |ui| Probe::new(&seen).id(shared).show(ui));
Probe::new(&seen).id(shared).show(ui);
});
assert!(findings(&frames.ctx).is_empty(), "a sizing pass registers no id: {:?}", findings(&frames.ctx));
}
/// A leaf whose width follows `Tone`.
#[derive(Component)]
struct Chip {
#[common]
common: Common,
}
impl Component for Chip {
const ROLE: Role = Role::None;
type Style = PlainStyle;
type Output = Response;
fn style(cx: &StyleCx<'_>, _: ChipStyleKey) -> PlainStyle {
PlainStyle::min(Vec2::splat(f32::from(cx.env::<Tone>().0) * 10.0))
}
fn sense(&self) -> Sense {
Sense::empty()
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
#[trial]
fn a_style_value_set_in_content_env_changes_a_body_childs_style() {
let mut frames = Frames::new();
let log: Log = RefCell::new(Vec::new());
let (mut outside, mut inside) = (0.0, 0.0);
frames.frame(vec![], |ui| {
outside = Chip { common: Common::new() }.id_salt("outside").show(ui).rect.width();
let mut body = Hooked::new(&log).id_salt("scoped");
body.tone = Some(5);
body.show(ui, |ui, _| inside = Chip { common: Common::new() }.id_salt("inside").show(ui).rect.width());
});
assert!(inside > outside, "the body's child read the body's value: {outside} -> {inside}");
}
/// A fixture pays for pipeline step records only when the caller inspects a region.
#[trial]
fn the_step_log_is_kept_only_for_an_inspected_region() {
let mut fixture = Frames::new();
let seen = RefCell::new(Seen::default());
fixture.frame(Vec::new(), |ui| {
Probe::new(&seen).show(ui);
});
let id = seen.borrow().id.expect("the probe ran");
assert!(steps(&fixture.ctx, id).is_empty(), "an ordinary fixture frame has no step log");
fixture.frame(Vec::new(), |ui| {
craft_ui::runtime::inspect::record(ui, egui::Id::unique("inspect probe"), |ui| Probe::new(&seen).show(ui));
});
assert!(!steps(&fixture.ctx, seen.borrow().id.expect("the inspected probe ran")).is_empty());
let app = Frames::new();
let seen = RefCell::new(Seen::default());
let mut output = app.ctx.run_ui(craft_ui::testing::windows::RawInput::default(), |ui| {
Probe::new(&seen).show(ui);
});
output.textures_delta.clear();
let id = seen.borrow().id.expect("the probe ran");
assert!(steps(&app.ctx, id).is_empty(), "an app frame records no steps");
}
/// A component whose declaration says the pipeline need not run its parts hook.
#[derive(Component)]
struct NoParts<'a> {
#[common]
common: Common,
calls: &'a std::cell::Cell<usize>,
declare: bool,
}
impl Component for NoParts<'_> {
const ROLE: Role = Role::None;
const PARTS: bool = false;
type Style = PlainStyle;
type Output = Response;
fn style(_: &StyleCx<'_>, _: NoPartsStyleKey) -> PlainStyle {
PlainStyle::min(Vec2::splat(20.0))
}
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
self.calls.set(self.calls.get() + 1);
if self.declare {
cx.part(craft_behavior::PartKey::new("unexpected"), rect);
}
}
fn paint(&mut self, _: &mut PaintUi<'_>, _: &Cx<'_, Self>) {}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
#[trial]
fn a_component_declaring_no_parts_skips_the_parts_hook() {
let mut frames = Frames::new();
let calls = std::cell::Cell::new(0);
frames.frame(vec![], |ui| {
NoParts { common: Common::new(), calls: &calls, declare: false }.show(ui);
});
assert_eq!(calls.get(), 0, "the parts hook is skipped on ordinary runs");
}
#[trial]
fn parts_declaration_checks_report_bad_components_and_restore_nested_checks() {
use craft_ui::testing::contract::check_parts_declarations;
let calls = std::cell::Cell::new(0);
let show = || {
Frames::new().frame(vec![], |ui| {
NoParts { common: Common::new(), calls: &calls, declare: true }.show(ui);
});
};
let outer = check_parts_declarations(|| {
show();
let inner = check_parts_declarations(show);
assert!(inner.iter().any(|name| name.contains("NoParts")), "{inner:?}");
show();
});
assert!(outer.len() >= 2 && outer.iter().all(|name| name.contains("NoParts")), "{outer:?}");
let panic = std::panic::catch_unwind(|| check_parts_declarations(|| panic!("guard test")));
assert!(panic.is_err());
let before = calls.get();
show();
assert_eq!(calls.get(), before, "the check is disabled after unwinding");
}
#[derive(Component)]
struct FocusParts {
#[common]
common: Common,
}
impl Component for FocusParts {
const ROLE: Role = Role::None;
type Style = PlainStyle;
type Output = Response;
fn style(_: &StyleCx<'_>, _: FocusPartsStyleKey) -> PlainStyle {
PlainStyle::min(Vec2::splat(20.0))
}
fn sense(&self) -> Sense {
Sense::empty()
}
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
cx.part(craft_behavior::PartKey::new("first"), rect).focusable();
cx.part(craft_behavior::PartKey::new("second"), rect).focusable();
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
#[trial]
fn inspector_places_synthetic_focus_parts_after_each_owner() {
let mut frames = Frames::new();
let mut recorded = None;
let mut ids = Vec::new();
frames.frame(vec![], |ui| {
let (shown, record) = craft_ui::runtime::inspect::record(ui, named_id("focus-region"), |ui| {
["one", "two"].map(|salt| FocusParts { common: Common::new() }.id_salt(salt).show(ui).id)
});
ids = shown.to_vec();
recorded = record;
});
let record = recorded.expect("real pass was recorded");
let mut stops = Vec::new();
for id in ids {
let owner = record.elements.iter().position(|element| element.id == id && element.part.is_none()).unwrap();
let parts = &record.elements[owner + 1..owner + 3];
assert!(parts.iter().all(|part| part.id == id && part.part.is_some() && part.facts.is_none()), "{parts:?}");
stops.extend(parts.iter().map(|part| part.stop.expect("part is a focus stop")));
}
stops.sort_unstable();
assert_eq!(stops, [1, 2, 3, 4]);
}