Merge branch 'red/fu-dialogs' into area/ribbon-fw

This commit is contained in:
Martin Ball
2026-11-18 22:53:47 +00:00
13 changed files with 422 additions and 48 deletions
@@ -80,6 +80,7 @@ craft_ui::words! {
left_to_right: "paragraphDialog.leftToRight" = "Left-to-right";
right_to_left: "paragraphDialog.rightToLeft" = "Right-to-left";
mirror_indents: "paragraphDialog.mirrorIndents" = "Mirror indents";
contextual_spacing: "paragraphDialog.contextualSpacing" = "Don't add space between paragraphs of the same style";
inside: "paragraphDialog.inside" = "Inside";
outside: "paragraphDialog.outside" = "Outside";
exceptions: "paragraphDialog.exceptions" = "Formatting exceptions";
@@ -215,6 +216,10 @@ pub struct ParagraphFormat {
/// Mirror indents: Left and Right read Inside and Outside when on. The outer `None` hides it; `Some(None)` is mixed.
#[serde(default, skip_serializing_if = "Option::is_none", with = "shown_or_hidden")]
pub mirror_indents: Option<Option<bool>>,
/// Don't add space between paragraphs of the same style (Word's contextual spacing): the spacing before and after
/// is left out between two paragraphs of one style. The outer `None` hides it; `Some(None)` is mixed.
#[serde(default, skip_serializing_if = "Option::is_none", with = "shown_or_hidden")]
pub contextual_spacing: Option<Option<bool>>,
/// The Line and Page Breaks check boxes. `None` hides the page.
pub breaks: Option<LineBreakOptions>,
/// The Asian Typography check boxes. `None` hides the page.
@@ -809,6 +814,11 @@ impl ParagraphDialog {
}
self.field(ui, scope, Row::At, &words.at, valid);
if let Some(current) = self.format.contextual_spacing
&& let Some(on) = check(ui, &words.contextual_spacing, current)
{
self.format.contextual_spacing = Some(Some(on));
}
}
fn answer(&self, open_tabs: bool) -> ParagraphAnswer {
+7
View File
@@ -146,6 +146,13 @@ fn indents_and_spacing(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
StoryOutput::default()
}
/// Paragraphs that differ in "Don't add space between paragraphs of the same style": the box under the spacing rows is
/// mixed.
#[story(ParagraphDialog, covers = [], drive = Drive::Never)]
fn contextual_spacing_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
hosted(ui, data, (), || ParagraphDialog::new(ParagraphFormat { contextual_spacing: Some(None), ..indented() }).word(true))
}
#[story(ParagraphDialog, covers = [], drive = Drive::Never)]
fn line_and_page_breaks(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
hosted(ui, data, (), || ParagraphDialog::new(indented()).word(true).tab(ParagraphTab::LineAndPageBreaks))
+19 -1
View File
@@ -271,13 +271,31 @@ impl FindReplaceDialog {
self
}
/// Sets the starting options for Match case, Whole words and the rest.
/// Sets the starting options for Match case, Whole words and the rest. An option that only Search Options shows
/// (Match prefix, Match suffix, Ignore punctuation, Ignore white-space, Regular expressions) opens Search Options,
/// so an option that is on is never hidden.
#[must_use]
pub fn options(mut self, options: FindOptions) -> Self {
self.options = options;
self.more |= options.prefix || options.suffix || options.ignore_punctuation || options.ignore_space || options.regex;
self
}
/// Shows `tab` in the open dialog, and puts `query` in Find what when given (Find or Replace asked again with a
/// selection). Replace with, the options, Search Options and the Go To target stay as they are.
pub fn show_tab(&mut self, tab: FindTab, query: Option<String>) {
self.tab = tab;
if let Some(query) = query {
self.query = query;
}
}
/// Replaces Go To's kinds in the open dialog (the document's bookmarks changed, say); the chosen kind and target
/// stay.
pub fn set_go_to_kinds(&mut self, kinds: Vec<GoToKind>) {
self.go_to_kinds = kinds;
}
/// Go To's kinds (Page, Section, Line, Bookmark, Comment, …), the app's.
#[must_use]
pub fn go_to_kinds(mut self, kinds: Vec<GoToKind>) -> Self {
+35 -1
View File
@@ -1,5 +1,6 @@
//! Go To in Find and Replace: the requests the app glue answers.
//! Go To in Find and Replace: the requests the app glue answers; the dialog asked for again while open.
use craft_text::find::FindOptions;
use craft_text::ui::find::{FindReplaceDialog, FindRequest, FindTab, GoToKind};
use craft_ui::dialog::{DialogStack, StackDialog as _};
use craft_ui::runtime::access::Role;
@@ -61,3 +62,36 @@ fn go_to_steps_on_an_empty_page_and_names_a_bookmark() {
fixture.click(&go).idle(4);
assert_eq!(dialog.borrow_mut().take_request(), None, "Go To is disabled without names");
}
// Find and Replace asked for again while open: `show_tab` switches the tab and puts a given Find what in, keeping
// Replace with, the options and Search Options; `set_go_to_kinds` replaces the open dialog's kinds. An option only
// Search Options shows opens it from the start.
#[trial]
fn a_reopened_find_switches_its_tab_and_keeps_what_the_user_set() {
let options = FindOptions { regex: true, ..FindOptions::default() };
let dialog = Rc::new(RefCell::new(FindReplaceDialog::new("cat", FindTab::Replace).word(true).options(options)));
let shown = dialog.clone();
let mut fixture = Fixture::new(move |ui| {
let _ = shown.borrow_mut().show(ui, &DialogStack::default());
});
fixture.idle(30);
assert!(fixture.by_label("Regular expressions").is_some(), "an option only Search Options shows opens Search Options");
let with = fixture.by_role(Role::TEXT_INPUT).get(1).copied().expect("the Replace with field");
fixture.click(&with).type_text("dog").idle(4);
dialog.borrow_mut().show_tab(FindTab::Find, Some("bird".to_owned()));
fixture.idle(4);
let fields = dialog.borrow().json_fields().expect("the dialog's fields");
assert_eq!(fields["tab"], "find", "the tab switches");
assert_eq!(fields["query"], "bird", "a given query replaces Find what");
assert_eq!(fields["with"], "dog", "Replace with stays");
assert_eq!(fields["regex"], true, "the options stay");
assert_eq!(fields["more"], true, "Search Options stays open");
dialog.borrow_mut().show_tab(FindTab::GoTo, None);
dialog.borrow_mut().set_go_to_kinds(vec![GoToKind::named("Bookmark", vec!["Intro".to_owned()], "No bookmarks")]);
fixture.idle(10);
let fields = dialog.borrow().json_fields().expect("the dialog's fields");
assert_eq!(fields["query"], "bird", "without a query Find what stays");
assert_eq!(fields["goToTarget"], "Intro", "the new kinds show: the target names the new bookmark");
}
+26 -1
View File
@@ -1,4 +1,5 @@
//! The Word Paragraph dialog's pages: a check box whose paragraphs differ stays mixed across page switches until clicked.
//! The Word Paragraph dialog's pages: a check box whose paragraphs differ stays mixed across page switches until clicked;
//! the contextual spacing box.
use craft_behavior::Mixed;
use craft_text::ui::character::{AsianTypography, LineBreakOptions, ParagraphDialog, ParagraphFormat, ParagraphTab};
@@ -44,3 +45,27 @@ fn word_paragraph_tabs_leave_mixed_boxes_unset_until_clicked() {
assert_eq!(breaks.widow_control, None, "a box left alone stays unset");
assert_eq!(answer.format.asian.expect("the page is answered").kinsoku, None);
}
/// "Don't add space between paragraphs of the same style" under the spacing rows: shown mixed for paragraphs that
/// differ, a click turns it on, and the answer carries it.
#[trial]
fn a_mixed_contextual_spacing_box_clicked_is_on_in_the_answer() {
const LABEL: &str = "Don't add space between paragraphs of the same style";
let mut format = ParagraphFormat::default();
format.contextual_spacing = Some(None);
let dialog = Rc::new(RefCell::new(ParagraphDialog::new(format).word(true).held_ok()));
let shown = dialog.clone();
let mut fixture = Fixture::new(move |ui| {
let _ = shown.borrow_mut().show(ui, &DialogStack::default());
});
fixture.idle(30);
assert!(matches!(toggled(&fixture, LABEL), Some(Mixed::Mixed)), "paragraphs that differ show the box mixed");
let boxed = fixture.by_label(LABEL).expect("the box is shown");
fixture.click(&boxed).idle(4);
assert!(matches!(toggled(&fixture, LABEL), Some(Mixed::Same(true))), "a click turns the mixed box on");
let ok = fixture.by_label("OK").expect("OK is shown");
fixture.click(&ok).idle(4);
let answer = dialog.borrow_mut().take_ok().expect("OK filed its answer");
assert_eq!(answer.format.contextual_spacing, Some(Some(true)), "the answer carries the box");
}
+1 -1
View File
@@ -484,7 +484,7 @@ impl FooterButton {
}
/// Whether the button can be activated.
pub(crate) const fn is_enabled(&self) -> bool {
pub const fn is_enabled(&self) -> bool {
self.enabled
}
}
@@ -37,9 +37,24 @@ craft_ui::words! {
/// The words a form dialog adds beside the common OK and Cancel.
pub struct FormDialogWords {
preview: "formDialog.preview" = "Preview";
/// The one closing button of a form without OK ([`FormButtons::Close`]).
close: "formDialog.close" = "Close";
}
}
/// The buttons a form dialog's footer starts with, before its [extra buttons](FormDialog::extra_buttons).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FormButtons {
/// OK and Cancel (Reset while Alt is held).
#[default]
OkCancel,
/// No OK: one button with `DialogRole::Cancel`, labelled by [`cancel_label`](FormDialog::cancel_label) or Close.
/// The work is in the extra buttons, whose [`FormOutput::picked`] indexes still start at 2. Enter picks the one
/// enabled extra button with `DialogRole::Accept` when there is one, and does nothing otherwise. Nothing is filed
/// as a held OK, and [`FormCx::accept`] does nothing.
Close,
}
/// The dialog's own undo history of its value while it is open: made on the opening pass, stepped by Undo and Redo.
#[derive(Clone)]
struct History<V>(Option<EditHistory<V>>);
@@ -85,6 +100,7 @@ pub struct FormCx<'a, 'b> {
first: bool,
answers: Vec<HostAnswer>,
requests: &'a mut HostRequests,
accept: bool,
}
impl FormCx<'_, '_> {
@@ -102,6 +118,16 @@ impl FormCx<'_, '_> {
pub fn requests(&mut self) -> &mut HostRequests {
self.requests
}
/// The body's activation is the OK press: a double click or Enter on a grid cell, say. After the body, the dialog
/// takes it as a press of OK while the values can be accepted. Under [`held`](FormDialog::held) it files the values
/// and stays open for the app's answer (nothing while an answer is out); with
/// [`accept_stays_open`](FormDialog::accept_stays_open) it reports the pick and stays open; otherwise it closes as
/// `CloseReason::Activated` with the value. A measuring run and a form without OK ([`FormButtons::Close`]) take
/// none.
pub fn accept(&mut self) {
self.accept = true;
}
}
impl<'b> Deref for FormCx<'_, 'b> {
@@ -127,7 +153,8 @@ pub struct FormOutput<V> {
/// How the dialog closed in this pass; `None` while it stays open.
pub closed: Option<CloseReason>,
/// The index of the footer button picked in this pass, in the order `ResetFooter::buttons` gives them, then the
/// [`extra_buttons`](FormDialog::extra_buttons) from 2 on.
/// [`extra_buttons`](FormDialog::extra_buttons) from 2 on. A [`FormCx::accept`] that leaves the dialog open is
/// OK's pick, 0. Without OK ([`FormButtons::Close`]) Close is 1 and the extras keep their indexes.
pub picked: Option<usize>,
/// The value, the pass the dialog closed as OK while it could be accepted.
pub accepted: Option<V>,
@@ -155,7 +182,10 @@ type ResetWithFn<'a, V> = Box<dyn Fn(&V, &V) -> V + 'a>;
/// `V::default()` each time the dialog opens.
/// - Keys: Enter is OK unless the body owns it or [`enter_confirms`](FormDialog::enter_confirms) is off, Escape cancels. Holding Alt turns Cancel into Reset, which restores
/// the value from when the dialog opened (and runs [`on_reset`](FormDialog::on_reset) for what the body keeps).
/// - The body returns whether the value can be accepted; OK is enabled while it can and `ok_enabled` is true.
/// - The body returns whether the value can be accepted; OK is enabled while it can and `ok_enabled` is true. The
/// body's own activation (a double click on a cell) is OK through [`FormCx::accept`].
/// - [`buttons`](FormDialog::buttons) with [`FormButtons::Close`] leaves out OK, for a form whose work is in its extra
/// buttons.
/// - With [`history`](FormDialog::history), Cmd/Ctrl+Z and Shift+Cmd/Ctrl+Z step the dialog's own value; a drag or a
/// typing run is one step.
/// - The footer goes across the foot, the Preview check box and the footer controls at its start edge; with
@@ -171,6 +201,7 @@ pub struct FormDialog<'a, V: Value + Default> {
open: Option<Bind<'a, bool>>,
ok_label: Option<Label>,
cancel_label: Option<Label>,
buttons: FormButtons,
ok_enabled: bool,
ok_reason: Option<Label>,
alt_resets: bool,
@@ -205,6 +236,7 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
open: None,
ok_label: None,
cancel_label: None,
buttons: FormButtons::OkCancel,
ok_enabled: true,
ok_reason: None,
alt_resets: true,
@@ -251,12 +283,18 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
self
}
/// The second button's label when it is not Cancel.
/// The second button's label when it is not Cancel (Close under [`FormButtons::Close`]).
pub fn cancel_label(mut self, label: impl Into<Label>) -> Self {
self.cancel_label = Some(label.into());
self
}
/// The buttons the footer starts with; [`FormButtons::OkCancel`] by default.
pub fn buttons(mut self, buttons: FormButtons) -> Self {
self.buttons = buttons;
self
}
/// Whether OK can be pressed; Enter does nothing while it cannot.
pub fn ok_enabled(mut self, on: bool) -> Self {
self.ok_enabled = on;
@@ -385,6 +423,7 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
open,
ok_label,
cancel_label,
buttons,
ok_enabled,
ok_reason,
alt_resets,
@@ -422,6 +461,13 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
let name: Arc<str> = title.as_str().into();
let bind = Rc::new(RefCell::new(bind));
// A form without OK has its one closing button and the extras; Enter goes to the enabled Accept-role extra.
let no_ok = buttons == FormButtons::Close;
let enter_extra = extra_buttons.iter().any(|button| button.role() == DialogRole::Accept && button.is_enabled());
let close = no_ok.then(|| {
let label = cancel_label.clone().unwrap_or_else(|| env.words::<FormDialogWords>().close.clone());
std::iter::once(FooterButton::new(label, DialogRole::Cancel)).chain(extra_buttons.iter().cloned()).collect::<Vec<_>>()
});
let reset = ResetFooter::new(ui, cancel_label, alt_resets).extra(extra_buttons);
let mut accept =
FooterButton::new(ok_label.unwrap_or_else(|| common.ok.clone()), DialogRole::Accept).enabled(ok_enabled).stays_open(accept_stays_open_button);
@@ -448,10 +494,13 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
};
let mut dialog = Dialog::new(title)
.closable(closable)
.close_on_enter(ok_enabled && enter_confirms)
.close_on_enter(enter_confirms && if no_ok { enter_extra } else { ok_enabled })
.outer_gesture(outer_gesture)
.side_buttons(side_buttons);
dialog = reset.install(dialog, accept, restore);
dialog = match close {
Some(close) => dialog.buttons(close),
None => reset.install(dialog, accept, restore),
};
if let Some(open) = open {
dialog = dialog.opened(open);
}
@@ -501,6 +550,7 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
let work = RefCell::new(None::<V>);
let requests = RefCell::new(HostRequests::new());
let accepts = Cell::new(ok_enabled);
let body_pick = Cell::new(false);
let shown = dialog.show(ui, |ui, cx| {
// A measuring run sees no answers and no opening pass: the real run that follows still has both.
let measuring = measuring_run;
@@ -521,16 +571,18 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
}
}
}
let (ok, running) = {
let (ok, running, activated) = {
let mut requests = requests.borrow_mut();
let mut form = FormCx {
cx: &mut *cx,
first,
answers: if measuring { Vec::new() } else { std::mem::take(&mut answers) },
requests: &mut requests,
accept: false,
};
let ctx = ui.ctx().clone();
crate::runtime::edit::watch_gestures(&ctx, || body(ui, &mut form, &mut values))
let (ok, running) = crate::runtime::edit::watch_gestures(&ctx, || body(ui, &mut form, &mut values));
(ok, running, form.accept && !measuring && !no_ok)
};
match &opening {
Some(opening) if !measuring => cx.memory::<Opened<V>>().0 = Some(opening.clone()),
@@ -547,6 +599,15 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
}
let can_accept = ok && ok_enabled;
accepts.set(can_accept);
// The body's activation presses OK: a press that stays open is reported as the button's pick (and filed when
// held, below); otherwise it closes with the value.
if activated && can_accept {
if accept_stays_open_button {
body_pick.set(true);
} else {
cx.request_close_as(CloseReason::Activated);
}
}
let edited = cx.memory::<Opened<V>>().0.as_ref().is_some_and(|opened| *opened != values);
ResetFooter::report(cx, edited, can_accept);
if values != before || first {
@@ -565,8 +626,10 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
});
let DialogOutput { response, closed, picked } = shown.output;
// Without OK the dialog's buttons start at Close, which keeps index 1, and the extras keep theirs from 2.
let picked = if no_ok { picked.map(|at| at + 1) } else { picked.or(body_pick.get().then_some(0)) };
let mut accepted = match closed {
Some(CloseReason::Enter | CloseReason::Activated) if accepts.get() && hold.is_none() => work.borrow().clone(),
Some(CloseReason::Enter | CloseReason::Activated) if accepts.get() && hold.is_none() && !no_ok => work.borrow().clone(),
_ => None,
};
if let Some(held) = hold.as_deref_mut() {
@@ -1,7 +1,8 @@
//! Stories of `FormDialog`.
use super::FormDialog;
use super::{FormButtons, FormDialog};
use crate::buttons::Button;
use crate::sections::{DialogRole, FooterButton};
use crate::choice::Checkbox;
use crate::contract::{Bind, Props as _, Show as _, clicked};
use crate::dialog::HeldAnswer;
@@ -38,6 +39,67 @@ fn form_dialog_held(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
output.response.into()
}
/// A held form whose body activation is OK: a double click on a cell files the cell's name, as the OK button does,
/// and the app accepts every name but `"Moon"`.
#[story(FormDialog<'static, bool>, covers = [], drive = Drive::Never)]
fn form_dialog_body_accept(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let mut open = *data.value("open", false);
if clicked(&Button::new("Insert Symbol…").show(ui)) {
open = true;
}
let held = data.note("held", HeldAnswer::<String>::new());
let output = FormDialog::own("Insert Symbol")
.opened(Bind::bound(&mut open))
.held(&mut *held)
.accept_stays_open(true)
.show(ui, |ui, cx, value: &mut String| {
for cell in ["Sun", "Moon", "Star"] {
let shown = Button::new(cell).show(ui);
if clicked(&shown) {
*value = cell.to_owned();
}
if shown.clicks == 2 {
cx.accept();
}
}
!value.is_empty()
});
if let Some(filed) = held.take() {
held.answer(if filed == "Moon" { Err(Label::from("The moon is not in this font.")) } else { Ok(()) });
}
*data.value("open", false) = open;
output.response.into()
}
/// A form without OK: Close, and the Mark (Enter) and Mark All buttons, which count what they marked.
#[story(FormDialog<'static, bool>, covers = [], drive = Drive::Never)]
fn form_dialog_close(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let mut open = *data.value("open", false);
if clicked(&Button::new("Mark Entry…").show(ui)) {
open = true;
}
let mut entry = data.value("entry", "Craft".to_owned()).clone();
let output = FormDialog::new("Mark Entry", Bind::bound(&mut entry))
.opened(Bind::bound(&mut open))
.buttons(FormButtons::Close)
.extra_buttons([FooterButton::new("Mark", DialogRole::Accept), FooterButton::new("Mark All", DialogRole::Other)])
.show(ui, |ui, _, value| {
TextField::new("Entry", Bind::bound(value)).show(ui);
true
});
let marked = match output.picked {
Some(2) => 1,
Some(3) => 10,
_ => 0,
};
*data.value("marked", 0_u32) += marked;
*data.value("open", false) = open;
if let Some(value) = output.value {
*data.value("entry", String::new()) = value;
}
output.response.into()
}
#[story(FormDialog<'static, bool>, covers = [], drive = Drive::Never)]
fn form_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let ok_enabled = *data.value("ok_enabled", true);
@@ -1,7 +1,7 @@
//! `ListManager`: a named list with a name box and a column of buttons that run, edit, create or delete entries.
use crate::contract::{
Bind, CollectionEvent, NoValue, Outcome, Props as _, Remember as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _,
Bind, BodyCx, CollectionEvent, NoValue, Outcome, Props as _, Remember as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _,
};
use crate::dialog::{Dialog, DialogOutput};
use crate::display::{Shade, Text};
@@ -14,11 +14,13 @@ use crate::runtime::words::CommonWords;
use crate::sections::{DialogRole, FooterButton};
use crate::style::TypeRole;
use crate::text::TextField;
use craft_behavior::{DisplayOrder, ItemSource, Selection};
use craft_behavior::{DisplayOrder, EditEvent, ItemSource, Mixed, Selection};
use craft_i18n::Folder;
use egui::{Response, Ui};
use std::borrow::Cow;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
#[cfg(feature = "testing")]
mod stories;
@@ -211,10 +213,12 @@ impl Outcome for ListManagerOutput {
}
}
/// What the dialog keeps while it is open: the text of the name box.
#[derive(Clone, Default)]
struct Session {
name: String,
/// The name box's text in `bind`: empty while a kept binding holds none.
fn text_of(bind: &mut Bind<'_, String>, cx: &mut BodyCx<'_>) -> String {
match bind.reborrow().read(cx) {
Some(Mixed::Same(text)) => text,
_ => String::new(),
}
}
/// The rows as the list's item source: the position in the entries is the key.
@@ -273,6 +277,8 @@ fn is_enabled(action: &ListManagerAction, entries: &[ListManagerEntry], folder:
/// it is enabled, Delete in the list runs the `delete` action, Escape cancels.
/// - Actions are the buttons in a column beside the list: the first action, Cancel, then the other actions in the
/// given order. The app replaces `entries` between passes; the name box keeps its text.
/// - The name box's text is one binding: the caller's with [`name_box`](ListManager::name_box), else the dialog's
/// memory, which each open starts from the `name` prop.
#[must_use = "show the dialog with `show`"]
#[derive(crate::contract::Pattern, crate::contract::Props)]
pub struct ListManager<'a> {
@@ -289,9 +295,12 @@ pub struct ListManager<'a> {
/// The name box also filters the rows to the names that match it.
#[prop]
searchable: bool,
/// The name the box opens with, with its entry selected.
/// The name the box opens with, with its entry selected, while the dialog keeps the text (no
/// [`name_box`](ListManager::name_box)).
#[prop(into)]
name: Option<String>,
/// The caller's binding of the name box's text.
name_box: Option<Bind<'a, String>>,
/// Binds the open state to `open`.
#[prop(name = "opened")]
open: Option<Bind<'a, bool>>,
@@ -313,6 +322,14 @@ impl<'a> ListManager<'a> {
self
}
/// Binds the name box's text to `bind`: the caller reads what the user typed and sets the text, which the box
/// shows on the next pass. The `name` prop does not apply then.
#[must_use]
pub fn name_box(mut self, bind: Bind<'a, String>) -> Self {
self.name_box = Some(bind);
self
}
/// A list manager titled `title` whose name box is labelled `name_label` ("Macro name:").
pub fn new(
title: impl Into<Label>,
@@ -329,6 +346,7 @@ impl<'a> ListManager<'a> {
note: None,
searchable: false,
name: None,
name_box: None,
open: None,
name_check: None,
cancel_label: None,
@@ -338,8 +356,11 @@ impl<'a> ListManager<'a> {
/// Shows the dialog.
pub fn show(self, ui: &mut Ui) -> ListManagerOutput {
let ListManager { title, name_label, entries, actions, empty, note, searchable, name, open, name_check, cancel_label, under } = self;
let ListManager { title, name_label, entries, actions, empty, note, searchable, name, name_box, open, name_check, cancel_label, under } = self;
let under = RefCell::new(under);
// The dialog keeps the text unless the caller binds it; a kept text starts each open from `name`.
let kept = name_box.is_none();
let name_box = Rc::new(RefCell::new(name_box.unwrap_or_else(Bind::kept)));
let env = Env::of(ui);
let words = env.words::<ListManagerWords>();
let common = env.words::<CommonWords>();
@@ -363,10 +384,11 @@ impl<'a> ListManager<'a> {
})
.collect();
buttons.push(FooterButton::new(cancel_label.unwrap_or_else(|| common.cancel.clone()), DialogRole::Cancel));
let settled = Rc::clone(&name_box);
let mut dialog = Dialog::new(title.clone()).collection_body().close_on_enter(false).side_buttons(true).buttons(buttons).settle_buttons(
move |cx, buttons| {
let folder = cx.env.folder();
let typed = cx.memory::<Session>().name.clone();
let typed = text_of(&mut settled.borrow_mut(), cx);
for (button, action) in buttons.iter_mut().zip(actions) {
button.set_enabled(is_enabled(action, entries, &folder, &typed, name_check));
}
@@ -380,26 +402,23 @@ impl<'a> ListManager<'a> {
let activated = Cell::new(None::<usize>);
let typed = RefCell::new(String::new());
let shown = dialog.show(ui, |ui, cx| {
let mut session = cx.memory::<Session>().clone();
if cx.appeared()
&& let Some(name) = &name
{
session.name.clone_from(name);
}
let session = RefCell::new(session);
let mut bind = name_box.borrow_mut();
let before = text_of(&mut bind, cx);
let opened = if kept && cx.appeared() { name.clone().unwrap_or_default() } else { before.clone() };
let text = RefCell::new(opened);
Stack::new()
.header(|ui, _| {
let mut session = session.borrow_mut();
let mut text = text.borrow_mut();
Field::new(name_label.clone()).show(ui, |ui, _| {
TextField::new(name_label.clone(), Bind::bound(&mut session.name)).select_on_focus().drives(list_id).show(ui);
TextField::new(name_label.clone(), Bind::bound(&mut *text)).select_on_focus().drives(list_id).show(ui);
});
})
.footer(|ui, _| {
let session = session.borrow();
let text = text.borrow();
if let Some(under) = under.borrow_mut().as_mut() {
under(ui);
}
if let Some(entry) = entries.iter().find(|entry| is_named(entry, &folder, &session.name)) {
if let Some(entry) = entries.iter().find(|entry| is_named(entry, &folder, &text)) {
Text::new(words.description.clone()).show(ui);
Text::new(entry.description.clone()).shade(Shade::Muted).show(ui);
}
@@ -408,8 +427,8 @@ impl<'a> ListManager<'a> {
}
})
.show(ui, |ui, _| {
let mut session = session.borrow_mut();
let current = entries.iter().position(|entry| is_named(entry, &folder, &session.name));
let mut text = text.borrow_mut();
let current = entries.iter().position(|entry| is_named(entry, &folder, &text));
let mut selection = current.map_or_else(Selection::default, Selection::single);
let source = Rows(entries);
let mut list = List::new(title.clone())
@@ -422,7 +441,7 @@ impl<'a> ListManager<'a> {
list = list.empty(empty.clone());
}
if searchable {
list = list.filter(&session.name, |at| Label::from(entries[*at].name.clone()));
list = list.filter(text.as_str(), |at| Label::from(entries[*at].name.clone()));
}
let events = list
.show_items(ui, &source, &mut |at, _| {
@@ -438,34 +457,37 @@ impl<'a> ListManager<'a> {
if picked != current
&& let Some(at) = picked
{
session.name.clone_from(&entries[at].name);
text.clone_from(&entries[at].name);
}
for event in events {
match event {
CollectionEvent::Activate(at) => {
session.name.clone_from(&entries[at].name);
let first = actions.first().filter(|action| is_enabled(action, entries, &folder, &session.name, name_check));
text.clone_from(&entries[at].name);
let first = actions.first().filter(|action| is_enabled(action, entries, &folder, &text, name_check));
activated.set(first.map(|_| 0));
}
CollectionEvent::Delete(rows) => {
if let Some(at) = rows.first() {
session.name.clone_from(&entries[*at].name);
text.clone_from(&entries[*at].name);
}
let delete = actions.iter().position(|action| action.id == DELETE);
activated.set(delete.filter(|at| is_enabled(&actions[*at], entries, &folder, &session.name, name_check)));
activated.set(delete.filter(|at| is_enabled(&actions[*at], entries, &folder, &text, name_check)));
}
_ => {}
}
}
});
let session = session.into_inner();
typed.borrow_mut().clone_from(&session.name);
let text = text.into_inner();
if text != before {
let event = EditEvent::set(Mixed::Same(before), text.clone(), Arc::from(name_label.as_str()), None);
let _ = bind.reborrow().write(cx, &event);
}
typed.borrow_mut().clone_from(&text);
if let Some(at) = activated.get()
&& actions[at].closes
{
cx.request_close_as(CloseReason::Activated);
}
*cx.memory::<Session>() = session;
});
let DialogOutput { response, closed, picked } = shown.output;
@@ -8,6 +8,7 @@ use crate::layout_components::Stack;
use crate::runtime::env::Env;
use crate::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
use std::cell::Cell;
fn entries() -> Vec<ListManagerEntry> {
vec![
@@ -31,6 +32,35 @@ fn list_manager(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
.into()
}
/// A list manager whose name box the caller owns: the story keeps the name, and a button under the list sets it on
/// the next pass, as a script sets the Macros dialog's name. The dialog opens from its button.
#[story(ListManager<'static>, covers = [], drive = Drive::Never)]
fn list_manager_name_box(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let words = Env::of(ui).words::<ListManagerWords>();
let mut name = data.value("name", String::new()).clone();
let mut open = *data.value("open", false);
if clicked(&Button::new("Macros…").show(ui)) {
open = true;
}
let first = Cell::new(false);
let actions = vec![ListManagerAction::run(&words), ListManagerAction::create(&words)];
let shown = ListManager::new("Macros", "Macro name:", entries(), actions)
.name_box(Bind::bound(&mut name))
.under_list(|ui| {
if clicked(&Button::new("Name the first macro").show(ui)) {
first.set(true);
}
})
.opened(Bind::bound(&mut open))
.show(ui);
if first.get() {
name = "Align Layers".to_owned();
}
*data.value("name", String::new()) = name;
*data.value("open", false) = open;
shown.into()
}
/// A bookmark name is valid while it is not empty and fits the name box.
fn bookmark_name(name: &str) -> bool {
!name.is_empty() && name.chars().count() <= 32
@@ -20,7 +20,7 @@ mod preview;
pub use dialog::{
BelowRows, HostedParamDialog, ParamDialog, ParamDialogOutput, ParamDialogWords, ParamLayout, ParamResult, ResetFooter, ResetPick, set_param_field,
};
pub use form::{FormCx, FormDialog, FormDialogWords, FormOutput};
pub use form::{FormButtons, FormCx, FormDialog, FormDialogWords, FormOutput};
pub use host_requests::{HostRequests, PreviewRequest};
pub use path_row::{PathRow, PathRowOutput, PathRowWords};
pub use preview::{
@@ -6,10 +6,11 @@ use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, Outcome as _, Props as _, Role, SaveKey, Show as _, clicked};
use craft_ui::choice::Checkbox;
use craft_ui::dialog::{DialogHost, DialogResult, HeldAnswer, HeldOk, dialog_id};
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, FormDialog, HostedParamDialog, Param, ParamDialog, ParamKind, ParamLayout, ParamResult};
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, FormButtons, FormDialog, HostedParamDialog, Param, ParamDialog, ParamKind, ParamLayout, ParamResult};
use craft_ui::patterns::presets::PresetRow;
use craft_ui::runtime::env::Label;
use craft_ui::runtime::overlay::CloseReason;
use craft_ui::sections::{DialogRole, FooterButton};
use craft_ui::testing::relations::{above, left_of};
use craft_ui::testing::{Fixture, trial};
use egui::load::SizedTexture;
@@ -282,6 +283,80 @@ fn a_held_ok_refused_keeps_the_dialog_open_and_an_accepted_one_closes() {
assert!(!fixture.tree().is_disabled_key(ok.node), "OK is enabled again");
}
// The body's activation is the OK press: under `held`, a double click on a cell that calls `FormCx::accept` files the
// values once, in a frame that runs twice too, and the dialog stays open waiting with OK disabled.
#[trial]
fn a_body_accept_files_a_held_ok_once_and_waits() {
let (held, twice, filed, closed) =
(Rc::new(RefCell::new(HeldAnswer::<String>::new())), Rc::new(Cell::new(false)), Rc::new(RefCell::new(Vec::new())), Rc::new(Cell::new(false)));
let (state, again, files, ended) = (Rc::clone(&held), Rc::clone(&twice), Rc::clone(&filed), Rc::clone(&closed));
let mut fixture = Fixture::new(move |ui| {
let mut held = state.borrow_mut();
let shown = FormDialog::own("Insert Symbol").held(&mut held).show(ui, |ui, cx, value: &mut String| {
let cell = Button::new("Sun").show(ui);
if clicked(&cell) {
*value = "Sun".to_owned();
}
if cell.clicks == 2 {
cx.accept();
}
!value.is_empty()
});
if let Some(values) = held.take() {
files.borrow_mut().push(values);
}
if shown.closed.is_some() {
ended.set(true);
}
if again.get() && ui.ctx().current_pass_index() == 0 {
ui.ctx().request_discard("the frame runs twice");
}
});
fixture.idle(10);
let cell = fixture.by_label("Sun").expect("the body's cell");
fixture.click(&cell);
assert!(filed.borrow().is_empty(), "a single click files nothing");
twice.set(true);
fixture.click(&cell);
assert_eq!(fixture.passes(), 2, "the frame ran a second pass");
twice.set(false);
fixture.idle(4);
assert_eq!(*filed.borrow(), ["Sun"], "the double click files the values once");
assert!(held.borrow().is_waiting(), "the filed values wait for the app's answer");
assert!(!closed.get(), "a held accept keeps the dialog open");
let ok = fixture.by_label("OK").expect("the OK button");
assert!(fixture.tree().is_disabled_key(ok.node), "OK waits disabled for the answer");
}
// A form without OK shows none, and Enter picks its one Accept-role extra, which keeps its index after Close.
#[trial]
fn a_form_without_ok_shows_none_and_enter_picks_its_accept_extra() {
let (picked, closed) = (Rc::new(RefCell::new(Vec::new())), Rc::new(Cell::new(false)));
let (picks, ended) = (Rc::clone(&picked), Rc::clone(&closed));
let mut fixture = Fixture::new(move |ui| {
let shown = FormDialog::own("Mark Entry")
.buttons(FormButtons::Close)
.extra_buttons([FooterButton::new("Mark All", DialogRole::Other), FooterButton::new("Mark", DialogRole::Accept)])
.show(ui, |ui, _, value: &mut bool| {
Checkbox::new(Bind::bound(value)).label("Bold").show(ui);
true
});
picks.borrow_mut().extend(shown.picked);
if shown.closed.is_some() {
ended.set(true);
}
});
fixture.idle(10);
assert!(fixture.by_label("OK").is_none(), "a form without OK shows none");
assert!(fixture.by_label("Close").is_some(), "its one closing button is Close");
// Focus on the check box, so Enter goes to the footer's default button rather than a focused one.
let bold = fixture.by_label("Bold").expect("the body's check box");
fixture.click(&bold).idle(2);
fixture.key(Key::Enter, Modifiers::NONE).idle(4);
assert_eq!(*picked.borrow(), [3], "Enter picks Mark, the second extra");
assert!(!closed.get(), "the extra keeps the dialog open");
}
// A dialog the app opens again under the same key, in the pass it takes the first one's Cancel, shows and answers.
#[trial]
fn a_hosted_dialog_reopened_under_the_same_key_opens() {
@@ -1,10 +1,12 @@
//! `ListManager`'s action rules: a name check, a button that never enables, the Cancel label and the section under
//! the list.
//! the list; a name box the caller binds.
use craft_ui::patterns::form_dialogs::{ActionEnabled, ListManager, ListManagerAction, ListManagerEntry};
use craft_ui::display::Text;
use craft_ui::contract::Show as _;
use craft_ui::contract::{Bind, Show as _};
use craft_ui::testing::{Fixture, trial};
use std::cell::RefCell;
use std::rc::Rc;
/// A name is valid while it is not empty and holds no digit.
fn plain_name(name: &str) -> bool {
@@ -68,3 +70,29 @@ fn a_valid_name_action_follows_the_name_check_and_a_never_action_stays_off() {
assert!(fixture.by_label("Close").is_some(), "cancel_label names the second button");
assert!(fixture.by_label("Cancel").is_none(), "Cancel is replaced");
}
// A bound name box is the caller's string both ways: a caller write shows in the box on the next pass and the buttons
// follow it, and what the user types lands in the caller's string.
#[trial]
fn a_bound_name_box_shows_the_callers_writes_and_takes_the_typed_name() {
let name = Rc::new(RefCell::new(String::new()));
let held = Rc::clone(&name);
let mut fixture = Fixture::new(move |ui| {
let actions = vec![ListManagerAction::new("add", "Add", ActionEnabled::OnNewName).keeps_open()];
let entries = vec![ListManagerEntry::new("a", "Alpha")];
let mut name = held.borrow_mut();
let _ = ListManager::new("Marks", "Name:", entries, actions).name_box(Bind::bound(&mut *name)).show(ui);
});
fixture.idle(10);
*name.borrow_mut() = "Gamma".to_owned();
fixture.idle(4);
let field = fixture.by_label("Name:").expect("the name box");
assert_eq!(fixture.tree().value_of(field.node), Some("Gamma"), "the caller's write shows in the box");
assert!(enabled(&fixture, "Add"), "the buttons follow the caller's name");
fixture.click(&field).idle(2);
fixture.key(egui::Key::A, egui::Modifiers::COMMAND).idle(2);
fixture.type_text("Alpha").idle(4);
assert_eq!(*name.borrow(), "Alpha", "the typed name is in the caller's string");
assert!(!enabled(&fixture, "Add"), "an existing name disables Add");
}