dialogs-w1: net change of 3 commits

- dialogs-w1: finished by an agent
- dialogs-w1: finished by an agent
- dialogs-w1: review fixes (review-1)
This commit is contained in:
Martin Ball
2026-11-18 18:18:25 +00:00
parent 4eba91fa62
commit a0b445d944
9 changed files with 502 additions and 25 deletions
+17 -2
View File
@@ -880,6 +880,9 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
let (layout, body) = (&props.layout, &mut *self.body);
// The room a scrolling body's bars take under or beside its content this run: no part of the line.
let mut bars_inset = Vec2::ZERO;
// The body-end hook runs in the body's own column below its layout and scroll region, outside the shared label
// columns, so it lies under the body and above the footer in every footer place: beside an `EndTop` footer
// column too.
let mut run = |parent: &mut Ui, at: Rect, bcx: &mut BodyCx<'_>| -> Option<Vec2> {
let mut body_ui = alloc::child(parent, {
let builder = UiBuilder::new().max_rect(at).layout(child::column_layout(rtl)).scope_id(body_id);
@@ -938,7 +941,9 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
let view_env = body_env.derive_local(|scoped| scoped.lazy = Some(view));
let region_env = Env::install_for(&region_ui, view_env.clone());
layout::run_body_measured(&mut region_ui, &view_env, layout_id, layout, gap, line, |ui| {
shared_labels(ui, id, columns, room.x, self.settle.clone(), &mut labels, |ui| body(ui, bcx))
shared_labels(ui, id, columns, room.x, self.settle.clone(), &mut labels, |ui| {
body(ui, bcx);
})
});
Env::restore(&ctx, region_env);
if lays_out {
@@ -977,11 +982,21 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
// A row that places its block itself asks for its children's width, not the room it spans.
None => {
let (_, natural) = layout::run_body_measured(&mut body_ui, &body_env, layout_id, layout, gap, line, |ui| {
shared_labels(ui, id, columns, room.x, self.settle.clone(), &mut labels, |ui| body(ui, bcx))
shared_labels(ui, id, columns, room.x, self.settle.clone(), &mut labels, |ui| {
body(ui, bcx);
})
});
natural.map(|width| Vec2::new(width, body_ui.min_rect().height()))
}
};
// A scrolling body's region allocates nothing in `body_ui`, so the hook starts below the part it shows.
if scroll.is_some() {
body_ui.allocate_space(Vec2::new(0.0, took.map_or(0.0, |size| size.y)));
}
let before = body_ui.min_rect().height();
comp.body_end(&mut body_ui, bcx);
let ended = body_ui.min_rect().height() - before;
let took = took.map(|size| Vec2::new(size.x, size.y + ended));
Env::restore(&ctx, installed);
let took = took.unwrap_or_else(|| body_ui.min_rect().size());
// A content-sized column of rows takes, in a measuring run, the width they take at its group's widest
+2 -1
View File
@@ -414,7 +414,8 @@ impl FooterRegion {
}
}
/// Where a footer region sits.
/// Where a footer region sits. In every place, `Container::body_end` fills the body's column under its content, so
/// a notice it shows lies under the body and above the footer, or beside a footer in the end region.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FooterPlace {
+110 -3
View File
@@ -11,8 +11,10 @@ use crate::runtime::env::Env;
use crate::runtime::focus::{self, FocusPolicy};
use crate::runtime::layout_memory;
use crate::runtime::memory::{MemoryStage, sub};
use crate::runtime::motion::{self, Driver};
use crate::runtime::overlay::{self, Backdrop, CloseReason, OpenEntry, Rank};
use egui::{Context, Id, Pos2, Rect, Ui};
use craft_behavior::{MotionKind, Playback};
use egui::{Context, Id, Pos2, Rect, Ui, Vec2};
/// What the host reads for one layer.
pub(crate) struct Layer<'a> {
@@ -108,7 +110,8 @@ fn area_id(id: Id) -> Id {
pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut Ui)) -> LayerOut {
// A layer that appears starts with nothing it remembered while shown before, also when it opens again during its
// exit fade or its host never saw it hide: the focus that was inside it does not close it as `focus_left`.
let mut memory = if overlay::appears(ctx, layer.id, layer.exiting) { LayerMemory::default() } else { recall(layer, ctx) };
let appears = overlay::appears(ctx, layer.id, layer.exiting);
let mut memory = if appears { LayerMemory::default() } else { recall(layer, ctx) };
// A right-click on a context opener while its layer is open hangs the layer at the new pointer.
let pointed = layer
.overlay
@@ -144,7 +147,11 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U
Some(size) => Some(egui::vec2(size.x.max(min_width), size.y)),
None => areas::layer_rect(ctx, area).map(|rect| rect.size()),
};
let placed = placement(ctx, layer, size, bounds, anchor);
let mut placed = placement(ctx, layer, size, bounds, anchor);
let nudge = Nudge::of(ctx, layer, appears);
if let Some(nudge) = &nudge {
placed.at += nudge.offset();
}
let tier = overlay::layer_tier(ctx, overlay.rank);
if (sized || layer.size.is_some()) && areas::layer_rect(ctx, area).is_none() {
areas::seed_area(ctx, areas::layer_of(tier, area), placed.at, placed.room);
@@ -177,6 +184,11 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U
let recorded = overlay.opener.as_ref().and_then(|first| focus::stop_rec(ctx, (first.id, None))).map(|rec| rec.stop.key());
owned.map(|rec| rec.stop.key()).or(pressed).or(recorded).or_else(|| focus::focused_stop(ctx))
});
// A modal closes the popups beneath it in the pass it first shows; `appears` is false in a discard pass that repeats
// the frame, so the close is queued once. A popup opened above it later is not touched.
if overlay.rank.is_modal() && appears {
overlay::close_popups_outside(ctx, &[layer.id]);
}
overlay::begin_layer(ctx, layer.id, tier, layer.exiting, placed.side);
let shown = areas::show_layer(ctx, &spec, |ui| {
if let Some(region) = layer.region {
@@ -219,11 +231,106 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U
entry.absorbs = overlay.dismiss.outside == Outside::Absorb;
overlay::record(ctx, entry);
let dismissed = if layer.exiting { None } else { dismissal(ctx, layer, shown.rect, anchor, scope, &mut memory) };
if let Some(nudge) = &nudge {
// `dismissal` above records the press beside the layer (`dismissal.rs`, `note_pressed_outside`), so the nudge
// starts after it and moves the layer from the next pass on.
nudge.start_on_press(ctx, layer);
nudge.flash(ctx, &shown, layer.env);
}
close_family(ctx, layer, layer.exiting || dismissed.is_some(), &mut memory);
remember(layer, ctx, memory);
LayerOut { dismissed }
}
/// The motion slot of a layer's nudge, under the layer's id.
// PLAN: the decision names a `NUDGE_SPEC`; `MotionSpec::new` (`runtime/motion.rs:39`) is a private `const fn` of a file outside this set, so
// the nudge runs on `spec::OPEN_FADE` (a fade, which reduced motion still runs) over the open token's duration.
const NUDGE: &str = "nudge";
/// The swings of a nudge's shake either way, dying away.
const NUDGE_SWINGS: f32 = 3.0;
/// The edge flashes of a nudge under reduced motion.
const NUDGE_FLASHES: f32 = 2.0;
/// A press beside a modal layer that stays open (`Outside::Keep`) nudges it, so the user sees why nothing behind it
/// reacts: a short damped shake, or two accent edge flashes when the motion policy snaps travel. `left` runs from 1 at
/// the press to 0 at rest on the motion clock, in the layer's motion memory, which goes with the layer; a layer that
/// appears starts at rest. With motion off the fade the nudge steps by snaps too, so nothing shows.
struct Nudge {
/// How much of the nudge is left: 1 at the press, 0 at rest.
left: f32,
/// The layer shakes; otherwise its edge flashes.
shakes: bool,
/// The widest swing of the shake: the gap between neighbouring controls.
amplitude: f32,
}
impl Nudge {
/// The nudge of `layer` in this pass, stepped on the pass clock; `None` for a layer that never nudges. A second
/// pass of one frame reads the same clock, so it repeats the first pass's value.
fn of(ctx: &Context, layer: &Layer<'_>, appears: bool) -> Option<Nudge> {
if !layer.overlay.rank.is_modal() || layer.overlay.dismiss.outside != Outside::Keep || layer.exiting {
return None;
}
let policy = layer.env.motion;
let left = Nudge::driven(ctx, layer, |driver| {
if appears {
driver.jump(NUDGE, 0.0_f32);
}
driver.anim(NUDGE, 0.0_f32, motion::spec::OPEN_FADE)
});
let shakes = policy.mode.playback(MotionKind::Travel) == Playback::Run;
Some(Nudge { left, shakes, amplitude: layer.env.tokens.space.gap.item })
}
/// Runs `f` with the motion driver of `layer`'s nudge, in a stage its owner keeps.
fn driven<R>(ctx: &Context, layer: &Layer<'_>, f: impl FnOnce(&Driver<'_>) -> R) -> R {
let stage = MemoryStage::open_owned(ctx, sub(layer.id, NUDGE), layer.owner);
let result = f(&Driver { stage: &stage, base: layer.id, policy: layer.env.motion });
stage.write_back();
result
}
/// How far through the nudge it is, 0 at the press to 1 at rest.
fn through(&self) -> f32 {
1.0 - self.left.clamp(0.0, 1.0)
}
/// The layer's sideways offset: the shake's swing, none at rest and none when the edge flashes instead.
fn offset(&self) -> Vec2 {
if !self.shakes || self.left <= 0.0 {
return Vec2::ZERO;
}
let swing = (self.through() * NUDGE_SWINGS * std::f32::consts::TAU).sin() * self.left;
Vec2::new(self.amplitude * swing, 0.0)
}
/// Starts the nudge when a press landed beside the layer in this pass and none runs; a press while one runs leaves
/// it alone. A later pass of the frame gets no press (`pressed_outside` is per pass), so it starts nothing.
fn start_on_press(&self, ctx: &Context, layer: &Layer<'_>) {
if self.left > 0.0 || !overlay::pressed_outside(ctx, layer.id) {
return;
}
Nudge::driven(ctx, layer, |driver| {
driver.jump(NUDGE, 1.0_f32);
// Aims it at rest from this pass's clock, so it runs and asks for the passes that step it.
driver.anim(NUDGE, 0.0_f32, motion::spec::OPEN_FADE);
});
}
/// Paints the edge flash on the layer's rect while the nudge runs without the shake: on in the first and third
/// quarters, so it flashes twice.
fn flash(&self, ctx: &Context, shown: &areas::LayerShown, env: &Env) {
if self.shakes || self.left <= 0.0 || (self.through() * NUDGE_FLASHES * 2.0).floor() % 2.0 != 0.0 {
return;
}
let stroke = egui::Stroke::new(env.tokens.stroke.medium, crate::style::rgba_color(env.tokens.color.accent.solid));
let radius = egui::CornerRadius::from(env.tokens.shape.radius.window);
ctx.layer_painter(shown.layer).rect_stroke(shown.rect, radius, stroke, egui::StrokeKind::Inside);
}
}
/// The layer-stack side of an OS-window mount: records the window as an entry of its viewport's stack (rank, key
/// class, scope; no egui layer) and decides its dismissal after the body ran. `rect` is the window's inner rect.
pub(crate) fn host_window(ctx: &Context, layer: &Layer<'_>, rect: Rect) -> LayerOut {
+1 -1
View File
@@ -21,7 +21,7 @@ pub enum HeldOk {
/// hands the answer to the app once ([`take`](HeldAnswer::take)), and closes with [`finish`](HeldAnswer::finish) once
/// the app accepted it; a refusal keeps the refused answer beside its reason, so the dialog can show the reason until
/// its values change.
#[derive(Debug)]
#[derive(Clone, Debug, PartialEq)]
pub struct HeldAnswer<T> {
filed: Option<T>,
/// `take` has not handed out `filed` yet.
+15 -5
View File
@@ -212,7 +212,6 @@ impl std::fmt::Debug for ChildDialog {
/// Type-erased [`StackDialog`] the host stores.
trait AnyStackDialog: Send {
fn id(&self) -> DialogId;
#[allow(dead_code)] // P3(dialogs-w1): dg.F31
fn modeless(&self) -> bool;
fn result_type(&self) -> TypeId;
fn key(&self) -> Option<String>;
@@ -224,6 +223,8 @@ trait AnyStackDialog: Send {
fn json_fields(&self) -> Option<Value>;
fn set_json_field(&mut self, ctx: &Context, field: &str, value: Value) -> Result<(), String>;
fn show_erased(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option<Box<dyn Any + Send>>;
/// [`StackDialog::take_child`], unwrapped.
fn take_child_erased(&mut self) -> Option<Box<dyn AnyStackDialog>>;
/// `DialogResult::<D::Result>::Cancel`, boxed, for a dialog closed from outside.
fn cancelled(&self) -> Box<dyn Any + Send>;
/// [`StackDialog::cancelled`].
@@ -282,6 +283,10 @@ impl<D: StackDialog> AnyStackDialog for D {
self.show(ui, stack).map(|result| Box::new(result) as Box<dyn Any + Send>)
}
fn take_child_erased(&mut self) -> Option<Box<dyn AnyStackDialog>> {
self.take_child().map(|ChildDialog(child)| child)
}
fn release(&mut self, ctx: &Context) {
StackDialog::cancelled(self, ctx);
}
@@ -389,8 +394,9 @@ impl fmt::Debug for DialogHost {
impl DialogHost {
/// Whether its open stack holds a dialog that is not modeless; current state, so a dialog opened this pass counts.
/// A queued startup dialog is not shown yet, so it does not count.
pub fn shows_modal(&self) -> bool {
todo!("dg.F3")
self.open.iter().any(|dialog| !dialog.modeless())
}
/// An empty host with no open or queued dialogs.
@@ -462,9 +468,13 @@ impl DialogHost {
let Some(at) = self.position_by_id(id) else { continue };
let stack = &self.stack;
let dialog = &mut self.open[at];
let Some(result) = crate::runtime::overlay::stack_place(&ctx, place, id, || dialog.show_erased(ui, stack)) else {
// The dialog stays open: a child it asks for opens over it and shows from the next pass.
if let Some(ChildDialog(child)) = self.open[at].take_child_erased() {
let shown = crate::runtime::overlay::stack_place(&ctx, place, id, || dialog.show_erased(ui, stack));
// The child is taken after every show, so a request is never left for a later pass; a dialog that just
// finished would close its child with it, so its request is dropped.
let child = dialog.take_child_erased();
let Some(result) = shown else {
if let Some(child) = child {
// The child is not on this run's `ids`, so it shows from the next pass, as any open during the run.
self.open_with_parent(child, Some(id));
}
continue;
+23 -7
View File
@@ -5,9 +5,10 @@ use super::frame::{self, DialogOutput, FOOTER, FooterCx, FooterFn, FooterHooks,
use crate::contract::overlay::{FloatPlace, OverlayFit, Place};
use crate::contract::{
Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, Cx, DragBand, FooterPlace, FooterRegion, HeaderRegion, Mount, Overlay, Pad,
Props as _, Role, SaveKey, ShowContainer as _,
Props as _, Role, SaveKey, Show as _, ShowContainer as _,
};
use crate::edit::outer::{self, OuterEnd};
use crate::notices::{Notice, NoticeLayout};
use crate::runtime::access::Access;
use crate::runtime::env::Label;
use crate::runtime::focus::Initial;
@@ -18,6 +19,7 @@ use crate::sections::{DialogRole, FooterButton};
use crate::style::{ComponentStyle, StyleCx};
use craft_behavior::{CancelRule, Metrics, Sense};
use craft_host::target::WindowState;
use craft_theme::variant::Tone;
use egui::{Align2, Context, Id, Pos2, Rangef, Rect, Response, Ui, ViewportId};
/// The style of a dialog: the surface and padding come from the container.
@@ -34,6 +36,8 @@ type OnPickFn<'a> = Box<dyn FnMut(&FooterButton, &mut BodyCx<'_>) + 'a>;
type SettleFn<'a> = Box<dyn FnMut(&mut BodyCx<'_>, &mut [FooterButton]) + 'a>;
type RefusalFn<'a> = Box<dyn FnMut() -> Option<Label> + 'a>;
/// A dialog on its own layer. It opens in the middle of the window, moves by its title band, scrolls its body when the
/// window is smaller and traps the keyboard focus while it is open.
///
@@ -41,7 +45,9 @@ type SettleFn<'a> = Box<dyn FnMut(&mut BodyCx<'_>, &mut [FooterButton]) + 'a>;
/// session slot that starts open. The close action, Escape and `BodyCx::request_close` write `false`.
/// - Placement and size: saved across runs under [`remember`](Dialog::remember); a resizable dialog also saves the
/// size the user left it at.
/// - A modal dialog blocks input below it in every window; a press outside does nothing.
/// - A modal dialog blocks input below it in every window; a press outside nudges it (a short damped shake, or two
/// accent edge flashes under reduced motion) and changes nothing else.
/// - A refusal ([`refusal`](Dialog::refusal)) shows as a bad-tone notice under the body, above the footer.
/// - Escape closes a modal dialog, and a modeless one with a footer; a modeless tool window without one ignores it.
/// - Focus starts on the body's first text or number field, else on the default button, else nowhere.
#[derive(crate::contract::Component, crate::contract::Props)]
@@ -82,6 +88,8 @@ pub struct Dialog<'a> {
/// The body ran in this pass: the header region marks it.
body_shown: bool,
alert: bool,
/// The refusal's reason, read by the body-end hook in every run that shows it.
refusal: Option<RefusalFn<'a>>,
}
impl<'a> Dialog<'a> {
@@ -118,6 +126,7 @@ impl<'a> Dialog<'a> {
picked: None,
body_shown: false,
alert: false,
refusal: None,
}
.label(title)
}
@@ -185,12 +194,12 @@ impl<'a> Dialog<'a> {
}
/// Shows the label `reason` gives as an inline bad-tone notice in the body-end hook, above the footer: the one
/// display of a held answer's refusal. The closure is called once in that hook, after the body ran; `None` shows no
/// notice.
/// display of a held answer's refusal. The closure is called in that hook in every run that shows it, after the
/// body ran, so a notice never trails an edit by a pass; `None` shows no notice.
#[must_use]
pub fn refusal(self, reason: impl FnOnce() -> Option<Label> + 'a) -> Self {
let _ = reason;
todo!("dg.F1")
pub fn refusal(mut self, reason: impl FnMut() -> Option<Label> + 'a) -> Self {
self.refusal = Some(Box::new(reason));
self
}
/// Saves the placement and size under `key`, so a reopened dialog sits where the user left it.
@@ -477,6 +486,13 @@ impl Container for Dialog<'_> {
self.keep_window_draggable(ui);
}
/// The refusal notice, under the body and above the footer: the reason is read in every run, after the body ran.
fn body_end(&mut self, ui: &mut Ui, _cx: &mut BodyCx<'_>) {
if let Some(reason) = self.refusal.as_mut().and_then(|reason| reason()) {
Notice::new(Tone::Bad, reason).layout(NoticeLayout::Inline).show(ui);
}
}
fn footer(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>) {
frame::footer_in(
ui,
+27
View File
@@ -5,6 +5,8 @@ use super::{BlockingOverlay, Dialog, DialogFrame, DialogHost, StackDialog};
use crate::buttons::Button;
use crate::choice::Checkbox;
use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _, clicked};
use crate::display::Text;
use crate::runtime::env::Label;
use crate::runtime::focus::Initial;
use crate::sections::{DialogRole, FooterButton};
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story};
@@ -170,6 +172,31 @@ fn dialog_modeless(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
shown
}
#[story(Dialog<'static>, covers = [], drive = Drive::Never)]
fn dialog_with_refusal(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let mut checks = *data.value("checks", [true, false]);
let refused = *data.value("refused", true);
let shown: StoryOutput = Dialog::new("Grid options")
.opened(Bind::bound(opener(ui, data, GRID_OPTIONS)))
.buttons([FooterButton::new("OK", DialogRole::Accept), FooterButton::new("Cancel", DialogRole::Cancel)])
.refusal(move || refused.then(|| Label::from("The grid is finer than the document allows.")))
.show(ui, |ui, _| body(ui, &mut checks))
.into();
*data.value("checks", [true, false]) = checks;
shown
}
#[story(Dialog<'static>, covers = [], drive = Drive::Never)]
fn dialog_nudge(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
Dialog::new("Grid options")
.opened(Bind::bound(opener(ui, data, GRID_OPTIONS)))
.buttons([FooterButton::new("OK", DialogRole::Accept), FooterButton::new("Cancel", DialogRole::Cancel)])
.show(ui, |ui, _| {
Text::new("Press beside this dialog: it shakes, or its edge flashes twice with reduced motion.").show(ui);
})
.into()
}
#[story(DialogFrame<'static>, covers = [Default], drive = Drive::Custom(close_box))]
fn dialog_frame(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let mut checks = *data.value("checks", [true, false]);
+306 -5
View File
@@ -1,21 +1,26 @@
//! The dialog host and stack.
use craft_behavior::{Metrics, PartKey, Sense};
use craft_behavior::{Metrics, MotionMode, PartKey, Sense};
use craft_host::target::{Os, WindowChrome};
use craft_quit::{CloseAnswer, CloseScope};
use craft_ui::contract::{Common, Component, Cx, MeasureCx, PartsCx, Props as _, Role, Show as _, ShowContainer as _};
use craft_ui::contract::overlay::{Dismiss, Outside};
use craft_ui::contract::{Bind, Common, Component, Cx, MeasureCx, PartsCx, Props as _, Role, Show as _, ShowContainer as _};
use craft_ui::dialog::stories::hosted;
use craft_ui::dialog::{
Alert, Dialog, DialogHost, DialogId, DialogResult, DialogStack, HostedAlert, PromptKind, StackDialog, StandardPrompt, StartupStage,
Alert, ChildDialog, Dialog, DialogHost, DialogId, DialogResult, DialogStack, HostedAlert, PromptKind, StackDialog, StandardPrompt, StartupStage,
UnsavedChangesDialog, dialog_id,
};
use craft_ui::display::Text;
use craft_ui::popover::Popover;
use craft_ui::runtime::windows::{WindowHit, WindowHost};
use craft_ui::sections::{DialogRole, FooterButton};
use craft_ui::style::{ComponentStyle, StyleCx};
use craft_ui::testing::{Fixture, Frames, Story, StoryData, StoryOutput, trial};
use egui::{Modifiers, Rect, Response, Ui, Vec2, ViewportId, vec2};
use craft_ui::testing::{Fixture, Frames, Story, StoryData, StoryOutput, pointer, trial};
use egui::{Modifiers, Pos2, Rect, Response, Ui, Vec2, ViewportId, vec2};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
/// A dialog with no content: it records whether it was the top of the stack when shown and finishes with
/// `finish` once set.
@@ -95,6 +100,61 @@ fn a_parent_with_an_open_child_refuses_confirm() {
assert_eq!(host.take::<Probe<1>>(), Some(DialogResult::Ok(1)));
}
/// A dialog that asks for a `Probe<3>` child in the show after `ask` is set, and finishes with `finish` once set.
struct Asker {
ask: bool,
child: Option<ChildDialog>,
finish: Option<DialogResult<u32>>,
}
impl StackDialog for Asker {
type Result = u32;
fn id(&self) -> DialogId {
dialog_id("asker")
}
fn show(&mut self, _: &mut Ui, _: &DialogStack) -> Option<DialogResult<u32>> {
if std::mem::take(&mut self.ask) {
self.child = Some(ChildDialog::new(Probe::<3>::new("asked")));
}
self.finish.take()
}
fn take_child(&mut self) -> Option<ChildDialog> {
self.child.take()
}
}
/// A child a dialog asks for in its show opens over it, once, and shows from the next pass; a dialog that finishes in
/// the show that asked takes its request with it.
#[trial]
fn a_child_a_dialog_asks_for_opens_over_it_once() {
let mut frames = Frames::new();
let mut host = DialogHost::new();
let asker = host.open(Asker { ask: false, child: None, finish: None });
run(&mut host, &mut frames);
assert!(!host.is_open::<Probe<3>>(), "no request, no child");
host.get_mut::<Asker>().unwrap().ask = true;
run(&mut host, &mut frames);
assert!(host.is_open::<Probe<3>>(), "the request opens the child in the run of the show that asked");
assert_eq!(host.get::<Probe<3>>().unwrap().shows, 0, "a child opened during the run shows from the next pass");
let parent = host.open_dialogs().into_iter().find(|open| open.id == dialog_id("asked")).and_then(|open| open.parent);
assert_eq!(parent, Some(asker));
run(&mut host, &mut frames);
assert_eq!(host.get::<Probe<3>>().unwrap().shows, 1);
assert_eq!(host.open_dialogs().len(), 2, "the request is taken once");
assert!(host.cancel::<Probe<3>>(&frames.ctx));
let dialog = host.get_mut::<Asker>().unwrap();
dialog.ask = true;
dialog.finish = Some(DialogResult::Cancel);
run(&mut host, &mut frames);
assert!(host.is_empty(), "a dialog that finished does not leave its child open");
}
/// A story of a hosted alert whose title is the story's `title` knob.
fn titled_alert(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let title = *data.value("title", "Could not open");
@@ -321,3 +381,244 @@ fn each_open_of_a_dialog_has_its_own_serial() {
assert_eq!(again, id, "the reopened dialog has the same id");
assert_ne!(host.open_serial(id), Some(first), "the reopened dialog has a serial of its own");
}
/// The title of the hosted modal the nudge and popup trials open.
const NUDGED: &str = "Nudge probe";
/// The body text of that modal.
const NUDGED_BODY: &str = "Press beside this dialog.";
/// A hosted modal with a line of text and OK; while `above` is on, a popover opened from its body shows above it.
struct Nudged {
above: Arc<AtomicBool>,
}
impl Nudged {
fn new() -> Self {
Nudged { above: Arc::new(AtomicBool::new(false)) }
}
}
impl StackDialog for Nudged {
type Result = ();
fn id(&self) -> DialogId {
dialog_id("nudged")
}
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<()>> {
let above = Arc::clone(&self.above);
let shown = Dialog::new(NUDGED).buttons([FooterButton::new("OK", DialogRole::Accept)]).show(ui, |ui, _| {
Text::new(NUDGED_BODY).show(ui);
let mut open = above.load(Ordering::Relaxed);
kept_popover(ui, "Above options", &mut open, ABOVE);
above.store(open, Ordering::Relaxed);
});
shown.output.closed.map(|_| DialogResult::Ok(()))
}
}
/// The text inside the popover opened above the modal.
const ABOVE: &str = "Above the dialog";
/// The text inside the popover open beneath the modal.
const BENEATH: &str = "Beneath the dialog";
/// A popover bound to `open` that no press outside, focus move or Escape closes: only a close the runtime queues does.
fn kept_popover(ui: &mut Ui, label: &'static str, open: &mut bool, text: &'static str) {
Popover::new(label, Bind::bound(open)).dismiss(Dismiss::new().outside(Outside::Keep)).escape(false).show(ui, |ui, _| {
Text::new(text).show(ui);
});
}
/// The rect of the open dialog in the latest frame; `None` while none shows.
fn dialog_rect(fixture: &Fixture) -> Option<Rect> {
fixture.by_role(Role::DIALOG).first().map(|dialog| dialog.rect)
}
/// A pointer move to `at`, a press there and its release, each in a frame of its own; `during` runs after each frame.
fn press_at(fixture: &mut Fixture, at: Pos2, mut during: impl FnMut(&Fixture)) {
for event in [pointer::moved(at), pointer::press(at), pointer::release(at)] {
fixture.frame(vec![event]);
during(fixture);
}
}
/// The stroked rects the latest frame painted, with their strokes.
fn strokes(shapes: &[egui::Shape]) -> Vec<(Rect, egui::Stroke)> {
shapes
.iter()
.filter_map(|shape| match shape {
egui::Shape::Rect(rect) if rect.stroke.width > 0.0 => Some((rect.rect, rect.stroke)),
_ => None,
})
.collect()
}
/// A hosted modal under full motion: a press inside does nothing; a press beside shakes it, also when the press frame
/// runs a second pass; a second press while it shakes does not start it over, so it is at rest by the end of the first
/// shake; and a dialog closed while it shakes opens again at rest. Under reduced motion the press flashes its edge and
/// the dialog never moves.
#[trial]
fn a_press_beside_a_modal_dialog_nudges_it_once_and_it_comes_to_rest() {
let host = Rc::new(RefCell::new(DialogHost::new()));
let rerun = Rc::new(Cell::new(false));
let (shown, again) = (Rc::clone(&host), Rc::clone(&rerun));
let mut fixture = Fixture::new(move |ui| {
shown.borrow_mut().run(ui);
if again.get() && ui.ctx().current_pass_index() == 0 {
ui.ctx().request_discard("the press frame runs twice");
}
});
fixture.motion(MotionMode::Full);
host.borrow_mut().open(Nudged::new());
fixture.settle().idle(12);
let rest = dialog_rect(&fixture).expect("the modal shows");
let beside = Pos2::new(4.0, 4.0);
assert!(!rest.contains(beside), "the press point lies beside the dialog");
// On the dialog's own padding, beside its text and buttons.
let inside = Pos2::new(rest.left() + 2.0, rest.center().y);
let mut moved = false;
press_at(&mut fixture, inside, |fixture| moved |= dialog_rect(fixture) != Some(rest));
for _ in 0..12 {
fixture.frame(Vec::new());
moved |= dialog_rect(&fixture) != Some(rest);
}
assert!(!moved, "a press inside the dialog does not nudge it");
assert!(host.borrow().is_open::<Nudged>(), "the press inside left the dialog open");
// The nudge starts in the press frame, which runs two passes; the press reaches only the first.
fixture.frame(vec![pointer::moved(beside)]);
rerun.set(true);
fixture.frame(vec![pointer::press(beside)]);
rerun.set(false);
assert!(fixture.passes() > 1, "the press frame ran a second pass");
fixture.frame(vec![pointer::release(beside)]);
moved |= dialog_rect(&fixture) != Some(rest);
// Frames two to four after the first press: a second press while the shake runs.
press_at(&mut fixture, beside, |fixture| moved |= dialog_rect(fixture) != Some(rest));
// Frames five to ten: the open motion's duration is nine frames, so the first shake is over by the tenth.
for _ in 0..6 {
fixture.frame(Vec::new());
moved |= dialog_rect(&fixture) != Some(rest);
}
assert!(moved, "a press beside the dialog moves it");
assert_eq!(dialog_rect(&fixture), Some(rest), "the dialog is back at rest when the first nudge ends");
assert!(!fixture.repaint_requested(), "the second press did not start the nudge over");
assert!(host.borrow().is_open::<Nudged>(), "the presses beside left the dialog open");
// A dialog closed in the middle of a nudge opens again as one that never was nudged.
let reopened = |fixture: &mut Fixture, nudge: bool| -> Vec<Option<Rect>> {
if nudge {
press_at(fixture, beside, |_| {});
} else {
fixture.idle(3);
}
assert!(host.borrow_mut().cancel::<Nudged>(fixture.ctx()), "the open dialog cancels");
fixture.frame(Vec::new());
host.borrow_mut().open(Nudged::new());
(0..10).map(|_| dialog_rect(fixture.frame(Vec::new()))).collect()
};
let calm = reopened(&mut fixture, false);
fixture.settle().idle(12);
let after_nudge = reopened(&mut fixture, true);
assert_eq!(after_nudge, calm, "a reopened dialog does not carry the nudge it closed in");
// Reduced motion: two edge flashes over the dialog, which stays where it is.
let host = Rc::new(RefCell::new(DialogHost::new()));
let shown = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
fixture.motion(MotionMode::Reduced);
host.borrow_mut().open(Nudged::new());
fixture.settle().idle(12);
let rest = dialog_rect(&fixture).expect("the modal shows");
let calm = strokes(&fixture.frame_shapes());
let mut moved = false;
press_at(&mut fixture, beside, |fixture| moved |= dialog_rect(fixture) != Some(rest));
let mut flashed = false;
for _ in 0..10 {
let painted = strokes(&fixture.frame_shapes());
flashed |= painted.iter().any(|stroke| !calm.contains(stroke) && stroke.0.contains(rest.center()));
moved |= dialog_rect(&fixture) != Some(rest);
}
assert!(flashed, "under reduced motion a press beside flashes the dialog's edge");
assert!(!moved, "under reduced motion the dialog does not move");
fixture.idle(4);
let after = strokes(&fixture.frame_shapes());
assert!(after.iter().all(|stroke| calm.contains(stroke)), "the flash is over once the nudge ends");
}
/// A popup open beneath a modal closes in the pass the modal first shows; a popup opened above the modal afterwards
/// stays open.
#[trial]
fn a_new_modal_closes_the_popups_beneath_it() {
let host = Rc::new(RefCell::new(DialogHost::new()));
let beneath = Rc::new(Cell::new(true));
let (shown, below) = (Rc::clone(&host), Rc::clone(&beneath));
let mut fixture = Fixture::new(move |ui| {
let mut open = below.get();
kept_popover(ui, "Beneath options", &mut open, BENEATH);
below.set(open);
shown.borrow_mut().run(ui);
});
fixture.settle();
assert!(beneath.get() && fixture.by_label(BENEATH).is_some(), "the popup beneath is open before the modal");
let dialog = Nudged::new();
let above = Arc::clone(&dialog.above);
host.borrow_mut().open(dialog);
// The modal's first pass queues the close; the popup's owner takes it in the pass after.
fixture.frame(Vec::new());
assert!(fixture.by_label(NUDGED_BODY).is_some(), "the modal shows in its first pass");
fixture.idle(2);
assert!(!beneath.get(), "the popup beneath the new modal closed");
fixture.settle();
assert!(fixture.by_label(BENEATH).is_none(), "the closed popup is gone from the screen");
above.store(true, Ordering::Relaxed);
fixture.settle().idle(6);
assert!(above.load(Ordering::Relaxed), "a popup opened above the shown modal stays open");
assert!(fixture.by_label(ABOVE).is_some(), "the popup above the modal shows");
}
/// A dialog whose modality the test sets, as current state.
struct Tool {
modeless: bool,
}
impl StackDialog for Tool {
type Result = ();
fn id(&self) -> DialogId {
dialog_id("tool")
}
fn modeless(&self) -> bool {
self.modeless
}
fn show(&mut self, _: &mut Ui, _: &DialogStack) -> Option<DialogResult<()>> {
None
}
}
/// `shows_modal` reads the open dialogs' modality as it is now: an empty host shows none; a modeless dialog alone is
/// not modal; a modal opened in this pass counts at once, with no pass run; a startup modal still queued does not;
/// closing the modal returns it to false; a dialog that turns modal while open counts.
#[trial]
fn shows_modal_follows_the_open_dialogs_modality() {
let frames = Frames::new();
let mut host = DialogHost::new();
assert!(!host.shows_modal(), "an empty host shows no modal");
host.open(Tool { modeless: true });
assert!(!host.shows_modal(), "a modeless dialog alone is not modal");
host.enqueue(StartupStage::Warning, Probe::<3>::new("queued"));
assert!(!host.shows_modal(), "a startup modal still in the queue is not shown");
host.open(Probe::<1>::new("modal"));
assert!(host.shows_modal(), "a modal opened this pass counts before any pass runs");
assert!(host.cancel::<Probe<1>>(&frames.ctx));
assert!(!host.shows_modal(), "with the modal closed only the modeless dialog is open");
host.get_mut::<Tool>().expect("the tool is open").modeless = false;
assert!(host.shows_modal(), "the modality is the dialog's current state");
}
+1 -1
View File
@@ -308,7 +308,7 @@ note = "Removed: the dialog centres in the window or opens at `first_place`."
[[setter]]
type = "Dialog"
old = "first_place(|ctx| Option<Vec2>)"
new = "first_place(Pos2)"
new = "first_place(Pos2, Align2)"
note = "A screen position, not an offset from the window's corner."
[[setter]]