Old modality: Tour and ViewportWindow block nothing, Preferences is app-modal, a tool window ignores Escape (K17, D10)

The tour card is a popup that blocks and dims nothing and stays on an outside press; Backdrop::ScrimWithHole and the
cover layer's hole go with it. ViewportWindow blocks nothing until app_modal(backdrop). A modeless Dialog without a
footer ignores Escape; a modal one or one with a footer closes on it. PreferencesWindow drops modeless and takes the
shared app-modal path (blocked cursor, refused close).
This commit is contained in:
aiongg
2026-11-12 14:32:41 +00:00
parent e58aabe37e
commit 81c22f3469
13 changed files with 173 additions and 82 deletions
@@ -145,14 +145,10 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U
// A modal's scrim; it takes the presses below the modal while the modal is open.
let cover_id = sub(layer.id, "cover");
let cover = match overlay.rank {
Rank::Modal { backdrop } if backdrop != Backdrop::None => {
let hole = match backdrop {
Backdrop::ScrimWithHole(hole) => Some(hole),
_ => None,
};
Rank::Modal { backdrop: Backdrop::Scrim } => {
let scrim = crate::style::scrim_color(&layer.env.tokens).gamma_multiply(layer.fade);
let through = crate::runtime::sampler::through(ctx, crate::runtime::egui::pass::current_viewport(ctx), layer.id);
areas::show_cover_layer(ctx, areas::CoverLayer { id: cover_id, tier, screen: bounds, scrim, hole, through, absorbs: !layer.exiting });
areas::show_cover_layer(ctx, areas::CoverLayer { id: cover_id, tier, screen: bounds, scrim, through, absorbs: !layer.exiting });
Some(areas::layer_of(tier, cover_id))
}
_ => None,
+12 -29
View File
@@ -225,27 +225,26 @@ pub(crate) fn show_layer(ctx: &Context, spec: &LayerSpec, body: impl FnOnce(&mut
LayerShown { rect: shown.response.rect, layer: shown.response.layer_id }
}
/// What [`show_cover_layer`] shows: the layer's id and tier, the `screen` it covers, its `scrim`, the `hole` left
/// unpainted, the `through` canvas left open, and whether it `absorbs` pointer hits.
/// What [`show_cover_layer`] shows: the layer's id and tier, the `screen` it covers, its `scrim`, the `through` canvas
/// left open, and whether it `absorbs` pointer hits.
pub(crate) struct CoverLayer {
pub id: Id,
pub tier: Tier,
pub screen: Rect,
pub scrim: Color32,
pub hole: Option<Rect>,
pub through: Option<Rect>,
pub absorbs: bool,
}
/// Shows a layer that covers `screen` and paints `scrim` on it, around `hole` when there is one. While `absorbs` it
/// takes every pointer hit on it, so nothing below it is hit, except inside `through`, the canvas a modal leaves open
/// (`runtime::sampler`): that rect is left unpainted and unabsorbed, and the four bands around it absorb. `hole` is
/// left unpainted as well.
/// Shows a layer that covers `screen` and paints `scrim` on it. While `absorbs` it takes every pointer hit on it, so
/// nothing below it is hit, except inside `through`, the canvas a modal leaves open (`runtime::sampler`): that rect is
/// left unpainted and unabsorbed, and the four bands around it paint and absorb.
pub(crate) fn show_cover_layer(ctx: &Context, cover: CoverLayer) {
let CoverLayer { id, tier, screen, scrim, hole, through, absorbs } = cover;
let scrim = Some(scrim);
let clear = through.map(|through| through.intersect(screen)).filter(|through| through.is_positive());
let holes: Vec<Rect> = [clear, hole].into_iter().flatten().map(|hole| hole.intersect(screen)).filter(|hole| hole.is_positive()).collect();
let CoverLayer { id, tier, screen, scrim, through, absorbs } = cover;
let covered: Vec<Rect> = match through.map(|through| through.intersect(screen)).filter(|through| through.is_positive()) {
Some(clear) => bands(screen, clear).into_iter().filter(|band| band.is_positive()).collect(),
None => vec![screen],
};
egui::Area::new(id)
.order(tier.order())
.pivot(egui::Align2::LEFT_TOP)
@@ -254,24 +253,8 @@ pub(crate) fn show_cover_layer(ctx: &Context, cover: CoverLayer) {
.interactable(absorbs)
.sense(Sense::hover())
.show(ctx, |ui| {
if let Some(scrim) = scrim {
let painter = ui.painter();
let mut painted = vec![screen];
for hole in &holes {
painted = painted
.into_iter()
.flat_map(|rect| if rect.intersects(*hole) { bands(rect, hole.intersect(rect)).to_vec() } else { vec![rect] })
.collect();
}
for band in painted.into_iter().filter(|band| band.is_positive()) {
painter.rect_filled(band, 0.0, scrim);
}
}
let absorbed = match clear {
Some(clear) => bands(screen, clear).into_iter().filter(|band| band.is_positive()).collect(),
None => vec![screen],
};
for rect in absorbed {
for rect in covered {
ui.painter().rect_filled(rect, 0.0, scrim);
let absorber = ui.allocate_rect(rect, Sense::click_and_drag());
crate::runtime::egui::widgets::note_widget(ui.ctx(), absorber.id);
crate::runtime::egui::access::hide(ui.ctx(), absorber.id);
@@ -23,8 +23,6 @@ pub enum Backdrop {
None,
/// One scrim over the viewport.
Scrim,
/// A scrim with a hole around a rect (the tour).
ScrimWithHole(Rect),
}
/// An overlay's place in the order. `Rank` is the only place a layer's egui order is chosen.
+14 -2
View File
@@ -16,7 +16,7 @@ use crate::runtime::overlay::{self, Backdrop, CloseReason, Rank};
use crate::runtime::windows::{self, WindowHost};
use crate::sections::{DialogRole, FooterButton};
use crate::style::{ComponentStyle, StyleCx};
use craft_behavior::{Metrics, Sense};
use craft_behavior::{CancelRule, Metrics, Sense};
use craft_host::target::WindowState;
use egui::{Context, Id, Pos2, Rangef, Rect, Response, Ui, ViewportId};
@@ -42,6 +42,8 @@ type SettleFn<'a> = Box<dyn FnMut(&mut BodyCx<'_>, &mut [FooterButton]) + 'a>;
/// - 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.
/// - 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)]
#[component(container)]
pub struct Dialog<'a> {
@@ -124,6 +126,8 @@ impl<'a> Dialog<'a> {
/// dialog has until the user resizes it (`Overlay::size`) and the least it may be resized to (`Overlay::min_size`).
#[must_use]
pub fn overlay(mut self, change: impl FnOnce(Overlay) -> Overlay) -> Self {
let footer = self.props.footer.is_some();
let change = |overlay| escape_rule(change(overlay), footer);
self.props = match std::mem::take(&mut self.props.mount) {
Mount::Layer(overlay) => self.props.mount(Mount::Layer(change(overlay))),
Mount::Viewport { fallback, spec } => self.props.mount(Mount::Viewport { fallback: change(fallback), spec }),
@@ -248,7 +252,7 @@ impl<'a> Dialog<'a> {
let region = self.footer_region();
self.props = self.props.footer(region);
self.footer = Some(Box::new(content));
self
self.overlay(|overlay| overlay)
}
/// The footer stands in a column at the end edge, beside the whole body and at its top, instead of across the
@@ -293,6 +297,14 @@ impl Dialog<'_> {
}
}
/// Escape closes a modal dialog, and a modeless one whose footer answers it; a modeless tool window without a footer
/// ignores it.
fn escape_rule(mut overlay: Overlay, footer: bool) -> Overlay {
let cancel = if overlay.rank.is_modal() || footer { CancelRule::Close } else { CancelRule::Ignore };
overlay.focus = overlay.focus.cancel(cancel);
overlay
}
/// Whether the dialog `id` is the layer that takes the keys: no popup of the dialog and no other modal is open above
/// it. Its modal chrome takes no keys, so the strips never hide the dialog from this test.
fn on_top(ctx: &Context, id: Id) -> bool {
+13 -19
View File
@@ -1,7 +1,7 @@
//! `Tour` (24.4): a guided walk through the interface, one step at a time, a card beside the part it explains.
use super::words::PanelWords;
use crate::contract::overlay::{Anchor, FloatPlace, OverlayFit, Place, ViewportShare};
use crate::contract::overlay::{Anchor, Dismiss, FloatPlace, Outside, OverlayFit, Place, ViewportShare};
use crate::contract::{Bind, Overlay, Pattern, Props, Show as _, ShowContainer as _};
use crate::display::Text;
use crate::layout_components::Stack;
@@ -10,7 +10,6 @@ use crate::popover::Popover;
use crate::runtime::commands::{CommandSet as _, Commands as _};
use crate::runtime::env::{Env, Label};
use crate::runtime::focus::Initial;
use crate::runtime::overlay::{Backdrop, Rank};
use craft_behavior::overlay::{Align, Side};
use craft_behavior::{EditEvent, Mixed};
use craft_theme::variant::Tone;
@@ -21,7 +20,7 @@ use std::sync::Arc;
mod stories;
/// The keys of a tour: Right goes to the next step and Left back (the keymap mirrors them in a right-to-left
/// interface). They belong to the tour that holds the focus and work under the tour's own modal layer.
/// interface). They belong to the tour that holds the focus.
#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui_macros::CommandSet)]
#[command(prefix = "tour", scope = "tour")]
#[non_exhaustive]
@@ -41,8 +40,8 @@ const CARD_SHARE: ViewportShare = ViewportShare::new(0.3, 0.6);
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct TourStep {
/// The part the step points at, in window coordinates. The scrim leaves it clear and the card sits beside it; a
/// step without one shows its card in the middle of the window.
/// The part the step points at, in window coordinates. The card sits beside it; a step without one shows its card
/// in the middle of the window.
pub target: Option<Rect>,
/// The step's heading.
pub title: Label,
@@ -87,7 +86,8 @@ pub struct TourOutput {
}
/// A guided tour of the interface: a card with the step's heading and text, Skip, Back and Next (Done on the last
/// step) and the step count, beside the part the step points at, with the rest of the window dimmed.
/// step) and the step count, beside the part the step points at. The rest of the window stays usable and undimmed:
/// only the card takes presses, and a press outside it leaves the tour running.
///
/// - Show it while the tour runs; the app stops showing it on `Finished` and `Skipped`.
/// - The index binding holds the step; Next and Back change it and report the event. An index past the last step
@@ -172,20 +172,14 @@ impl<'a> Tour<'a> {
}
}
/// The card's layer: modal, with the scrim leaving `target` clear and the card beside it, else a plain scrim and the
/// card in the middle.
/// The card's layer: a popup beside `target`, else in the middle of the window. It blocks nothing and dims nothing; a
/// press outside leaves it open.
fn layer(target: Option<Rect>) -> Overlay {
let mut overlay = Overlay::modal();
let mut overlay = Overlay::popover().dismiss(Dismiss::new().outside(Outside::Keep));
overlay.fit = OverlayFit::ContentCapped(CARD_SHARE);
match target {
Some(target) => {
overlay.rank = Rank::modal(Backdrop::ScrimWithHole(target));
overlay.place = Place::anchored(Anchor::Rect(target), Side::End, Align::Center);
}
None => {
overlay.rank = Rank::modal(Backdrop::Scrim);
overlay.place = Place::Float(FloatPlace::centred());
}
}
overlay.place = match target {
Some(target) => Place::anchored(Anchor::Rect(target), Side::End, Align::Center),
None => Place::Float(FloatPlace::centred()),
};
overlay
}
@@ -1,4 +1,4 @@
//! `PreferencesWindow`: the preferences body in a modeless `Dialog` that opens in its own OS window where windows
//! `PreferencesWindow`: the preferences body in an app-modal `Dialog` that opens in its own OS window where windows
//! exist.
#[cfg(feature = "testing")]
@@ -50,7 +50,9 @@ pub struct PreferencesState {
/// cancels, once the search text, a field's own gesture and a popup have had them.
/// - **Nested dialogs.** While [`PreferencesModel::nested_open`] is true the window takes no input and refuses to
/// close; [`PreferencesModel::nested`] draws the nested dialogs inside the window's own viewport.
/// - **Placement.** The window opens in its own OS window where there are any, else as a modeless dialog layer
/// - **App-modal.** While the window is open the app's other windows take no input, show the blocked cursor and
/// refuse to close, and a press on one raises the window.
/// - **Placement.** The window opens in its own OS window where there are any, else as a modal dialog layer
/// ([`embedded`](PreferencesWindow::embedded) forces the layer). [`remember`](PreferencesWindow::remember) keeps
/// its place and size across runs.
#[must_use = "show the window with `show`"]
@@ -157,7 +159,6 @@ impl<'a> PreferencesWindow<'a> {
});
let mut dialog = Dialog::new(title.clone())
.collection_body()
.modeless()
.resizable(true)
.close_on_enter(can_ok)
.on_pick(|button, cx| {
@@ -1,6 +1,8 @@
//! The rules of the panels family: an inspector keys its controls by the target and shows the empty notice for no
//! target.
mod tour;
use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, Props as _, Show as _};
use craft_ui::patterns::panels::Inspector;
@@ -0,0 +1,28 @@
//! A tour blocks nothing: the window under its card stays usable.
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, Show as _, clicked};
use craft_ui::patterns::panels::{Tour, TourStep};
use craft_ui::testing::{Fixture, trial};
use std::cell::Cell;
use std::rc::Rc;
#[trial]
fn a_press_beside_the_tour_card_reaches_the_window_and_the_tour_stays() {
let presses = Rc::new(Cell::new(0));
let seen = presses.clone();
let mut fixture = Fixture::new(move |ui| {
let behind = Button::new("Behind").show(ui);
if clicked(&behind) {
seen.set(seen.get() + 1);
}
let steps = [TourStep::new("Layers", "Every object is a layer.").target(behind.rect), TourStep::new("Export", "Export it.")];
let mut index = 0_usize;
Tour::new("Welcome tour", &steps, Bind::bound(&mut index)).show(ui);
});
fixture.idle(30);
let behind = fixture.by_label("Behind").expect("the window's button is shown");
fixture.click(&behind).idle(4);
assert_eq!(presses.get(), 1, "the press went to the window under the tour");
assert!(fixture.by_label("Next").is_some(), "the tour's card stays");
}
+23 -15
View File
@@ -6,7 +6,7 @@ mod stories;
use crate::contract::{Bind, BodyCx, NoValue, Outcome, Overlay, Pattern, Props, SaveKey, ShowContainer as _};
use crate::dialog::Dialog;
use crate::runtime::env::Label;
use crate::runtime::overlay::CloseReason;
use crate::runtime::overlay::{Backdrop, CloseReason};
use egui::{Response, Ui};
/// What a window pass reports.
@@ -16,8 +16,8 @@ use egui::{Response, Ui};
pub struct ViewportWindowOutput {
/// The window's response.
pub response: Response,
/// How the window asked to close this pass: its close action, Escape (once a popup in it has had the key) or the
/// OS close button. `None` while it stays open. The window stays until the app stops showing it.
/// How the window asked to close this pass: its close action, the OS close button, or in an app-modal window
/// Escape (once a popup in it has had the key). `None` while it stays open. The window stays until the app stops showing it.
pub close_requested: Option<CloseReason>,
}
@@ -37,16 +37,15 @@ impl Outcome for ViewportWindowOutput {
/// - **Placement.** The window opens in its own OS window where there are any, else as a dialog layer over its
/// parent. [`overlay`](ViewportWindow::overlay) changes that layer, which also gives the OS window its limits and
/// place: `size_limits`, `placed` and `resizable`.
/// - **App-modal.** By default the app's windows ignore input while the window is open, and a press on one raises
/// this window. `app_modal(false)` makes it a tool window that blocks nothing.
/// - **Keys.** Escape asks to close, unless a popup in the window is open.
/// - **App-modal.** By default the window blocks nothing. [`app_modal`](ViewportWindow::app_modal) makes the app's
/// other windows ignore input while it is open, and a press on one raises this window.
/// - **Keys.** Escape asks to close an app-modal window, unless a popup in it is open; a tool window ignores it.
#[must_use = "show the window with `show`"]
#[derive(Pattern, Props)]
pub struct ViewportWindow {
title: Label,
/// Whether the app's other windows ignore input while this one is open.
#[prop]
app_modal: bool,
/// What lies over the app's other windows while this one is open and blocks them; `None` blocks nothing.
modal: Option<Backdrop>,
/// Changes the layer the window has where windows are unavailable, whose limits and place its OS window takes.
overlay: Option<Box<dyn FnOnce(Overlay) -> Overlay>>,
/// Keeps the window's place and size across runs under `key`.
@@ -55,9 +54,17 @@ pub struct ViewportWindow {
}
impl ViewportWindow {
/// An app-modal window titled `title`.
/// A window titled `title` that blocks nothing.
pub fn new(title: impl Into<Label>) -> Self {
ViewportWindow { title: title.into(), app_modal: true, overlay: None, remember: None }
ViewportWindow { title: title.into(), modal: None, overlay: None, remember: None }
}
/// Makes the app's other windows ignore input while this one is open, with `backdrop` over them where the window is
/// a layer (`Backdrop::Scrim` dims them, `Backdrop::None` leaves them as they are).
#[must_use]
pub fn app_modal(mut self, backdrop: Backdrop) -> Self {
self.modal = Some(backdrop);
self
}
/// Changes the layer the window falls back to, which starts as the resizable dialog layer: the smallest and
@@ -73,14 +80,15 @@ impl ViewportWindow {
/// Shows the window for this pass with `body` as its content.
pub fn show(self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>)) -> ViewportWindowOutput {
let ViewportWindow { title, app_modal, overlay, remember } = self;
let ViewportWindow { title, modal, overlay, remember } = self;
let mut dialog = Dialog::new(title).resizable(true);
if let Some(change) = overlay {
dialog = dialog.overlay(change);
}
if !app_modal {
dialog = dialog.modeless();
}
dialog = match modal {
Some(backdrop) => dialog.backdrop(backdrop),
None => dialog.modeless(),
};
dialog = dialog.viewport();
if let Some(key) = remember {
dialog = dialog.remember(key);
@@ -3,6 +3,7 @@
use super::ViewportWindow;
use crate::contract::Show as _;
use crate::display::Text;
use crate::runtime::overlay::Backdrop;
use crate::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
@@ -12,21 +13,21 @@ fn viewport_window(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
if !*open {
return StoryOutput::default();
}
let shown = ViewportWindow::new("Export Log").show(ui, |ui, _| {
let _ = Text::new("The export finished.").show(ui);
let shown = ViewportWindow::new("Tool Window").show(ui, |ui, _| {
let _ = Text::new("Other windows keep taking input.").show(ui);
});
*open = shown.close_requested.is_none();
shown.into()
}
#[story(ViewportWindow, covers = [], drive = Drive::Never)]
fn viewport_window_without_app_modal(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
fn viewport_window_app_modal(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let open = data.value("open", true);
if !*open {
return StoryOutput::default();
}
let shown = ViewportWindow::new("Tool Window").app_modal(false).show(ui, |ui, _| {
let _ = Text::new("Other windows keep taking input.").show(ui);
let shown = ViewportWindow::new("Export Log").app_modal(Backdrop::Scrim).show(ui, |ui, _| {
let _ = Text::new("The export finished.").show(ui);
});
*open = shown.close_requested.is_none();
shown.into()
+1
View File
@@ -1,3 +1,4 @@
//! Dialogs embedded in a region.
mod contained;
mod window;
+67
View File
@@ -0,0 +1,67 @@
//! A viewport window blocks nothing unless it is app-modal, and only an app-modal window closes on Escape.
use craft_ui::buttons::Button;
use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, Props as _, Show as _};
use craft_ui::runtime::overlay::{Backdrop, CloseReason};
use craft_ui::shell::ViewportWindow;
use craft_ui::testing::contract::clicked;
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers};
use std::cell::Cell;
use std::rc::Rc;
/// Presses on the button under the window, and the window's last close request.
#[derive(Default)]
struct Seen {
presses: Cell<u32>,
close: Cell<Option<CloseReason>>,
}
fn rig(modal: Option<Backdrop>) -> (Fixture, Rc<Seen>) {
let seen = Rc::new(Seen::default());
let sink = seen.clone();
let mut fixture = Fixture::new(move |ui| {
if clicked(&Button::new("Under").show(ui)) {
sink.presses.set(sink.presses.get() + 1);
}
let mut window = ViewportWindow::new("Log");
if let Some(backdrop) = modal {
window = window.app_modal(backdrop);
}
let mut on = false;
let shown = window.show(ui, |ui, _| {
Checkbox::new(Bind::bound(&mut on)).label("Wrap").show(ui);
});
if shown.close_requested.is_some() {
sink.close.set(shown.close_requested);
}
});
fixture.idle(30);
(fixture, seen)
}
/// Clicks the button under the window, then focuses the window's check box and presses Escape.
fn press_under_then_escape(fixture: &mut Fixture) {
let under = fixture.by_label("Under").expect("the button under the window is shown");
fixture.click(&under).idle(4);
let wrap = fixture.by_label("Wrap").expect("the window's body is shown");
fixture.click(&wrap).idle(4);
fixture.key(Key::Escape, Modifiers::NONE).idle(4);
}
#[trial]
fn a_tool_window_blocks_nothing_and_ignores_escape() {
let (mut fixture, seen) = rig(None);
press_under_then_escape(&mut fixture);
assert_eq!(seen.presses.get(), 1, "the press reached the window under it");
assert_eq!(seen.close.get(), None, "Escape does not close a tool window");
}
#[trial]
fn an_app_modal_window_blocks_the_window_under_it_and_closes_on_escape() {
let (mut fixture, seen) = rig(Some(Backdrop::None));
press_under_then_escape(&mut fixture);
assert_eq!(seen.presses.get(), 0, "the window under it took no press");
assert!(seen.close.get().is_some(), "Escape asks to close an app-modal window");
}
+1 -1
View File
@@ -17,7 +17,7 @@ One row per name in the author table (Overview) and per `pub` item a component a
| Arena member | A component that joins the innermost `Env.arena` because it is neither an arena root nor a text or editor leaf | `craft_ui::contract` | 8.3 |
| Arena root | A container with `ContainerProps.arena`, or any collection | `craft_ui::contract` | 8.3 |
| `ArenaId` | The id of an arena, carried in `Env.arena` | `craft_ui::runtime::env` | 8.3 |
| `Backdrop` | A modal's scrim (`None`, `Scrim`, `ScrimWithHole`), carried by `Rank::Modal` | `craft_ui::runtime` (layer stack) | 15.2 |
| `Backdrop` | A modal's scrim (`None`, `Scrim`), carried by `Rank::Modal` | `craft_ui::runtime` (layer stack) | 15.2 |
| `Bind<T>` | The one value binding | `craft_ui::contract` | 10.2 |
| `BindMut<T>` | A reborrowed `Bind<T>` that `bind()`, `open()`, `scroll()` and `selection()` return | `craft_ui::contract` | 10.2 |
| Body | The caller's closure that a container shows, its one caller region | — | 16.3 |