Window frame with page list and the confirm dialog on the UI kit

This commit is contained in:
Nathan Dane
2026-10-20 13:09:34 +02:00
parent f2eaead594
commit 57aad71bbe
33 changed files with 985 additions and 212 deletions
@@ -57,6 +57,11 @@ def ui_icon_names(source):
if icon: names.add(icon.group(1))
for table in re.finditer(r'for\s*\(i,\s*\(label,\s*icon,\s*tip\)\)\s*in\s*\[(.*?)\]\s*\.iter\(', source, re.S):
names.update(re.findall(r'\("[^"]*",\s*"([a-z][a-z0-9_]*)",\s*"[^"]*"\)', table.group(1)))
# System-window wrappers and declarative page lists own their icon arguments.
for call in re.finditer(r'\b(?:Window|Confirm)::new\([^;]*?,\s*"([a-z][a-z0-9_]*)"\s*,', source, re.S):
names.add(call.group(1))
for page in re.finditer(r'\bWindowPage\s*\{[^}]*?\bicon:\s*"([a-z][a-z0-9_]*)"', source, re.S):
names.add(page.group(1))
return names
def requested_icons():
+1 -1
View File
@@ -291,7 +291,7 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) {
let mut open = true;
let mut add = false;
let mut test = false;
let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_ai_add"), "settings", tr("ui.ai_add_agent_title"))
let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_ai_add"), "settings", tr("ui.ai_add_agent_title"))
.cards(2.0)
.fields()
.actions(tr("ui.ai_add"), "Cancel", None)
+1 -1
View File
@@ -20,7 +20,7 @@ pub(crate) fn panel(app: &mut SolveApp, ctx: &egui::Context) {
let at = panel_pos(app);
let (calibrate, name) = (m.calibrate, c.id);
let (ok, cancel) = if calibrate { (crate::i18n::tr_label("Calibrate"), crate::i18n::tr("ui.cancel")) } else { ("", crate::i18n::tr("ui.close")) };
let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_canvas_panel"), "canvas", &title)
let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_canvas_panel"), "canvas", &title)
.placed(egui::Align2::LEFT_TOP, at)
.fields()
.actions(ok, cancel, None)
+2 -2
View File
@@ -41,7 +41,7 @@ pub(crate) fn occurrence_panel(app: &mut SolveApp, ui: &mut egui::Ui) {
let title = crate::i18n::format("browser.move_title", &[("name", &name)]);
let at = panel_pos(app);
let (units, decimals) = (app.session.doc.units.clone(), app.preferences.length_decimals);
let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_occ_move"), "move", &title)
let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_occ_move"), "move", &title)
.placed(egui::Align2::LEFT_TOP, at)
.fields()
.cards(2.0)
@@ -97,7 +97,7 @@ pub(crate) fn capture_prompt(app: &mut SolveApp, ctx: &egui::Context) {
return;
}
let n = app.session.pending_moves.len();
let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_capture_prompt"), "capture", crate::i18n::tr_label("Capture Position"))
let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_capture_prompt"), "capture", crate::i18n::tr_label("Capture Position"))
.anchor(egui::Align2::CENTER_CENTER, egui::vec2(0.0, -80.0))
.actions("Capture Position", "Cancel", Some("Revert"))
.show(ctx, true, |ui| {
+1 -1
View File
@@ -67,7 +67,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
}
let mut report: Option<String> = None;
let mut delete: Option<Option<String>> = None;
let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_crash_reports"), "bug_report", crate::i18n::tr_label("Crash Reports"))
let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_crash_reports"), "bug_report", crate::i18n::tr_label("Crash Reports"))
.cards(2.0)
.actions("", crate::i18n::tr("ui.close"), None)
.show(ctx, true, |ui| {
+2 -3
View File
@@ -2,7 +2,6 @@
//! the viewport or the browser goes in one undoable step through `selection.delete`. When it
//! takes other features with it or makes some fail, a confirmation lists them first.
use egui::vec2;
use serde_json::{Value, json};
use crate::SolveApp;
@@ -121,8 +120,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
};
let (deleted, fails) = (list("deleted"), list("would_fail"));
let shared = shared_occurrences(app, &p.params);
let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_delete_confirm"), "delete", crate::i18n::tr_label("Delete"))
.anchor(egui::Align2::CENTER_CENTER, vec2(0.0, -60.0))
let (closed, action) = ui_kit::Confirm::new(egui::Id::new("sc_delete_confirm"), "delete", crate::i18n::tr_label("Delete"))
.tone(ui_kit::Tone::Danger)
.actions("Delete", "Cancel", None)
.show(ctx, true, |ui| {
if shared {
+3 -3
View File
@@ -5,7 +5,7 @@
//! Document Settings, the root component's menu and `ui.start` of `document.metadata` or
//! `document.metadata.set` open it. [`show_object`] draws the Properties card (mass, volume, area,
//! centre of mass, bounding box, counts) of the body or component a menu asked about; both are
//! `ui_kit::Prompt` cards.
//! `ui_kit::Window` cards.
use serde_json::{Map, Value};
use solidcraft_engine::doc::metadata::{DESCRIPTION, WELL_KNOWN};
@@ -90,7 +90,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
let Some(mut d) = app.design_properties.take() else { return };
let metadata = app.session.doc.metadata.clone();
let title = crate::i18n::tr_label("Design Properties");
let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_design_properties"), "settings", title).fields().show(ctx, true, |ui| {
let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_design_properties"), "settings", title).fields().show(ctx, true, |ui| {
for (i, key) in WELL_KNOWN.iter().enumerate() {
let label = label(key);
let Some(field) = d.fields.get_mut(i) else { continue };
@@ -158,7 +158,7 @@ pub fn show_object(app: &mut SolveApp, ctx: &egui::Context) {
}
rows.push(("Faces / edges / vertices", format!("{} / {} / {}", total["faces"], total["edges"], total["vertices"])));
let heading = crate::i18n::format("properties.title", &[("name", &title)]);
let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_props"), "settings", &heading).actions("", "Close", None).show(ctx, true, |ui| {
let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_props"), "settings", &heading).actions("", "Close", None).show(ctx, true, |ui| {
for (label, value) in &rows {
ui_kit::row(ui, crate::i18n::tr_label(label), |ui| ui_kit::text(ui, value, ui_kit::Text::Cell));
}
+84 -59
View File
@@ -2252,67 +2252,92 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
let window = panel.window();
let repeatable =
matches!(&d.kind, Kind::SketchModify(k) if crate::sketch_modify_ui::repeatable(k)) && d.editing.is_none() && !d.extra.contains_key("pattern");
let response = window.frame(frame).open(&mut keep).show(ctx, |ui| {
let spec = dense::command(&d.kind).and_then(solidcraft_engine::find_command);
let icon = spec.as_ref().map_or("", |s| s.icon);
let label = spec.as_ref().map_or(heading.as_str(), |s| tr(s.label));
let label = if d.editing.is_some() { heading.as_str() } else { label };
let heading =
crate::ui_kit::FeatureOptions { icon, title: label, drag_key: title(&d.kind), moved, docked, apply_label: repeatable.then_some("Apply") };
let applying = app.applying.is_some();
let mut collapsed = d.collapsed;
let manager = matches!(
d.kind,
Kind::Material { .. }
| Kind::Appearance(_)
| Kind::Motion(crate::dialogs_motion::Mo::Configurations { .. })
| Kind::Sheet(crate::dialogs_sheet::Sm::Rules { .. })
| Kind::Plastic(crate::dialogs_plastic::Pl::Rules { .. })
);
// A study/configuration owns Enter for its cells, including when folded.
let cell_enter = matches!(&d.kind, Kind::Motion(k) if k.wide());
if cell_enter && collapsed {
ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
}
let body = |ui: &mut egui::Ui| {
enter |= dense::rows(app, ctx, &mut d, ui);
if cell_enter {
ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
}
let text = app.applying.as_ref().map(|job| {
let seconds = ((crate::now_ms() - job.started) / 1000.0).floor().max(0.0);
crate::i18n::format("dialog.computing", &[("seconds", &format!("{seconds:.0}"))])
if let Kind::ConfirmDelete { with, fail, .. } = &d.kind {
let detail = with.join(" · ");
let (closed, action) = crate::ui_kit::Confirm::new(egui::Id::new(("sc_dialog", title(&d.kind))), "delete", &heading)
.tone(crate::ui_kit::Tone::Danger)
.actions("Delete", "Cancel", None)
.detail(&detail)
.show(ctx, true, |ui| {
if !with.is_empty() {
crate::ui_kit::text(ui, tr("Also deletes"), crate::ui_kit::Text::Report("also_deletes", false));
}
if !fail.is_empty() {
crate::ui_kit::text(ui, &format!("{}: {}", tr("Will fail"), fail.join(", ")), crate::ui_kit::Text::Report("will_fail", true));
}
});
crate::ui_kit::ComputeStatus { text, busy: app.applying.is_some() || app.preview.busy, applying: app.applying.is_some() }
};
let (closed, action) = if manager {
panel.feature_collapsible(ui, heading, applying, valid, &mut collapsed, body)
} else {
panel.feature(ui, heading, applying, valid, body)
};
d.reset_scroll = false;
d.collapsed = collapsed;
cancel |= closed;
if app.issue_report.draft.is_none() {
match action {
crate::ui_kit::Action::Ok => {
ok = true;
apply_again = false;
}
crate::ui_kit::Action::Cancel => {
if !app.esc_handled || !ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
cancel = true;
}
}
crate::ui_kit::Action::Apply => {
ok = true;
apply_again = true;
}
crate::ui_kit::Action::None => {}
ok = action == crate::ui_kit::Action::Ok;
cancel = closed || action == crate::ui_kit::Action::Cancel;
app.viewport.dialog_rect = crate::scenario::rect_of("dialog:window");
} else {
let response = window.frame(frame).open(&mut keep).show(ctx, |ui| {
let spec = dense::command(&d.kind).and_then(solidcraft_engine::find_command);
let icon = spec.as_ref().map_or("", |s| s.icon);
let label = spec.as_ref().map_or(heading.as_str(), |s| tr(s.label));
let label = if d.editing.is_some() { heading.as_str() } else { label };
let heading = crate::ui_kit::FeatureOptions {
icon,
title: label,
drag_key: title(&d.kind),
moved,
docked,
apply_label: repeatable.then_some("Apply"),
};
let applying = app.applying.is_some();
let mut collapsed = d.collapsed;
let manager = matches!(
d.kind,
Kind::Material { .. }
| Kind::Appearance(_)
| Kind::Motion(crate::dialogs_motion::Mo::Configurations { .. })
| Kind::Sheet(crate::dialogs_sheet::Sm::Rules { .. })
| Kind::Plastic(crate::dialogs_plastic::Pl::Rules { .. })
);
// A study/configuration owns Enter for its cells, including when folded.
let cell_enter = matches!(&d.kind, Kind::Motion(k) if k.wide());
if cell_enter && collapsed {
ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
}
}
});
app.viewport.dialog_rect = response.map(|r| r.response.rect);
let body = |ui: &mut egui::Ui| {
enter |= dense::rows(app, ctx, &mut d, ui);
if cell_enter {
ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
}
let text = app.applying.as_ref().map(|job| {
let seconds = ((crate::now_ms() - job.started) / 1000.0).floor().max(0.0);
crate::i18n::format("dialog.computing", &[("seconds", &format!("{seconds:.0}"))])
});
crate::ui_kit::ComputeStatus { text, busy: app.applying.is_some() || app.preview.busy, applying: app.applying.is_some() }
};
let (closed, action) = if manager {
panel.feature_collapsible(ui, heading, applying, valid, &mut collapsed, body)
} else {
panel.feature(ui, heading, applying, valid, body)
};
d.reset_scroll = false;
d.collapsed = collapsed;
cancel |= closed;
if app.issue_report.draft.is_none() {
match action {
crate::ui_kit::Action::Ok => {
ok = true;
apply_again = false;
}
crate::ui_kit::Action::Cancel => {
if !app.esc_handled || !ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
cancel = true;
}
}
crate::ui_kit::Action::Apply => {
ok = true;
apply_again = true;
}
crate::ui_kit::Action::None => {}
}
}
});
app.viewport.dialog_rect = response.map(|r| r.response.rect);
}
if let Some(r) = app.viewport.dialog_rect {
crate::scenario::publish_rect("dialog:outer", r);
crate::scenario::publish_target("dialog:card", r);
-10
View File
@@ -792,16 +792,6 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo
enter |= ui_kit::focused_text_field(ui, name, "");
});
}
Kind::ConfirmDelete { with, fail, .. } => {
if !with.is_empty() {
form_row(ui, "Also deletes", |ui| {
ui_kit::text(ui, &with.join(", "), ui_kit::Text::Cell);
});
}
if !fail.is_empty() {
ui_kit::text(ui, &format!("{}: {}", tr("Will fail"), fail.join(", ")), ui_kit::Text::Report("will_fail", true));
}
}
_ => {}
}
enter
+13 -18
View File
@@ -4,7 +4,7 @@
//! Closing a design with unsaved changes asks first, and so does quitting: one "save changes?"
//! per design with unsaved changes ([`request_quit`]).
use egui::{Align2, FontId, Rect, Sense, pos2, vec2};
use egui::{FontId, Rect, Sense, pos2, vec2};
use serde_json::{Value, json};
use solidcraft_engine::Session;
use solidcraft_engine::render::Camera;
@@ -549,7 +549,7 @@ pub fn prompt(app: &mut SolveApp, ctx: &egui::Context) {
let mut answer: Option<Answer> = None;
// Left and Right move between the buttons as they are laid out (Save is picked first, at the
// right); Enter gives the picked one.
let order = [Answer::Cancel, Answer::DontSave, Answer::Save];
let order = [Answer::DontSave, Answer::Cancel, Answer::Save];
let (left, right, enter) = ctx.input_mut(|x| {
(
x.consume_key(egui::Modifiers::NONE, egui::Key::ArrowLeft),
@@ -571,22 +571,17 @@ pub fn prompt(app: &mut SolveApp, ctx: &egui::Context) {
answer = Some(choice);
}
let title = crate::i18n::format("document.save_changes", &[("name", &name_display)]);
let (closed, action) =
ui_kit::Prompt::new(egui::Id::new("sc_close_prompt"), solidcraft_engine::find_command("file.save").map_or("", |c| c.icon), &title)
.anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0))
.actions(crate::i18n::tr("ui.save"), crate::i18n::tr("ui.cancel"), Some(crate::i18n::tr("ui.don_t_save")))
.selected(match choice {
Answer::Save => ui_kit::Action::Ok,
Answer::DontSave => ui_kit::Action::Apply,
Answer::Cancel => ui_kit::Action::Cancel,
})
.show(ctx, true, |ui| {
ui_kit::text(
ui,
&crate::i18n::format("document.unsaved_changes", &[("name", &name_display)]),
ui_kit::Text::Report("unsaved", false),
);
});
let (closed, action) = ui_kit::Confirm::new(egui::Id::new("sc_close_prompt"), "status_warning", &title)
.tone(ui_kit::Tone::Warning)
.actions(crate::i18n::tr("ui.save"), crate::i18n::tr("ui.cancel"), Some(crate::i18n::tr("ui.don_t_save")))
.selected(match choice {
Answer::Save => ui_kit::Action::Ok,
Answer::DontSave => ui_kit::Action::Apply,
Answer::Cancel => ui_kit::Action::Cancel,
})
.show(ctx, true, |ui| {
ui_kit::text(ui, &crate::i18n::format("document.unsaved_changes", &[("name", &name_display)]), ui_kit::Text::Report("unsaved", false));
});
answer = match action {
ui_kit::Action::Ok => Some(Answer::Save),
ui_kit::Action::Apply => Some(Answer::DontSave),
+1 -1
View File
@@ -931,7 +931,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
Kind::Recover { .. } => "restore",
Kind::ExportDxf => "export",
};
let (closed, action) = ui_kit::Prompt::new(card_id, icon, title)
let (closed, action) = ui_kit::Window::new(card_id, icon, title)
.cards(((cover.width() - 16.0) / crate::theme::Tokens::get().form_card_width).clamp(0.5, 1.3))
.placed(egui::Align2::CENTER_TOP, top)
.actions("", crate::i18n::tr("ui.cancel"), None)
+1 -1
View File
@@ -246,7 +246,7 @@ mod tests {
let p = e.unwrap().path();
if p.extension().is_some_and(|x| x == "rs") && p.file_name().is_some_and(|n| n != "frame.rs") {
let text = std::fs::read_to_string(&p).unwrap();
if text.contains("Window::new(") {
if text.contains("egui::Window::new(") {
bad.push(p.display().to_string());
}
}
+1 -1
View File
@@ -98,7 +98,7 @@ fn about(app: &mut SolveApp, ctx: &egui::Context) {
if !app.help.about {
return;
}
let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_about"), "help", crate::i18n::tr_label("About SolidCraft"))
let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_about"), "help", crate::i18n::tr_label("About SolidCraft"))
.cards(2.0)
.actions("", "Close", None)
.show(ctx, true, |ui| {
+1 -1
View File
@@ -88,7 +88,7 @@ pub fn start(app: &mut SolveApp, offer: Offer) {
pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
let Some(steps) = app.install_steps else { return };
let (lines, after) = steps.messages();
let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_install_steps"), "web", crate::i18n::tr("install.title"))
let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_install_steps"), "web", crate::i18n::tr("install.title"))
.actions("", crate::i18n::tr("install.done"), None)
.show(ctx, true, |ui| {
ui_kit::text(ui, crate::i18n::tr("install.steps_intro"), ui_kit::Text::Report("intro", false));
+1 -1
View File
@@ -517,7 +517,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
let chrome = ui_kit::header_height() + t.form_footer_height + 6.0 * t.space_8;
let scroll = (screen.height() - 2.0 * t.space_16 - chrome).clamp(60.0, 640.0);
let mut link = None;
let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_issue_report"), "bug_report", crate::i18n::tr_label("Create Issue — review draft"))
let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_issue_report"), "bug_report", crate::i18n::tr_label("Create Issue — review draft"))
.cards(cards)
.fields()
.keep_open_on_escape()
+36 -36
View File
@@ -210,6 +210,33 @@ pub fn nav_preset(id: &str) -> &'static NavPreset {
}
/// The dialog's pages, in order.
pub const PAGES: [&str; 9] = ["General", "Navigation", "Keyboard Shortcuts", "Design", "Graphics", "Sketch", "Selection", "AI", "Plugins"];
// Keep every existing page and its scenario identity; only their presentation is shared.
const WINDOW_PAGES: [ui_kit::WindowPage<SolveApp>; 9] = [
ui_kit::WindowPage { icon: "settings", label: "ui.general", handle: "prefs:page:General", scroll: true, draw: window_page::<0> },
ui_kit::WindowPage { icon: "orbit", label: "ui.navigation", handle: "prefs:page:Navigation", scroll: true, draw: window_page::<1> },
ui_kit::WindowPage {
icon: "settings",
label: "ui.keyboard_shortcuts",
handle: "prefs:page:Keyboard Shortcuts",
scroll: false,
draw: window_page::<2>,
},
ui_kit::WindowPage { icon: "ws_design", label: "ui.design", handle: "prefs:page:Design", scroll: true, draw: window_page::<3> },
ui_kit::WindowPage { icon: "style", label: "ui.graphics", handle: "prefs:page:Graphics", scroll: true, draw: window_page::<4> },
ui_kit::WindowPage { icon: "sketch", label: "ui.sketch", handle: "prefs:page:Sketch", scroll: true, draw: window_page::<5> },
ui_kit::WindowPage { icon: "select", label: "ui.selection", handle: "prefs:page:Selection", scroll: true, draw: window_page::<6> },
ui_kit::WindowPage { icon: "assistant", label: "ui.ai_button", handle: "prefs:page:AI", scroll: true, draw: window_page::<7> },
ui_kit::WindowPage { icon: "library", label: "ui.plugins", handle: "prefs:page:Plugins", scroll: true, draw: window_page::<8> },
];
fn window_page<const INDEX: usize>(ui: &mut egui::Ui, app: &mut SolveApp) {
if app.prefs_window.section != INDEX {
app.keymap.read_only = false;
app.prefs_window.section = INDEX;
}
page(app, ui, &Tokens::get());
}
pub const PAGE_AI: usize = 7;
pub const PAGE_PLUGINS: usize = 8;
pub const PAGE_SHORTCUTS: usize = 2;
@@ -966,54 +993,27 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
app.prefs_window.snapshot = Some(Snapshot::take(app));
}
unfold(ctx);
let t = Tokens::get();
let mut button: Option<&str> = None;
let before = app.preferences.clone();
let capturing = crate::keymap::capturing(app);
let prompt = ui_kit::Prompt::new(egui::Id::new("sc_prefs"), "settings", app.tr("ui.preferences")).cards(3.0).fields().actions(
let window = ui_kit::Window::new(egui::Id::new("sc_prefs"), "settings", app.tr("ui.preferences")).cards(3.0).fields().actions(
"OK",
"Cancel",
Some("Apply"),
);
let prompt = if capturing { prompt.keep_open_on_escape() } else { prompt };
let (closed, action) = prompt.show(ctx, true, |ui| {
// A fixed, clipped page viewport keeps every page and translation the same size.
let height = (ctx.content_rect().height() - t.form_header_height - t.form_footer_height - t.space_24 * 3.0)
.clamp(t.control_height * 4.0, t.control_height * 16.0);
let (body, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), height), egui::Sense::hover());
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(body).layout(egui::Layout::left_to_right(egui::Align::Min)));
child.shrink_clip_rect(body);
child.vertical(|ui| {
ui.set_width(t.form_label_width * 2.0);
for (i, title) in PAGES.iter().enumerate() {
let tab = ui_kit::list_picker(ui, title, app.tr_label(title), app.prefs_window.section == i);
crate::scenario::publish_target(&format!("prefs:page:{title}"), tab.rect);
if tab.clicked() {
app.prefs_window.section = i;
app.keymap.read_only = false;
}
}
});
child.separator();
child.vertical(|ui| {
ui.set_width(ui.available_width());
if app.prefs_window.section == PAGE_SHORTCUTS {
page(app, ui, &t);
} else {
let scroll = egui::ScrollArea::vertical()
.id_salt(("sc_prefs_page", app.prefs_window.section))
.auto_shrink([false, false])
.show(ui, |ui| page(app, ui, &t));
crate::scenario::publish_rect("prefs:page_body", scroll.inner_rect);
}
});
if ui_kit::button(ui, app.tr("ui.restore_defaults"), ui_kit::Button::Normal)
.on_hover_text(app.tr("ui.reset_the_settings_on_this_page"))
let window = if capturing { window.keep_open_on_escape() } else { window };
let mut selected = app.prefs_window.section;
let (closed, action) = window.show_pages(ctx, &mut selected, &WINDOW_PAGES, app, |ui| {
if ui_kit::button(ui, crate::i18n::tr("ui.restore_defaults"), ui_kit::Button::Normal)
.on_hover_text(crate::i18n::tr("ui.reset_the_settings_on_this_page"))
.clicked()
{
button = Some("defaults");
}
});
if let Some(rect) = crate::scenario::rect_of("dialog:page_body") {
crate::scenario::publish_rect("prefs:page_body", rect);
}
for name in ["window", "footer", "ok", "apply", "cancel"] {
if let Some(rect) = crate::scenario::rect_of(&format!("dialog:{name}")) {
crate::scenario::publish_target(&format!("prefs:{name}"), rect);
+1 -1
View File
@@ -10,7 +10,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
if app.settings_reset.is_empty() {
return;
}
let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_settings_reset"), "settings", app.tr("settings.reset_title"))
let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_settings_reset"), "settings", app.tr("settings.reset_title"))
.actions(app.tr("ui.open_preferences"), app.tr("ui.heading_ok"), None)
.show(ctx, true, |ui| {
ui_kit::text(ui, app.tr("settings.reset_intro"), ui_kit::Text::Report("intro", false));
+25 -4
View File
@@ -64,12 +64,12 @@ fn delete_confirmation_deletes_on_the_primary_action_and_keeps_everything_otherw
}
#[test]
fn legacy_delete_dialog_is_a_dense_card_whose_primary_action_is_delete() {
fn legacy_delete_dialog_is_a_confirm_whose_primary_action_is_delete() {
let mut h = with_dependent_feature();
h.app.menu.confirm = None;
h.app.dialog = Some(crate::dialogs::Dialog::confirm_delete(1, vec!["Extrude1".into()], vec!["Hole1".into()]));
card_is_drawn(&mut h);
assert!(scenario::handle_at("dialog:Delete").is_some() && scenario::rect_of("dialog:row:Also deletes").is_some());
assert!(scenario::handle_at("dialog:Delete").is_some() && scenario::rect_of("dialog:note:confirm_detail").is_some());
press(&mut h, "Cancel");
assert!(h.app.dialog.is_none());
}
@@ -128,16 +128,19 @@ fn save_prompt_moves_between_its_actions_with_the_arrow_keys() {
assert!(scenario::handle_at(&format!("dialog:{label}")).is_some(), "{label}");
}
assert_eq!(h.app.docs.choice, Answer::Save);
// The buttons read Cancel, Don't Save, Save from the left: Left walks toward Cancel.
// The ghost action is at the left: Don't Save, Cancel, Save. Arrows follow that order.
h.step(&json!({"key": "ArrowLeft"})).unwrap();
h.frames(2);
assert_eq!(h.app.docs.choice, Answer::DontSave);
assert_eq!(h.app.docs.choice, Answer::Cancel);
h.step(&json!({"key": "ArrowRight"})).unwrap();
h.frames(2);
assert_eq!(h.app.docs.choice, Answer::Save);
h.step(&json!({"key": "ArrowLeft"})).unwrap();
h.step(&json!({"key": "ArrowLeft"})).unwrap();
h.frames(2);
assert_eq!(h.app.docs.choice, Answer::DontSave);
h.step(&json!({"key": "ArrowRight"})).unwrap();
h.frames(2);
assert_eq!(h.app.docs.choice, Answer::Cancel);
h.step(&json!({"key": "Enter"})).unwrap();
h.frames(2);
@@ -228,3 +231,21 @@ fn object_properties_card_only_closes() {
press(&mut h, "Close");
assert!(h.app.menu.props.is_none());
}
#[test]
fn delete_confirm_resumes_after_the_issue_draft_closes() {
let mut h = with_dependent_feature();
h.frames(3);
let features = h.app.session.doc.features.len();
h.app.issue_report.draft = Some(crate::issue_report::draft_for(&h.app, None, None));
// As in the report window's screenshot/layout tests, let the bounded review settle.
h.frames(20);
let [x, y] = h.widget("Close draft").unwrap();
assert!(scenario::rect_of("dialog:cancel").unwrap().contains(egui::pos2(x as f32, y as f32)));
h.step(&json!({"widget":"Close draft"})).unwrap();
h.frames(3);
assert!(h.app.issue_report.draft.is_none(), "the report can close while the confirmation is suspended");
assert!(h.app.menu.confirm.is_some() && h.app.session.doc.features.len() == features);
press(&mut h, "Cancel");
assert!(h.app.menu.confirm.is_none() && h.app.session.doc.features.len() == features);
}
+1 -1
View File
@@ -56,7 +56,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
}
let dir = app.autosave.as_ref().map(|a| a.dir.clone()).or_else(recovery::default_dir);
let mut act: Option<(Entry, bool)> = None;
let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_recover_prompt"), "restore", crate::i18n::tr_label("Recover unsaved design?"))
let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_recover_prompt"), "restore", crate::i18n::tr_label("Recover unsaved design?"))
.actions("", crate::i18n::tr_label("Later"), None)
.show(ctx, true, |ui| {
ui_kit::text(
+1 -1
View File
@@ -48,7 +48,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
if app.stand_up.is_none() {
return;
}
let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_stand_up"), "move", crate::i18n::tr_label("Stand this part up?"))
let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_stand_up"), "move", crate::i18n::tr_label("Stand this part up?"))
.anchor(egui::Align2::CENTER_TOP, egui::vec2(0.0, 140.0))
.actions("Stand it up", "Leave it", Some("Don't ask again"))
.show(ctx, true, |ui| {
+1 -1
View File
@@ -50,7 +50,7 @@ pub(crate) struct TabAccent {
}
/// WCAG contrast of two opaque sRGB colours.
fn contrast_ratio(a: Color32, b: Color32) -> f64 {
pub(crate) fn contrast_ratio(a: Color32, b: Color32) -> f64 {
let luminance = |c: Color32| {
let linear = |v: u8| {
let v = f64::from(v) / 255.0;
+1 -1
View File
@@ -286,7 +286,7 @@ pub fn window(app: &mut SolveApp, ctx: &egui::Context) {
// published positions instead of shifting them after egui measures the taller content.
let origin =
egui::pos2((ctx.content_rect().center().x - t.form_card_width).max(ctx.content_rect().left()), ctx.content_rect().top() + t.space_24 * 2.0);
let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_toolbar_customize"), "settings", crate::i18n::tr_label("Customize Toolbar"))
let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_toolbar_customize"), "settings", crate::i18n::tr_label("Customize Toolbar"))
.placed(egui::Align2::LEFT_TOP, origin)
.cards(2.0)
.actions("", "Close", None)
+41 -5
View File
@@ -66,15 +66,31 @@ pub(crate) struct Footer<'a> {
pub apply: Option<&'a str>,
pub status: Option<&'a str>,
pub selected: Option<Action>,
pub danger: bool,
pub confirm: bool,
}
pub(crate) fn footer(ui: &mut Ui, ok_label: &str, cancel_label: &str, ok_enabled: bool, options: Footer<'_>) -> Action {
let Footer { apply: apply_label, status, selected } = options;
footer_with_left(ui, ok_label, cancel_label, ok_enabled, options, |_| {})
}
pub(super) fn footer_with_left(
ui: &mut Ui,
ok_label: &str,
cancel_label: &str,
ok_enabled: bool,
options: Footer<'_>,
left: impl FnOnce(&mut Ui),
) -> Action {
let Footer { apply: apply_label, status, selected, danger, confirm } = options;
let t = Tokens::get();
let ok_enabled = ok_enabled && !ok_label.is_empty();
// The footer is a full-width band (the card has no margin of its own): its own fill, a rule
// on top, and the buttons right-aligned with 10 pt above/below and 12 pt at the sides.
let (band, _) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), t.form_footer_height), egui::Sense::hover());
let (band, _) = ui.allocate_exact_size(
vec2(dimension(ui.available_width()), t.form_footer_height + if confirm { t.space_4 } else { 0.0 }),
egui::Sense::hover(),
);
let corner = t.radius_xl.saturating_sub(1);
ui.painter().rect_filled(band, egui::CornerRadius { nw: 0, ne: 0, sw: corner, se: corner }, t.dialog_footer);
ui.painter().hline(band.x_range(), band.top(), egui::Stroke::new(1.0, t.dialog_rule));
@@ -83,12 +99,14 @@ pub(crate) fn footer(ui: &mut Ui, ok_label: &str, cancel_label: &str, ok_enabled
let inner = band.shrink2(vec2(t.space_12, t.space_10));
scenario::publish_rect("dialog:footer:actions", inner);
let mut action = if ui.is_enabled() { keyboard(ui.ctx(), ok_enabled) } else { Action::None };
let primary_fill = if danger { t.form_error } else { t.form_primary };
let primary_ink = if danger && crate::theme::contrast_ratio(t.on_accent, primary_fill) < 4.5 { t.tab_on_fill_dark } else { t.on_accent };
let mut actions_left = inner.right();
let row = ui.scope_builder(egui::UiBuilder::new().max_rect(inner).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.spacing_mut().item_spacing.x = t.space_6;
for (label, kind) in [(ok_label, Action::Ok), (apply_label.unwrap_or(""), Action::Apply), (cancel_label, Action::Cancel)] {
if (kind == Action::Apply && apply_label.is_none()) || (kind == Action::Ok && ok_label.is_empty()) {
if (kind == Action::Apply && (apply_label.is_none() || confirm)) || (kind == Action::Ok && ok_label.is_empty()) || label.is_empty() {
continue;
}
let marked = selected == Some(kind);
@@ -96,7 +114,7 @@ pub(crate) fn footer(ui: &mut Ui, ok_label: &str, cancel_label: &str, ok_enabled
let live = kind == Action::Cancel || ok_enabled;
ui.spacing_mut().button_padding = vec2(if primary { t.space_16 } else { t.space_12 }, 0.0);
let text = RichText::new(crate::i18n::tr_label(label)).size(t.font_label).color(if primary && ok_enabled {
t.on_accent
primary_ink
} else if primary {
t.form_dim
} else {
@@ -107,7 +125,7 @@ pub(crate) fn footer(ui: &mut Ui, ok_label: &str, cancel_label: &str, ok_enabled
egui::Button::new(if primary && ok_enabled { text.bold_face() } else { text })
.selected(marked && !primary)
.fill(if primary && ok_enabled {
t.form_primary
primary_fill
} else if marked {
t.selected_bg
} else {
@@ -136,6 +154,24 @@ pub(crate) fn footer(ui: &mut Ui, ok_label: &str, cancel_label: &str, ok_enabled
}
});
});
let left_rect = egui::Rect::from_min_max(inner.min, egui::pos2((actions_left - t.space_8).max(inner.left()), inner.bottom()));
ui.scope_builder(egui::UiBuilder::new().max_rect(left_rect).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| {
if let Some(label) = apply_label.filter(|_| confirm) {
let response = ui.add(
egui::Button::new(crate::i18n::tr_label(label))
.frame(false)
.selected(selected == Some(Action::Apply))
.min_size(vec2(0.0, t.form_button_height)),
);
pointer_on_hover(ui, &response);
scenario::publish_target("dialog:apply", response.rect);
scenario::publish_handle(&format!("dialog:{label}"), response.rect.center());
if response.clicked() {
action = Action::Apply;
}
}
left(ui);
});
if let Some(status) = status {
let left = (row.response.rect.left() + t.space_16 + t.space_4).min(actions_left);
let right = (actions_left - t.space_8).max(left);
+138
View File
@@ -0,0 +1,138 @@
//! Modal confirmations share the Panel/Window frame and the single kit footer.
use super::{Action, Footer, Window, actions::footer_with_left, text::paint_text};
use crate::{scenario, theme::Tokens};
use egui::{Ui, vec2};
#[derive(Clone, Copy)]
pub(crate) enum Tone {
Warning,
Danger,
Info,
}
pub(crate) struct Confirm<'a> {
window: Window<'a>,
icon: &'a str,
title: &'a str,
tone: Tone,
ok: &'a str,
cancel: &'a str,
left: Option<&'a str>,
selected: Option<Action>,
detail: Option<&'a str>,
}
impl<'a> Confirm<'a> {
pub(crate) fn new(id: egui::Id, icon: &'a str, title: &'a str) -> Self {
Self {
window: Window::new(id, icon, title),
icon,
title,
tone: Tone::Info,
ok: "OK",
cancel: "Cancel",
left: None,
selected: None,
detail: None,
}
}
pub(crate) fn tone(mut self, tone: Tone) -> Self {
self.tone = tone;
self
}
pub(crate) fn actions(mut self, ok: &'a str, cancel: &'a str, left: Option<&'a str>) -> Self {
(self.ok, self.cancel, self.left) = (ok, cancel, left);
self
}
pub(crate) fn selected(mut self, selected: Action) -> Self {
self.selected = Some(selected);
self
}
pub(crate) fn detail(mut self, detail: &'a str) -> Self {
self.detail = (!detail.is_empty()).then_some(detail);
self
}
pub(crate) fn show(self, ctx: &egui::Context, valid: bool, message: impl FnOnce(&mut Ui)) -> (bool, Action) {
// Reviewed reports and native pickers temporarily own input. Keep the pending
// answer untouched and resume the modal when that boundary closes.
if crate::issue_report::cad_input_blocked() {
return (false, Action::None);
}
self.window.surface(ctx, true, |ui| self.content(ui, valid, message))
}
pub(super) fn content(&self, ui: &mut Ui, valid: bool, message: impl FnOnce(&mut Ui)) -> (bool, Action) {
super::scope(ui, |ui| {
let t = Tokens::get();
ui.spacing_mut().item_spacing.y = 0.0;
// Consume before native button focus can interpret Enter as a different answer.
let enter = ui.is_enabled() && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
let mut closed = false;
egui::Frame::NONE
.inner_margin(egui::Margin {
left: (t.space_16 + t.space_2) as i8,
right: (t.space_16 + t.space_2) as i8,
top: (t.space_16 + t.space_2) as i8,
bottom: t.space_16 as i8,
})
.show(ui, |ui| {
ui.spacing_mut().item_spacing = vec2(t.space_14, t.space_6);
ui.horizontal_top(|ui| {
let diameter = t.control_height + t.space_8;
let (disc, _) = ui.allocate_exact_size(vec2(diameter, diameter), egui::Sense::hover());
let (fill, ink) = match self.tone {
Tone::Warning => (t.warning.gamma_multiply(0.15), t.warning),
Tone::Danger => (t.form_error_fill, t.form_error),
Tone::Info => (t.accent_soft, t.form_primary),
};
ui.painter().circle_filled(disc.center(), diameter / 2.0, fill);
crate::icons::paint_ink(ui.painter(), disc.shrink(t.space_8), self.icon, ink);
scenario::publish_rect("confirm:disc", disc);
ui.vertical(|ui| {
ui.set_width(ui.available_width().max(0.0));
let (heading, _) = ui.allocate_exact_size(vec2(ui.available_width().max(0.0), t.form_close_size), egui::Sense::hover());
let close = egui::Rect::from_min_size(
egui::pos2((heading.right() - t.form_close_size).max(heading.left()), heading.top()),
vec2(t.form_close_size, t.form_close_size),
);
let title = egui::Rect::from_min_max(heading.min, egui::pos2(close.left(), heading.bottom()));
paint_text(ui, title, self.title, crate::fonts::semibold(t.font_subtitle), t.form_ink, false);
ui.interact(title, ui.id().with("title"), egui::Sense::hover())
.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, ui.is_enabled(), self.title));
let response = super::icon_button_at(ui, close, "close", "Close");
closed = response.clicked();
scenario::publish_target("dialog:close", response.rect);
scenario::publish_rect("dialog:header", heading);
message(ui);
if let Some(detail) = self.detail {
super::list_frame(ui, "confirm_detail", |ui| {
super::text(ui, detail, super::Text::MonoNote("confirm_detail"));
});
}
});
});
});
let action = footer_with_left(
ui,
self.ok,
self.cancel,
valid,
Footer { apply: self.left, selected: self.selected, danger: matches!(self.tone, Tone::Danger), confirm: true, ..Default::default() },
|_| {},
);
let action = if action == Action::Cancel {
action
} else if enter && valid {
self.selected.unwrap_or(Action::Ok)
} else {
action
};
(closed, action)
})
}
}
+50
View File
@@ -28,6 +28,56 @@ macro_rules! element {
// One entry per element/variant: names, rendering and geometry expectations stay together.
const ELEMENTS: &[Element] = &[
element!("window", "dialog:footer", Some("dialog:ok"), |ui, _| {
Window::new(ui.id().with("window"), "settings", "Preferences").content(
ui,
true,
|ui| {
text(ui, "General", Text::Report("window", false));
},
|ui| {
button(ui, "Restore defaults", Button::Normal);
},
);
}),
element!("window_pages", "dialog:pages", Some("gallery:page"), |ui, s| {
panel::page_list(
ui,
&mut s.selected,
&[WindowPage {
icon: "settings",
label: "ui.general",
handle: "gallery:page",
scroll: true,
draw: |ui, _: &mut ()| {
text(ui, "General", Text::Inline);
},
}],
&mut (),
);
}),
element!("confirm_warning", "dialog:footer", Some("dialog:apply"), |ui, _| {
Confirm::new(ui.id().with("confirm"), "status_warning", "Save changes?")
.tone(Tone::Warning)
.actions("Save", "Cancel", Some("Don't Save"))
.content(ui, true, |ui| {
text(ui, "Your changes will be lost.", Text::Report("message", false));
});
}),
element!("confirm_danger", "dialog:footer", Some("dialog:ok"), |ui, _| {
Confirm::new(ui.id().with("confirm"), "delete", "Delete")
.tone(Tone::Danger)
.detail("Fillet2 · Chamfer1")
.actions("Delete", "Cancel", None)
.content(ui, true, |ui| {
text(ui, "These features will be deleted:", Text::Report("message", false));
});
}),
element!("confirm_info", "dialog:footer", Some("dialog:ok"), |ui, _| {
Confirm::new(ui.id().with("confirm"), "help", "Replace file?").actions("Replace", "Cancel", None).content(ui, true, |ui| {
text(ui, "A file with this name already exists.", Text::Report("message", false));
});
}),
element!("mono_note", |ui, _| {
text(ui, "solid.fillet · replayable", Text::MonoNote("sample"));
}),
+3 -1
View File
@@ -5,6 +5,7 @@ mod actions;
mod checks;
mod choice;
mod color;
mod confirm;
mod disclosure;
mod fields;
mod layout;
@@ -19,11 +20,12 @@ pub(crate) use actions::*;
pub(crate) use checks::*;
pub(crate) use choice::*;
pub(crate) use color::*;
pub(crate) use confirm::{Confirm, Tone};
pub(crate) use disclosure::*;
pub(crate) use fields::*;
pub(crate) use layout::*;
pub(crate) use metrics::{ContentWidth, header_height, row_height, table_row_height};
pub(crate) use panel::{ComputeStatus, FeatureOptions, Panel, Part, Prompt};
pub(crate) use panel::{ComputeStatus, FeatureOptions, Panel, Part, Window, WindowPage};
#[cfg(test)]
pub(crate) use panel::{collapsible_header, header};
pub(crate) use reports::*;
+177 -42
View File
@@ -90,11 +90,17 @@ pub(crate) enum Part {
}
impl<'a> Panel<'a> {
/// Shared floating card surface for panels, windows and modal confirmations.
pub(super) fn card_frame() -> egui::Frame {
let t = Tokens::get();
crate::frame::shell_card(t.dialog_body).stroke(egui::Stroke::new(1.0, t.dialog_border)).corner_radius(t.radius_xl).inner_margin(0.0)
}
/// Feature surface; Tokens: dialog_body and shell_card/dock_frame's border/shadow tokens.
pub(crate) fn feature_frame(ctx: &egui::Context, layout: crate::shell::LayoutMode, side: crate::frame::Side) -> egui::Frame {
let t = Tokens::get();
if layout == crate::shell::LayoutMode::Floating {
crate::frame::shell_card(t.dialog_body).stroke(egui::Stroke::new(1.0, t.dialog_border)).corner_radius(t.radius_xl).inner_margin(0.0)
Self::card_frame()
} else {
crate::frame::dock_frame(ctx, side).fill(t.dialog_body).inner_margin(0.0)
}
@@ -275,7 +281,7 @@ impl<'a> Panel<'a> {
self.ok,
self.cancel,
valid && !state.applying,
super::Footer { apply: heading.apply_label, status: state.text.as_deref(), selected: None },
super::Footer { apply: heading.apply_label, status: state.text.as_deref(), ..Default::default() },
);
if state.busy {
let rect = egui::Rect::from_min_size(
@@ -339,12 +345,10 @@ impl<'a> Panel<'a> {
}
}
/// A centred prompt or small form card, one and a half card widths wide: the feature header (icon, title, close), a padded body,
/// and the pinned footer with up to three actions (`apply` is the third, middle action, e.g.
/// "Don't Save"). Floats over the viewport instead of docking, for confirmations, offers and
/// short property forms. Tokens: `form_card_width` (x1.5), header/footer tokens, `dialog_body`,
/// `space_6/8/10`.
pub(crate) struct Prompt<'a> {
/// System window built on Panel's shared floating card: 40 pt header, bounded content,
/// optional page list, and 48 pt actions with a left slot. Existing IDs and editor policies
/// survive the migration. All geometry and colours derive from Tokens.
pub(crate) struct Window<'a> {
id: egui::Id,
icon: &'a str,
title: &'a str,
@@ -353,13 +357,14 @@ pub(crate) struct Prompt<'a> {
ok: &'a str,
cancel: &'a str,
apply: Option<&'a str>,
selected: Option<super::Action>,
enter_submits: bool,
escape_closes: bool,
width: f32,
body_padding: bool,
left_slot: bool,
}
impl<'a> Prompt<'a> {
impl<'a> Window<'a> {
/// A card with OK and Cancel, centred and movable.
pub(crate) fn new(id: egui::Id, icon: &'a str, title: &'a str) -> Self {
Self {
@@ -371,10 +376,11 @@ impl<'a> Prompt<'a> {
ok: "OK",
cancel: "Cancel",
apply: None,
selected: None,
enter_submits: true,
escape_closes: true,
width: Tokens::get().form_card_width * 1.5,
body_padding: true,
left_slot: false,
}
}
@@ -414,24 +420,93 @@ impl<'a> Prompt<'a> {
/// `cards` times the card width instead of one and a half, for wide footers.
pub(crate) fn cards(mut self, cards: f32) -> Self {
if cards.is_finite() && cards > 0.0 {
self.width = Tokens::get().form_card_width * cards;
self.width = Tokens::get().form_card_width * cards.min(16.0);
}
self
}
/// Mark one action as the one Enter gives.
pub(crate) fn selected(mut self, action: super::Action) -> Self {
self.selected = Some(action);
self
/// Draw shared header, content and optional footer, retaining the caller's IDs.
pub(crate) fn show(self, ctx: &egui::Context, valid: bool, body: impl FnOnce(&mut Ui)) -> (bool, super::Action) {
self.surface(ctx, false, |ui| self.content(ui, valid, body, |_| {}))
}
/// Draw the card. Returns whether the header's close was pressed and the footer's action.
/// `valid` enables the primary action.
pub(crate) fn show(self, ctx: &egui::Context, valid: bool, body: impl FnOnce(&mut Ui)) -> (bool, super::Action) {
let t = Tokens::get();
let frame =
crate::frame::shell_card(t.dialog_body).stroke(egui::Stroke::new(1.0, t.dialog_border)).corner_radius(t.radius_xl).inner_margin(0.0);
let inner_width = (self.width.min(ctx.content_rect().width()) - frame.total_margin().sum().x).max(0.0);
/// A pinned left action slot, independent of the right-aligned footer buttons.
pub(crate) fn show_with_left(
mut self,
ctx: &egui::Context,
valid: bool,
body: impl FnOnce(&mut Ui),
left: impl FnOnce(&mut Ui),
) -> (bool, super::Action) {
self.left_slot = true;
self.surface(ctx, false, |ui| self.content(ui, valid, body, left))
}
pub(super) fn content(&self, ui: &mut Ui, valid: bool, body: impl FnOnce(&mut Ui), left: impl FnOnce(&mut Ui)) -> (bool, super::Action) {
super::scope(ui, |ui| {
let t = Tokens::get();
ui.spacing_mut().item_spacing.y = 0.0;
let mut close = false;
header(ui, self.icon, self.title, || close = true);
egui::Frame::NONE.inner_margin(if self.body_padding { t.space_12 } else { 0.0 }).show(ui, |ui| {
ui.spacing_mut().item_spacing.y = t.form_gap_y;
if self.body_padding {
let height =
(dimension(ui.ctx().content_rect().height()) - t.form_header_height - t.form_footer_height - t.space_24 * 2.0).max(0.0);
egui::ScrollArea::vertical()
.id_salt("window_body")
.max_height(height)
.min_scrolled_height(0.0)
.auto_shrink([false, true])
.show(ui, body);
} else {
body(ui);
}
});
if !self.enter_submits {
ui.ctx().input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
}
if !self.escape_closes {
ui.ctx().input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape));
}
let action = if self.ok.is_empty() && self.cancel.is_empty() && self.apply.is_none() && !self.left_slot {
super::Action::None
} else {
super::actions::footer_with_left(ui, self.ok, self.cancel, valid, super::Footer { apply: self.apply, ..Default::default() }, left)
};
(close, action)
})
}
/// Declarative page navigation: the kit owns geometry, selection and page scrolling.
pub(crate) fn show_pages<S>(
mut self,
ctx: &egui::Context,
selected: &mut usize,
pages: &[WindowPage<S>],
state: &mut S,
left: impl FnOnce(&mut Ui),
) -> (bool, super::Action) {
self.body_padding = false;
self.show_with_left(ctx, true, |ui| page_list(ui, selected, pages, state), left)
}
/// The same bounded card frame, either movable or an input-blocking modal.
pub(super) fn surface(&self, ctx: &egui::Context, modal: bool, add: impl FnOnce(&mut Ui) -> (bool, super::Action)) -> (bool, super::Action) {
let frame = Panel::card_frame();
let inner_width = (self.width.min(dimension(ctx.content_rect().width())) - frame.total_margin().sum().x).max(0.0);
if modal {
let shown = egui::Modal::new(self.id)
.area(egui::Modal::default_area(self.id).fade_in(false))
.backdrop_color(Tokens::get().tab_on_fill_dark.gamma_multiply(0.35))
.frame(frame)
.show(ctx, |ui| {
ui.set_width(inner_width);
add(ui)
});
scenario::publish_rect("dialog:window", shown.response.rect);
return shown.inner;
}
let window = egui::Window::new(self.title)
.enabled(!crate::issue_report::cad_input_blocked())
.id(self.id)
@@ -450,31 +525,91 @@ impl<'a> Prompt<'a> {
(None, Some((pivot, pos))) => window.pivot(pivot).default_pos(pos),
(None, None) => window.pivot(egui::Align2::CENTER_CENTER).default_pos(ctx.content_rect().center() - vec2(0.0, row_height() * 2.5)),
};
let shown = window.show(ctx, |ui| {
super::scope(ui, |ui| {
let mut close = false;
header(ui, self.icon, self.title, || close = true);
egui::Frame::NONE
.inner_margin(egui::Margin { left: t.space_12 as i8, right: t.space_12 as i8, top: t.space_12 as i8, bottom: t.space_12 as i8 })
.show(ui, body);
if !self.enter_submits {
ui.ctx().input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
}
if !self.escape_closes {
ui.ctx().input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape));
}
let action =
super::footer(ui, self.ok, self.cancel, valid, super::Footer { apply: self.apply, status: None, selected: self.selected });
(close, action)
})
});
let shown = window.show(ctx, add);
if let Some(shown) = &shown {
crate::scenario::publish_rect("dialog:window", shown.response.rect);
scenario::publish_rect("dialog:window", shown.response.rect);
}
shown.and_then(|r| r.inner).unwrap_or((false, super::Action::None))
}
}
/// A page's existing icon, translated label key, stable handle and draw callback.
pub(crate) struct WindowPage<S> {
pub icon: &'static str,
pub label: &'static str,
pub handle: &'static str,
pub scroll: bool,
pub draw: fn(&mut Ui, &mut S),
}
pub(super) fn page_list<S>(ui: &mut Ui, selected: &mut usize, pages: &[WindowPage<S>], state: &mut S) {
let t = Tokens::get();
let height = (dimension(ui.ctx().content_rect().height()) - t.form_header_height - t.form_footer_height - t.space_24 * 3.0)
.clamp(0.0, t.control_height * 16.0);
let (body, _) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), height), egui::Sense::hover());
let width = (t.form_label_width * 2.0 + t.space_24 * 2.0).min(body.width());
let nav = egui::Rect::from_min_size(body.min, vec2(width, body.height()));
ui.painter().rect_filled(nav, 0.0, t.dialog_footer);
ui.painter().vline(nav.right(), nav.y_range(), egui::Stroke::new(1.0, t.dialog_rule));
scenario::publish_rect("dialog:pages", nav);
*selected = (*selected).min(pages.len().saturating_sub(1));
ui.scope_builder(egui::UiBuilder::new().max_rect(nav.shrink2(vec2(t.space_8, t.space_10))), |ui| {
ui.set_clip_rect(ui.clip_rect().intersect(nav));
ui.spacing_mut().item_spacing.y = t.space_2;
egui::ScrollArea::vertical().id_salt("window_pages").show(ui, |ui| {
for (index, page) in pages.iter().enumerate() {
let label = crate::i18n::tr(page.label);
let (rect, response) =
ui.allocate_exact_size(vec2(dimension(ui.available_width()), t.control_height + t.space_4), egui::Sense::click());
if response.clicked() {
*selected = index;
}
let on = *selected == index;
if on || response.hovered() || response.has_focus() {
ui.painter().rect_filled(rect, t.control_radius, if on { t.selected_bg } else { t.hover });
}
let ink = if on { t.selected_ink } else { t.form_ink };
let icon =
egui::Rect::from_center_size(egui::pos2(rect.left() + t.space_10 + t.space_8, rect.center().y), vec2(t.space_16, t.space_16));
crate::icons::paint_ink(ui.painter(), icon, page.icon, if on { ink } else { t.form_dim });
let text_rect = egui::Rect::from_min_max(egui::pos2(icon.right() + t.space_8, rect.top()), rect.right_bottom());
paint_text(
ui,
text_rect,
label,
if on { crate::fonts::semibold(t.font_label) } else { egui::FontId::proportional(t.font_label) },
ink,
false,
);
response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, ui.is_enabled(), on, label));
if response.hovered() {
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
}
scenario::publish_target(page.handle, rect);
response.on_hover_text(label);
}
});
});
let content = egui::Rect::from_min_max(egui::pos2(nav.right(), body.top()), body.max);
let content = content.shrink2(vec2(t.space_16.min(content.width() / 2.0), t.space_16.min(content.height() / 2.0)));
ui.scope_builder(egui::UiBuilder::new().max_rect(content), |ui| {
ui.set_clip_rect(ui.clip_rect().intersect(content));
ui.spacing_mut().item_spacing.y = t.form_gap_y;
if let Some(page) = pages.get(*selected) {
if page.scroll {
let scroll = egui::ScrollArea::vertical()
.id_salt(("sc_prefs_page", *selected))
.auto_shrink([false, false])
.show(ui, |ui| (page.draw)(ui, state));
scenario::publish_rect("dialog:page_body", scroll.inner_rect);
} else {
(page.draw)(ui, state);
scenario::publish_rect("dialog:page_body", content);
}
}
});
}
#[cfg(test)]
#[path = "panel_tests.rs"]
mod tests;
+254 -5
View File
@@ -229,7 +229,7 @@ fn wide_tables_remain_bounded_with_pinned_actions_on_small_viewports() {
}
#[test]
fn prompt_is_one_and_a_half_cards_wide_with_its_actions_in_both_themes() {
fn window_is_one_and_a_half_cards_wide_with_its_actions_in_both_themes() {
let previous = crate::theme::is_dark();
for dark in [false, true] {
crate::theme::set_dark(dark);
@@ -246,9 +246,8 @@ fn prompt_is_one_and_a_half_cards_wide_with_its_actions_in_both_themes() {
..Default::default()
},
|ui| {
action = Prompt::new(egui::Id::new("prompt_test"), "delete", "Delete")
action = Window::new(egui::Id::new("prompt_test"), "delete", "Delete")
.actions("Delete", "Cancel", Some("Keep"))
.selected(Action::Apply)
.show(ui.ctx(), true, |ui| {
text(ui, "Three features go with it.", Text::Report("body", false));
})
@@ -272,7 +271,7 @@ fn prompt_is_one_and_a_half_cards_wide_with_its_actions_in_both_themes() {
}
#[test]
fn escape_closes_a_prompt_unless_it_keeps_the_card_open() {
fn escape_closes_a_window_unless_it_keeps_the_card_open() {
for keep in [false, true] {
let ctx = crate::fonts::test_context();
let mut action = Action::None;
@@ -287,7 +286,7 @@ fn escape_closes_a_prompt_unless_it_keeps_the_card_open() {
..Default::default()
},
|ui| {
let prompt = Prompt::new(egui::Id::new(("prompt_escape", keep)), "settings", "Report").actions("Open", "Close", None);
let prompt = Window::new(egui::Id::new(("prompt_escape", keep)), "settings", "Report").actions("Open", "Close", None);
let prompt = if keep { prompt.keep_open_on_escape() } else { prompt };
action = prompt
.show(ui.ctx(), true, |ui| {
@@ -300,3 +299,253 @@ fn escape_closes_a_prompt_unless_it_keeps_the_card_open() {
assert_eq!(action, if keep { Action::None } else { Action::Cancel }, "keep_open_on_escape={keep}");
}
}
#[test]
fn window_pages_have_shared_metrics_callbacks_and_a_pinned_left_footer_action() {
let previous = crate::theme::is_dark();
for dark in [false, true] {
crate::theme::set_dark(dark);
let ctx = crate::fonts::test_context();
let mut selected = usize::MAX;
let mut drawn = 0;
let pages = [
WindowPage {
icon: "settings",
label: "ui.general",
handle: "test:page:general",
scroll: true,
draw: |ui, state| {
*state = 1;
text(ui, "General", Text::Inline);
},
},
WindowPage {
icon: "orbit",
label: "ui.navigation",
handle: "test:page:navigation",
scroll: true,
draw: |ui, state| {
*state = 2;
text(ui, "Navigation", Text::Inline);
},
},
];
for _ in 0..3 {
scenario::clear_handles();
crate::test_support::frame(
&ctx,
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 800.0))),
focused: true,
..Default::default()
},
|ui| {
Window::new(ui.id().with("pages"), "settings", "Preferences").cards(3.0).show_pages(
ui.ctx(),
&mut selected,
&pages,
&mut drawn,
|ui| {
button(ui, "Restore defaults", Button::Normal);
},
);
},
);
}
assert_eq!((selected, drawn), (1, 2), "hostile page index is bounded before callback dispatch");
let nav = scenario::rect_of("dialog:pages").unwrap();
let header = scenario::rect_of("dialog:header").unwrap();
let footer = scenario::rect_of("dialog:footer").unwrap();
assert_eq!(nav.width(), 188.0);
assert_eq!(header.height(), 40.0);
assert_eq!(footer.height(), 48.0);
assert_eq!(nav.top(), header.bottom(), "no body inset around navigation");
assert_eq!(scenario::rect_of("test:page:general").unwrap().height(), 32.0);
assert!(footer.top() >= nav.bottom());
let left = scenario::rect_of("dialog:button::Restore defaults").unwrap();
let cancel = scenario::rect_of("dialog:cancel").unwrap();
assert!(footer.contains_rect(left) && left.right() < cancel.left());
let page = scenario::handle_at("test:page:general").unwrap();
for down in [true, false] {
crate::test_support::frame(
&ctx,
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 800.0))),
focused: true,
events: pointer(page, down),
..Default::default()
},
|ui| {
Window::new(ui.id().with("pages"), "settings", "Preferences").cards(3.0).show_pages(
ui.ctx(),
&mut selected,
&pages,
&mut drawn,
|_| {},
);
},
);
}
assert_eq!((selected, drawn), (0, 1), "click dispatches the declared page");
}
crate::theme::set_dark(previous);
}
#[test]
fn confirm_routes_enter_escape_selected_answers_and_blocks_background_clicks() {
for (key, valid, selected, expected) in [
(egui::Key::Enter, true, Action::Ok, Action::Ok),
(egui::Key::Enter, false, Action::Ok, Action::None),
(egui::Key::Enter, true, Action::Apply, Action::Apply),
(egui::Key::Escape, true, Action::Ok, Action::Cancel),
] {
let ctx = crate::fonts::test_context();
let mut action = Action::None;
let mut background = false;
let mut at = egui::Pos2::ZERO;
for pass in 0..5 {
let events = match pass {
2 => pointer(at, true),
3 => pointer(at, false),
4 => crate::test_support::key(key),
_ => vec![],
};
scenario::clear_handles();
crate::test_support::frame(
&ctx,
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0))),
focused: true,
events,
..Default::default()
},
|ui| {
let button = button(ui, "Background", Button::Normal);
at = button.rect.center();
background |= button.clicked();
action = Confirm::new(ui.id().with("modal"), "status_warning", "Save changes?")
.tone(Tone::Warning)
.actions("Save", "Cancel", Some("Don't Save"))
.selected(selected)
.detail("Sample Plate")
.show(ui.ctx(), valid, |ui| {
text(ui, "Your changes will be lost.", Text::Report("message", false));
})
.1;
},
);
}
assert!(!background, "modal intercepts background pointer events");
assert_eq!(action, expected, "{key:?}, valid={valid}, selected={selected:?}");
assert_eq!(scenario::rect_of("confirm:disc").unwrap().size(), egui::vec2(36.0, 36.0));
let (ghost, cancel, primary) =
(scenario::rect_of("dialog:apply").unwrap(), scenario::rect_of("dialog:cancel").unwrap(), scenario::rect_of("dialog:ok").unwrap());
assert!(ghost.right() < cancel.left() && cancel.right() < primary.left());
assert!(scenario::rect_of("dialog:note:confirm_detail").is_some());
}
}
#[test]
fn destructive_confirm_paints_error_primary_with_readable_on_colour_in_both_themes() {
let previous = crate::theme::is_dark();
for dark in [false, true] {
crate::theme::set_dark(dark);
let ctx = crate::fonts::test_context();
let mut output = None;
for _ in 0..3 {
output = Some(crate::test_support::frame(
&ctx,
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0))),
focused: true,
..Default::default()
},
|ui| {
Confirm::new(ui.id().with("delete"), "delete", "Delete").tone(Tone::Danger).actions("Delete", "Cancel", None).show(
ui.ctx(),
true,
|ui| {
text(ui, "These features will be deleted:", Text::Report("message", false));
},
);
},
));
}
let t = Tokens::get();
let primary = scenario::rect_of("dialog:ok").unwrap();
let shapes = output.unwrap().shapes;
let mut painted_fill = false;
for shape in &shapes {
crate::test_support::each_shape(&shape.shape, &mut |s| {
painted_fill |= matches!(s, egui::Shape::Rect(r) if r.rect == primary && r.fill == t.form_error);
});
}
assert!(painted_fill, "{dark}: primary must use form_error");
let ink = if crate::theme::contrast_ratio(t.on_accent, t.form_error) >= 4.5 { t.on_accent } else { t.tab_on_fill_dark };
assert!(crate::theme::contrast_ratio(ink, t.form_error) >= 4.5);
let mut painted_ink = false;
for shape in &shapes {
crate::test_support::each_shape(&shape.shape, &mut |s| {
painted_ink |= matches!(s, egui::Shape::Text(text) if primary.contains(text.pos) && text.galley.job.text == "Delete"
&& text.galley.job.sections.iter().all(|section| section.format.color == ink));
});
}
assert!(painted_ink, "{dark}: destructive primary text must use readable on-colour");
}
crate::theme::set_dark(previous);
}
#[test]
fn preferences_preserves_every_page_and_footer_in_both_themes() {
let previous = crate::theme::is_dark();
for dark in [false, true] {
crate::theme::set_dark(dark);
let mut h = crate::scenario::Harness::new();
h.app.preferences.theme = if dark { "dark" } else { "light" }.into();
h.app.home.open = false;
for (index, page) in crate::prefs::PAGES.iter().enumerate() {
crate::prefs::open_at(&mut h.app, index);
h.frames(3);
assert_eq!(h.app.prefs_window.section, index);
let nav = scenario::rect_of("dialog:pages").unwrap();
let row = scenario::rect_of(&format!("prefs:page:{page}")).unwrap();
assert!(nav.contains_rect(row), "{dark}: {page} stays visible");
let window = scenario::rect_of("prefs:window").unwrap();
for action in ["prefs:ok", "prefs:apply", "prefs:cancel"] {
assert!(window.contains_rect(scenario::rect_of(action).unwrap()), "{dark}: {page}: {action}");
}
assert!(scenario::rect_of("prefs:page_body").is_some());
assert!(h.widget(h.app.tr("ui.restore_defaults")).is_some());
}
}
crate::theme::set_dark(previous);
}
#[test]
fn window_footer_is_optional_and_can_contain_only_a_left_action() {
for left in [false, true] {
let ctx = crate::fonts::test_context();
for _ in 0..3 {
scenario::clear_handles();
frame(&ctx, vec![], |ui| {
let window = Window::new(ui.id().with("optional_footer"), "settings", "Preferences").actions("", "", None);
if left {
window.show_with_left(
ui.ctx(),
true,
|_| {},
|ui| {
button(ui, "Restore defaults", Button::Normal);
},
);
} else {
window.show(ui.ctx(), true, |_| {});
}
});
}
assert_eq!(scenario::rect_of("dialog:footer").is_some(), left);
assert_eq!(scenario::rect_of("dialog:button::Restore defaults").is_some(), left);
assert!(scenario::handle_at("dialog:ok").is_none() && scenario::handle_at("dialog:cancel").is_none());
assert!(scenario::handle_at("dialog:close").is_some());
}
}
+98
View File
@@ -786,3 +786,101 @@ fn disclosure_guard_distinguishes_overflow_and_playback_from_conditional_folds()
assert_eq!(disclosure_guard(r#"fn show(ui: &mut Ui) { ui.label(if collapsed { "«" } else { "»" }); }"#).found.len(), 1);
assert_eq!(disclosure_guard("fn show(ui: &mut Ui) { egui::collapsing_header::paint_default_icon(ui, open, response); }").found.len(), 1);
}
/// System windows and confirms may compose content, but never define another card frame.
fn window_frame_violations(source: &str) -> Vec<String> {
#[derive(Default)]
struct Frames {
found: Vec<String>,
aliases: Vec<String>,
}
impl<'ast> Visit<'ast> for Frames {
fn visit_item(&mut self, item: &'ast syn::Item) {
let attrs = match item {
syn::Item::Mod(i) => &i.attrs,
syn::Item::Fn(i) => &i.attrs,
_ => return visit::visit_item(self, item),
};
if !attrs
.iter()
.any(|a| a.path().is_ident("test") || (a.path().is_ident("cfg") && a.parse_args::<syn::Path>().is_ok_and(|p| p.is_ident("test"))))
{
visit::visit_item(self, item);
}
}
fn visit_use_tree(&mut self, tree: &'ast syn::UseTree) {
if let syn::UseTree::Rename(rename) = tree
&& matches!(rename.ident.to_string().as_str(), "Frame" | "Window" | "Modal")
{
self.aliases.push(rename.rename.to_string());
}
visit::visit_use_tree(self, tree);
}
fn visit_expr_path(&mut self, expr: &'ast syn::ExprPath) {
let names: Vec<_> = expr.path.segments.iter().map(|s| s.ident.to_string()).collect();
if !names.iter().any(|s| s == "ui_kit")
&& names.iter().any(|s| matches!(s.as_str(), "Frame" | "Window" | "Modal" | "shell_card" | "dock_frame") || self.aliases.contains(s))
{
self.found.push(names.join("::"));
}
visit::visit_expr_path(self, expr);
}
}
let ast = syn::parse_file(source).unwrap();
let mut frames = Frames::default();
// Collect aliases first, including imports below a caller.
for item in &ast.items {
if let syn::Item::Use(u) = item {
frames.visit_use_tree(&u.tree);
}
}
frames.visit_file(&ast);
frames.found
}
#[test]
fn system_windows_and_prompts_only_use_kit_frames_without_allowances() {
fn scan(dir: &Path, failures: &mut Vec<String>) {
for entry in std::fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
if path.file_name().is_none_or(|n| n != "ui_kit") {
scan(&path, failures);
}
} else if path.extension().is_some_and(|n| n == "rs") {
let source = std::fs::read_to_string(&path).unwrap();
if source.contains("ui_kit::Window::") || source.contains("ui_kit::Confirm::") {
let found = window_frame_violations(&source);
if !found.is_empty() {
failures.push(format!("{}: {found:?}", path.display()));
}
}
if path.file_name().is_none_or(|n| n != "ui_kit_guard_tests.rs") {
assert!(!source.contains("ui_kit::Prompt"), "{}: use Window or Confirm", path.display());
}
}
}
}
let mut failures = Vec::new();
scan(&Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut failures);
assert!(failures.is_empty(), "No caller-defined window frames:\n{}", failures.join("\n"));
assert!(ALLOWED.is_empty());
}
#[test]
fn window_guard_rejects_frames_aliases_and_native_windows_but_accepts_kit_composition() {
let found = window_frame_violations(
r#"
use egui::{Frame as Card, Window as Popup, Modal as Alert};
fn raw(ui: &mut Ui) {
Card::NONE.show(ui, |_| {});
egui::Frame::group(ui.style());
Popup::new("Title"); Alert::new(id);
crate::frame::shell_card(fill); crate::frame::dock_frame(ctx, side);
}
fn kit() { crate::ui_kit::Window::new(id, icon, title); crate::ui_kit::Confirm::new(id, icon, title); }
#[cfg(test)] mod tests { fn ignored() { egui::Frame::NONE; } }
"#,
);
assert_eq!(found.len(), 6, "{found:?}");
}
+2 -2
View File
@@ -817,10 +817,10 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
let id = egui::Id::new("sc_update");
let mut also_download = false;
let (closed, answer) =
ui_kit::Prompt::new(id, "update", crate::i18n::tr("update.title")).cards(1.7).actions(ok, cancel, apply).show(ctx, true, |ui| {
ui_kit::Window::new(id, "update", crate::i18n::tr("update.title")).cards(1.7).actions(ok, cancel, apply).show(ctx, true, |ui| {
ui_kit::text(ui, &crate::i18n::format("update.available", &[("version", release.version())]), ui_kit::Text::Report("available", false));
ui_kit::text(ui, &crate::i18n::format("update.you_have", &[("version", current_version())]), ui_kit::Text::Note("have"));
egui::Frame::group(ui.style()).show(ui, |ui| {
ui_kit::list_frame(ui, "release_notes", |ui| {
ui.set_width(ui.available_width());
egui::ScrollArea::vertical().max_height(260.0).auto_shrink([false, true]).show(ui, |ui| {
if release.notes.trim().is_empty() {
@@ -10,17 +10,19 @@
{"expect": {"shown": "Don't Save", "quit_requested": false}},
{"key": "Escape"},
{"expect": {"not_shown": "Don't Save", "quitting": false, "quit_requested": false}},
{"note": "Left and Right pick a button as laid out (Cancel, Don't Save, Save from the left; Save first, stopping at the ends) and Enter gives it."},
{"note": "Left and Right pick a button as laid out (Don't Save, Cancel, Save from the left; Save first, stopping at the ends) and Enter gives it."},
{"call": "app.quit"},
{"key": "ArrowLeft"},
{"key": "ArrowLeft"},
{"key": "ArrowLeft"},
{"key": "ArrowRight"},
{"key": "Enter"},
{"expect": {"not_shown": "Don't Save", "quitting": false, "quit_requested": false, "bodies": 1}},
{"call": "app.quit"},
{"key": "ArrowLeft"},
{"key": "ArrowLeft"},
{"key": "ArrowRight"},
{"key": "ArrowLeft"},
{"key": "Enter"},
{"expect": {"quit_requested": true}}
]
+21 -8
View File
@@ -21,10 +21,21 @@ preferences, manager cards, prompts and the sketch palette. Import through
pinned actions, compute status and keyboard routing. `wide()` uses three card
widths. `feature_frame` and `palette_frame` retain docked/floating surfaces.
`FeatureOptions::apply_label` adds Apply; `Panel::actions` supplies custom labels.
- `Prompt` owns floating confirmation/property cards. Use `actions(ok, cancel,
apply)`, `anchor`/`placed`, `cards`, `selected`, `fields` and
`keep_open_on_escape` for existing prompt behavior. Empty `ok` omits the primary
action. It returns `(close_pressed, Action)`.
- `Window` composes the shared Panel frame with a 40 pt icon/title/close header,
padded content and optional 48 pt footer. `show_with_left` pins a left action beside
the right-aligned buttons. `show_pages` accepts declarative `WindowPage` entries
(existing icon, i18n label key, stable handle, scroll policy and draw callback).
Its 188 pt soft page list has 32 pt icon/label rows, selected tint/ink and a divider.
All nine existing Preferences pages retain their order, settings and handles.
`actions`, `anchor`/`placed`, `cards`, `fields` and `keep_open_on_escape` retain
existing window behavior. Empty action labels omit the footer.
- `Confirm` is an input-blocking modal using the same card frame and footer controls.
It shows a 36 pt icon disc in warning, danger or info tone, a title, caller-supplied
message and optional monospace `detail`, above a 52 pt footer. `actions(primary, cancel, left_ghost)`
places the optional third action at the left. Danger uses `form_error` with a
contrast-selected on-colour; other primaries use blue. Enter invokes the selected
answer (primary by default) when valid; Esc cancels. It retains close, answer and
message scenario handles. The old `Prompt` element is removed.
- Callers supply data and enabled state, then dispatch existing commands. Editors
leave their established completion, Enter, Tab and commit ownership unchanged.
- Every text input uses the kit's shared `text_input` policy: symmetric horizontal
@@ -40,10 +51,12 @@ preferences, manager cards, prompts and the sketch palette. Import through
Module names below describe implementation locations, not caller import paths.
Every inline element/variant has one entry in the light/dark `gallery::ELEMENTS`
table. Panel/Prompt compositions also have dedicated geometry and interaction tests.
table. Panel/Window/Confirm compositions also have dedicated geometry and interaction tests.
| Module / element | Use and options | Main tokens |
| --- | --- | --- |
| panel: `Window`, `WindowPage` | Shared card frame, header, optional page list, bounded content and footer with a left action | `form_header/footer_height`, `form_card_width`, `form_label_width`, `control_height`, `dialog_footer/rule`, `selected_bg/ink`, spacing |
| confirm: `Confirm`, `Tone` | Modal warning/danger/info, title/message, mono detail and ghost/cancel/primary actions | `warning`, `form_error/fill`, `accent_soft`, `form_primary`, `on_accent`, `tab_on_fill_dark`, `font_subtitle`, spacing |
| metrics: `row_height`, `table_row_height`, `header_height` | Shared control/header heights | `control_height`, `space_8`, `form_header_height` |
| layout: `scope`, `row` | Form styling and aligned label/control columns | `form_label_width`, `form_gap_y`, `control_*`, `font_label`, `dialog_label`, `space_4/8` |
| `caption` | Dim caption aligned beneath a control | `font_small`, `text_dim`, label-column tokens |
@@ -133,17 +146,17 @@ that remain outside the kit and why.
## Popup presentation and draft rows
All kit cards use 28 pt controls, a 40 pt title band (14 pt semibold title,
Panel and Window use 28 pt controls, a 40 pt title band (14 pt semibold title,
19 pt command icon and 26 pt close/fold targets), and a 48 pt footer with
28 pt actions. Table rows are `control_height + space_8` (36 pt), independent
of control height. Bodies use 12 pt insets. Width limits and scroll boundaries
remain owned by Panel/Prompt. Titles retain the supplied case.
remain owned by Panel/Window/Confirm. Titles retain the supplied case.
The `form_ink`, `form_dim`, `form_primary`, `form_error` and `form_error_fill`
colour keys match the approved light cards. Dark values follow existing text,
accent and error palette roles; every role is exported by theme files and measured
by the colour-vision checks. Invalid fields include both error text and a tinted
surface. Long variable-height lists can use `Prompt::placed` with a top-left pivot to
surface. Long variable-height lists can use `Window::placed` with a top-left pivot to
keep their painted controls and scenario targets aligned as they grow.
Completion lists use the approved 230 pt minimum width (derived from card and
spacing tokens), show kind labels on the right, selected details beneath
+15
View File
@@ -66,6 +66,21 @@ def review_fixture():
class IconReviewTest(unittest.TestCase):
def test_window_confirm_and_page_list_icons_are_discovered(self):
with review_fixture() as (root, design, get, post):
source = root / 'crates/ui-egui/src/windows.rs'
source.parent.mkdir(parents=True)
source.write_text('''fn show() {
ui_kit::Window::new(egui::Id::new("prefs"), "settings", title);
ui_kit::Confirm::new(id, "status_warning", title);
ui_kit::WindowPage { icon: "orbit", label: "ui.navigation", draw: draw_page };
ui_kit::Window::new(id, variable_icon, "not_an_icon");
}''', encoding='utf-8')
page = get('/')
for icon in ('settings', 'status_warning', 'orbit'):
self.assertIn(f'data-id="{icon}"', page)
self.assertNotIn('data-id="not_an_icon"', page)
def test_runtime_manifest_discovers_variable_ids_and_reports_actual_placeholder(self):
with review_fixture() as (root, design, get, post):
manifest = design / 'requested_icons.txt'