mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-30 18:27:00 +01:00
dialogs-w3: net change of 5 commits
- dialogs-w3: written by an agent - dialogs-w3: finished by an agent - dialogs-w3: finished by an agent - dialogs-w3: finished by an agent - dialogs-w3: review fixes (review-1)
This commit is contained in:
1 parent
e362defade
commit
e6dbf86f8f
10 files changed
+497
-102
No files matched your search
@@ -17,7 +17,7 @@ plain text and a language and return what layout needs before it shapes and plac
|
||||
| `ui::editor` | `ui` | `TextEditor` and `TextEditorTool`: the text editor on a canvas over a `TextEditorHost`; input methods through craft-ui's `Composer`. Caret and underline sizes are the `text_editor.*` tokens |
|
||||
| `ui::character` | `ui` | `CharacterControls` and `ParagraphControls`: Photoshop's Character and Paragraph panels |
|
||||
| `ui::style_panel` | `ui` | `TextStylesPanel`: the Character Styles and Paragraph Styles panels |
|
||||
| `ui::spelling` | `ui` | `CheckSpellingDialog` and the user's words as a settings section |
|
||||
| `ui::spelling` | `ui` | `CheckSpellingDialog`: repeated-word deletion, layer or document scope, a caption note and modal or modeless display; the user's words as a settings section |
|
||||
| `ui::ruler`, `ui::tabs_dialog`, `ui::notes`, `ui::columns`, `ui::hyperlink` | `ui` | The paged-text controls: the text ruler, Tabs dialog, notes editor, Columns and Hyperlink dialogs |
|
||||
| `ui::find` | `ui` and `find` | The find bar and Find and Replace |
|
||||
| | `font-picker` | The Character controls' family field is craft-font-manager's font picker |
|
||||
|
||||
@@ -27,15 +27,15 @@ use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{
|
||||
Bind, CollectionEvent, NoValue, Outcome, Pad, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing,
|
||||
};
|
||||
use craft_ui::dialog::{ButtonPlace, Dialog, DialogId, DialogOutput, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::dialog::{ButtonPlace, Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::form::Field;
|
||||
use craft_ui::list::{List, ListRow};
|
||||
use craft_ui::notices::{Notice, NoticeLayout};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::overlay::CloseReason;
|
||||
use craft_ui::sections::{DialogRole, FooterButton};
|
||||
use craft_ui::style::SurfaceKind;
|
||||
use craft_ui::style::{SurfaceKind, TypeRole};
|
||||
use craft_ui::text::TextField;
|
||||
use egui::{Context, Response, Ui};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -154,15 +154,14 @@ pub enum SpellingAction {
|
||||
impl SpellingItem {
|
||||
/// Marks a repeated word with the range Delete removes, in the app's units.
|
||||
#[must_use]
|
||||
pub fn repeated(self, delete: Range<usize>) -> Self {
|
||||
let _ = delete;
|
||||
todo!("dl.F15")
|
||||
pub fn repeated(mut self, delete: Range<usize>) -> Self {
|
||||
self.delete = Some(delete);
|
||||
self
|
||||
}
|
||||
|
||||
/// The misspelling `word` at `range` of the text object `object`, with the `suggestions` best first.
|
||||
pub fn new(object: u64, range: Range<usize>, word: impl Into<String>, suggestions: Vec<String>) -> Self {
|
||||
// P3(dialogs-w3): dl.F15
|
||||
SpellingItem { object, range, delete: Default::default(), word: word.into(), suggestions, before: String::new(), after: String::new() }
|
||||
SpellingItem { object, range, delete: None, word: word.into(), suggestions, before: String::new(), after: String::new() }
|
||||
}
|
||||
|
||||
/// Sets the sentence's text before and after the word.
|
||||
@@ -214,7 +213,7 @@ pub enum SpellingScope {
|
||||
/// box and the buttons.
|
||||
/// - Result: `()`; every close from inside (Done, Escape, the close action, automation's confirm) is
|
||||
/// [`DialogResult::Ok`], and a close from outside is `Cancel`.
|
||||
/// - Automation fields: `word` and `count` (read only), `changeTo` and `allLayers`.
|
||||
/// - Automation fields: `word` and `count` (read only), `changeTo`, and `allLayers` under [`SpellingScope::Layers`].
|
||||
#[derive(Clone, Debug, PartialEq, craft_ui::contract::Pattern)]
|
||||
pub struct CheckSpellingDialog {
|
||||
items: Vec<SpellingItem>,
|
||||
@@ -223,6 +222,9 @@ pub struct CheckSpellingDialog {
|
||||
ignored: Vec<String>,
|
||||
change_to: String,
|
||||
all_layers: bool,
|
||||
scope: SpellingScope,
|
||||
note: Option<Label>,
|
||||
modeless: bool,
|
||||
action: Option<SpellingAction>,
|
||||
open: bool,
|
||||
}
|
||||
@@ -230,33 +232,33 @@ pub struct CheckSpellingDialog {
|
||||
impl CheckSpellingDialog {
|
||||
/// Chooses the check's scope; Document hides and refuses the allLayers field.
|
||||
#[must_use]
|
||||
pub fn scope(self, scope: SpellingScope) -> Self {
|
||||
let _ = scope;
|
||||
todo!("dl.F16")
|
||||
pub fn scope(mut self, scope: SpellingScope) -> Self {
|
||||
self.scope = scope;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets a muted caption at the end of the dialog body.
|
||||
#[must_use]
|
||||
pub fn note(self, note: impl Into<Label>) -> Self {
|
||||
let _ = note;
|
||||
todo!("dl.F17")
|
||||
pub fn note(mut self, note: impl Into<Label>) -> Self {
|
||||
self.set_note(Some(note.into()));
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets or removes the muted caption at the end of the dialog body.
|
||||
pub fn set_note(&mut self, note: Option<Label>) {
|
||||
let _ = note;
|
||||
todo!("dl.F17")
|
||||
self.note = note;
|
||||
}
|
||||
|
||||
/// The item currently shown, for the app to reveal in its document.
|
||||
pub fn current(&self) -> Option<&SpellingItem> {
|
||||
todo!("dl.F17")
|
||||
self.items.get(self.index)
|
||||
}
|
||||
|
||||
/// Keeps the document editable behind the dialog; the default is modal.
|
||||
#[must_use]
|
||||
pub fn modeless(self) -> Self {
|
||||
todo!("dl.F18")
|
||||
pub fn modeless(mut self) -> Self {
|
||||
self.modeless = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// The misspellings the dialog lists.
|
||||
@@ -267,7 +269,18 @@ impl CheckSpellingDialog {
|
||||
/// Over `items` from a first search (the current layer: Check All Layers off).
|
||||
pub fn new(items: Vec<SpellingItem>) -> Self {
|
||||
let change_to = items.first().and_then(|i| i.suggestions.first()).cloned().unwrap_or_default();
|
||||
CheckSpellingDialog { items, index: 0, ignored: Vec::new(), change_to, all_layers: false, action: None, open: true }
|
||||
CheckSpellingDialog {
|
||||
items,
|
||||
index: 0,
|
||||
ignored: Vec::new(),
|
||||
change_to,
|
||||
all_layers: false,
|
||||
scope: SpellingScope::Layers,
|
||||
note: None,
|
||||
modeless: false,
|
||||
action: None,
|
||||
open: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Open with Check All Layers on.
|
||||
@@ -321,33 +334,38 @@ impl CheckSpellingDialog {
|
||||
/// Shows the dialog.
|
||||
pub fn show(&mut self, ui: &mut Ui) -> SpellingOutput {
|
||||
let words = Env::of(ui).words::<CheckSpellingWords>();
|
||||
let item = self.items.get(self.index).cloned();
|
||||
let item = self.current().cloned();
|
||||
let has_item = item.is_some();
|
||||
let repeated = item.as_ref().is_some_and(|item| item.delete.is_some());
|
||||
let word_label = if repeated { &words.repeated } else { &words.not_in_dictionary };
|
||||
let body_press = Cell::new(None::<Press>);
|
||||
let CheckSpellingDialog { change_to, all_layers, open, .. } = self;
|
||||
let CheckSpellingDialog { change_to, all_layers, scope, note, modeless, open, .. } = self;
|
||||
|
||||
let actions = [
|
||||
(&words.ignore, Press::Ignore),
|
||||
(&words.ignore_all, Press::IgnoreAll),
|
||||
(&words.change, Press::Change),
|
||||
(if repeated { &words.delete } else { &words.change }, Press::Change),
|
||||
(&words.change_all, Press::ChangeAll),
|
||||
(&words.add, Press::Add),
|
||||
];
|
||||
let buttons = std::iter::once(FooterButton::new(words.done.clone(), DialogRole::Accept))
|
||||
.chain(actions.iter().map(|(label, _)| FooterButton::new((*label).clone(), DialogRole::Other).stays_open(true).enabled(has_item)));
|
||||
let dialog = Dialog::new(words.title.clone()).button_place(ButtonPlace::Side).buttons(buttons).opened(Bind::bound(open));
|
||||
let buttons = std::iter::once(FooterButton::new(words.done.clone(), DialogRole::Accept)).chain(actions.iter().map(|(label, press)| {
|
||||
let enabled = has_item && (!repeated || !matches!(press, Press::ChangeAll | Press::Add));
|
||||
FooterButton::new((*label).clone(), DialogRole::Other).stays_open(true).enabled(enabled)
|
||||
}));
|
||||
let mut dialog = Dialog::new(words.title.clone()).button_place(ButtonPlace::Side).buttons(buttons).opened(Bind::bound(open));
|
||||
if *modeless {
|
||||
dialog = dialog.modeless();
|
||||
}
|
||||
let shown = dialog.show(ui, |ui, _| {
|
||||
let word = item.as_ref().map_or_else(String::new, |i| i.word.clone());
|
||||
Field::new(words.not_in_dictionary.clone()).id_salt("word").show(ui, |ui, _| {
|
||||
// PLAN: the word should be strong, underlined and in the accent ink inside the sunken field; no display
|
||||
// component takes a run of `Span`s (`Text::spans` wants `DocRun`s with fonts and data colours) and `Span`
|
||||
// has no colour (contract-03 OQ1), so the context reads as one wrapped line.
|
||||
Field::new(word_label.clone()).id_salt("word").show(ui, |ui, _| {
|
||||
// PLAN: plan error: no display component accepts styled spans for the spelling context's emphasized word.
|
||||
match item.as_ref().filter(|i| !i.before.is_empty() || !i.after.is_empty()) {
|
||||
Some(i) => {
|
||||
Text::new(format!("{}{}{}", i.before, i.word, i.after)).show(ui);
|
||||
}
|
||||
None => {
|
||||
TextField::new(words.not_in_dictionary.clone(), Bind::given(word.clone())).enabled(false).show(ui);
|
||||
TextField::new(word_label.clone(), Bind::given(word.clone())).enabled(false).show(ui);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -382,14 +400,19 @@ impl CheckSpellingDialog {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut checked = *all_layers;
|
||||
Checkbox::new(Bind::bound(&mut checked)).label(words.all_layers.clone()).show(ui);
|
||||
if checked != *all_layers {
|
||||
body_press.set(Some(Press::Relist(checked)));
|
||||
if *scope == SpellingScope::Layers {
|
||||
let mut checked = *all_layers;
|
||||
Checkbox::new(Bind::bound(&mut checked)).label(words.all_layers.clone()).show(ui);
|
||||
if checked != *all_layers {
|
||||
body_press.set(Some(Press::Relist(checked)));
|
||||
}
|
||||
}
|
||||
if !has_item {
|
||||
Notice::new(Tone::Neutral, words.complete.clone()).layout(NoticeLayout::Centred).show(ui);
|
||||
}
|
||||
if let Some(note) = note {
|
||||
Text::new(note.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
});
|
||||
let DialogOutput { response, closed, picked } = shown.output;
|
||||
let button_press = picked.and_then(|at| actions.get(at.checked_sub(1)?)).map(|(_, which)| *which);
|
||||
@@ -410,16 +433,24 @@ impl CheckSpellingDialog {
|
||||
}
|
||||
Some(Press::Change) => {
|
||||
if let Some(item) = item {
|
||||
self.action = Some(SpellingAction::Change { item, to: self.change_to.clone() });
|
||||
self.action = Some(if repeated {
|
||||
SpellingAction::Delete { item }
|
||||
} else {
|
||||
SpellingAction::Change { item, to: self.change_to.clone() }
|
||||
});
|
||||
}
|
||||
}
|
||||
Some(Press::ChangeAll) => {
|
||||
if let Some(item) = item {
|
||||
self.action = Some(SpellingAction::ChangeAll { item, to: self.change_to.clone(), all_layers: self.all_layers });
|
||||
if let Some(item) = item.filter(|_| !repeated) {
|
||||
self.action = Some(SpellingAction::ChangeAll {
|
||||
item,
|
||||
to: self.change_to.clone(),
|
||||
all_layers: self.scope == SpellingScope::Document || self.all_layers,
|
||||
});
|
||||
}
|
||||
}
|
||||
Some(Press::Add) => {
|
||||
if let Some(item) = item {
|
||||
if let Some(item) = item.filter(|_| !repeated) {
|
||||
self.action = Some(SpellingAction::Add(item.word));
|
||||
}
|
||||
}
|
||||
@@ -435,7 +466,7 @@ impl StackDialog for CheckSpellingDialog {
|
||||
|
||||
/// Whether the document stays editable behind the dialog.
|
||||
fn modeless(&self) -> bool {
|
||||
todo!("dl.F18")
|
||||
self.modeless
|
||||
}
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
@@ -448,8 +479,12 @@ impl StackDialog for CheckSpellingDialog {
|
||||
}
|
||||
|
||||
fn json_fields(&self) -> Option<Value> {
|
||||
let word = self.items.get(self.index).map(|item| item.word.as_str());
|
||||
Some(json!({ "word": word, "changeTo": self.change_to, "allLayers": self.all_layers, "count": self.items.len() }))
|
||||
let word = self.current().map(|item| item.word.as_str());
|
||||
let mut fields = json!({ "word": word, "changeTo": self.change_to, "count": self.items.len() });
|
||||
if self.scope == SpellingScope::Layers {
|
||||
fields["allLayers"] = json!(self.all_layers);
|
||||
}
|
||||
Some(fields)
|
||||
}
|
||||
|
||||
fn set_json_field(&mut self, _: &Context, field: &str, value: Value) -> Result<(), String> {
|
||||
@@ -458,17 +493,17 @@ impl StackDialog for CheckSpellingDialog {
|
||||
if self.items.is_empty() {
|
||||
return Err("`changeTo` takes no input: the list of misspellings is empty".to_owned());
|
||||
}
|
||||
let text = value.as_str().ok_or_else(|| "`changeTo` takes a string".to_owned())?;
|
||||
let text = value.as_str().ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?;
|
||||
self.change_to = text.to_owned();
|
||||
Ok(())
|
||||
}
|
||||
"allLayers" => {
|
||||
let on = value.as_bool().ok_or_else(|| "`allLayers` takes true or false".to_owned())?;
|
||||
"allLayers" if self.scope == SpellingScope::Layers => {
|
||||
let on = value.as_bool().ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?;
|
||||
self.relist_all_layers(on);
|
||||
Ok(())
|
||||
}
|
||||
"word" | "count" => Err(format!("`{field}` is read only")),
|
||||
_ => Err(format!("unknown field `{field}`: this dialog has `word`, `changeTo`, `allLayers` and `count`")),
|
||||
"word" | "count" => Err(FieldRefusal::ReadOnly.message(field)),
|
||||
_ => Err(FieldRefusal::Unknown.message(field)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
//! Stories of `CheckSpellingDialog`.
|
||||
|
||||
use super::{CheckSpellingDialog, SpellingItem};
|
||||
use super::{CheckSpellingDialog, SpellingItem, SpellingScope};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::contract::{Show as _, clicked};
|
||||
use craft_ui::dialog::stories::hosted;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use craft_ui::text::TextField;
|
||||
use egui::Ui;
|
||||
|
||||
fn items() -> Vec<SpellingItem> {
|
||||
@@ -29,18 +33,30 @@ fn check_spelling_complete(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
|
||||
/// A repeated word offers Delete instead of Change.
|
||||
#[story(CheckSpellingDialog, covers = [], drive = Drive::Never)]
|
||||
fn check_spelling_repeated_word(_: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
todo!("dl.F15")
|
||||
fn check_spelling_repeated_word(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
open_spelling(ui, data, || {
|
||||
let item = SpellingItem::new(1, 11..14, "the", Vec::new()).repeated(10..14).context("We saw the ", " cat.");
|
||||
CheckSpellingDialog::new(vec![item]).note("Delete removes the repeated word and its preceding space.")
|
||||
})
|
||||
}
|
||||
|
||||
/// A document-wide check without the layer checkbox.
|
||||
#[story(CheckSpellingDialog, covers = [], drive = Drive::Never)]
|
||||
fn check_spelling_whole_document(_: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
todo!("dl.F16")
|
||||
fn check_spelling_whole_document(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
open_spelling(ui, data, || CheckSpellingDialog::new(items()).scope(SpellingScope::Document).note("Checking the whole document."))
|
||||
}
|
||||
|
||||
/// The modeless spelling dialog leaves the document editable.
|
||||
#[story(CheckSpellingDialog, covers = [], drive = Drive::Never)]
|
||||
fn check_spelling_modeless(_: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
todo!("dl.F18")
|
||||
fn check_spelling_modeless(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
TextField::new("Document", data.bind("document", "The cat sat on the mat.".to_owned())).show(ui);
|
||||
open_spelling(ui, data, || CheckSpellingDialog::new(items()).modeless())
|
||||
}
|
||||
|
||||
fn open_spelling(ui: &mut Ui, data: &mut StoryData, open: impl FnOnce() -> CheckSpellingDialog) -> StoryOutput {
|
||||
let opened = data.value("open", false);
|
||||
if clicked(&Button::new("Check Spelling…").show(ui)) {
|
||||
*opened = true;
|
||||
}
|
||||
hosted(ui, data, (), open)
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
use crate::contract::{
|
||||
Bind, BodyCx, CollectionEvent, NoValue, Outcome, Props as _, Remember as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _,
|
||||
};
|
||||
use crate::dialog::{ButtonPlace, Dialog, DialogId, DialogOutput, DialogResult, DialogStack, StackDialog};
|
||||
use crate::dialog::{ButtonPlace, Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, StackDialog};
|
||||
use crate::display::{Shade, Text};
|
||||
use crate::form::Field;
|
||||
use crate::layout_components::Stack;
|
||||
@@ -106,6 +106,13 @@ pub enum ActionEnabled {
|
||||
Never,
|
||||
}
|
||||
|
||||
impl ActionEnabled {
|
||||
/// Enables the action on an entry of any kind.
|
||||
pub fn on_entry() -> Self {
|
||||
Self::OnEntry { kind: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// One button of the column, top to bottom.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
@@ -133,12 +140,12 @@ impl ListManagerAction {
|
||||
|
||||
/// Run, enabled on an entry, closing; the default action (Enter, double click).
|
||||
pub fn run(words: &ListManagerWords) -> Self {
|
||||
Self::new("run", words.run.clone(), ActionEnabled::OnEntry { kind: None })
|
||||
Self::new("run", words.run.clone(), ActionEnabled::on_entry())
|
||||
}
|
||||
|
||||
/// Edit, enabled on an entry, closing.
|
||||
pub fn edit(words: &ListManagerWords) -> Self {
|
||||
Self::new("edit", words.edit.clone(), ActionEnabled::OnEntry { kind: None })
|
||||
Self::new("edit", words.edit.clone(), ActionEnabled::on_entry())
|
||||
}
|
||||
|
||||
/// Create, enabled when the name box holds a new name, closing.
|
||||
@@ -148,7 +155,7 @@ impl ListManagerAction {
|
||||
|
||||
/// Delete, enabled on an entry, keeping the dialog open for the app's confirmation; the Delete key runs it.
|
||||
pub fn delete(words: &ListManagerWords) -> Self {
|
||||
Self::new(DELETE, words.delete.clone(), ActionEnabled::OnEntry { kind: None }).keeps_open()
|
||||
Self::new(DELETE, words.delete.clone(), ActionEnabled::on_entry()).keeps_open()
|
||||
}
|
||||
|
||||
/// Tells `reason` while the button is disabled.
|
||||
@@ -168,7 +175,7 @@ impl ListManagerAction {
|
||||
/// Enabled only on entries of `kind`.
|
||||
#[must_use]
|
||||
pub fn kind(mut self, kind: u32) -> Self {
|
||||
if let ActionEnabled::OnEntry { kind: wanted } = &mut self.enabled {
|
||||
if let ActionEnabled::OnEntry { kind: wanted, .. } = &mut self.enabled {
|
||||
*wanted = Some(kind);
|
||||
}
|
||||
self
|
||||
@@ -186,7 +193,7 @@ impl ListManagerAction {
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct ListManagerChoice {
|
||||
/// The second labelled text box's value.
|
||||
/// The second labelled text box's text, trimmed; `None` when no box is shown.
|
||||
pub field: Option<String>,
|
||||
/// The pressed action's id.
|
||||
pub action: String,
|
||||
@@ -240,6 +247,9 @@ pub struct HostedListManager {
|
||||
renames: Option<u32>,
|
||||
/// The name box's text, kept by the dialog.
|
||||
name: String,
|
||||
empty: Option<Label>,
|
||||
note: Option<Label>,
|
||||
field: Option<(Label, String)>,
|
||||
open: bool,
|
||||
/// The choice of an action that kept the dialog open, until the host takes it.
|
||||
choice: Option<ListManagerChoice>,
|
||||
@@ -259,6 +269,9 @@ impl HostedListManager {
|
||||
actions,
|
||||
renames: None,
|
||||
name: String::new(),
|
||||
empty: None,
|
||||
note: None,
|
||||
field: None,
|
||||
open: true,
|
||||
choice: None,
|
||||
}
|
||||
@@ -266,27 +279,30 @@ impl HostedListManager {
|
||||
|
||||
/// Sets the name box's opening text.
|
||||
#[must_use]
|
||||
pub fn name(self, name: impl Into<String>) -> Self {
|
||||
let _ = name;
|
||||
todo!("dl.F19")
|
||||
pub fn name(mut self, name: impl Into<String>) -> Self {
|
||||
self.name = name.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the text shown when the list is empty.
|
||||
pub fn empty(self, empty: impl Into<Label>) -> Self {
|
||||
let _ = empty;
|
||||
todo!("dl.F19")
|
||||
#[must_use]
|
||||
pub fn empty(mut self, empty: impl Into<Label>) -> Self {
|
||||
self.empty = Some(empty.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the note below the list.
|
||||
pub fn note(self, note: impl Into<Label>) -> Self {
|
||||
let _ = note;
|
||||
todo!("dl.F19")
|
||||
#[must_use]
|
||||
pub fn note(mut self, note: impl Into<Label>) -> Self {
|
||||
self.note = Some(note.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds a second labelled text box with the supplied opening text.
|
||||
pub fn field(self, label: impl Into<Label>, text: impl Into<String>) -> Self {
|
||||
let _ = (label, text);
|
||||
todo!("dl.F19")
|
||||
#[must_use]
|
||||
pub fn field(mut self, label: impl Into<Label>, text: impl Into<String>) -> Self {
|
||||
self.field = Some((label.into(), text.into()));
|
||||
self
|
||||
}
|
||||
|
||||
/// The entries the list opens with.
|
||||
@@ -323,9 +339,18 @@ impl StackDialog for HostedListManager {
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<ListManagerChoice>> {
|
||||
let list = ListManager::new(self.title.clone(), self.name_label.clone(), &self.entries[..], &self.actions[..])
|
||||
let mut list = ListManager::new(self.title.clone(), self.name_label.clone(), &self.entries[..], &self.actions[..])
|
||||
.name_box(Bind::bound(&mut self.name))
|
||||
.opened(Bind::bound(&mut self.open));
|
||||
if let Some(empty) = &self.empty {
|
||||
list = list.empty(empty.clone());
|
||||
}
|
||||
if let Some(note) = &self.note {
|
||||
list = list.note(note.clone());
|
||||
}
|
||||
if let Some((label, text)) = &mut self.field {
|
||||
list = list.field((label.clone(), Bind::bound(text)));
|
||||
}
|
||||
let list = match self.renames {
|
||||
Some(kind) => list.renames(kind),
|
||||
None => list,
|
||||
@@ -344,12 +369,24 @@ impl StackDialog for HostedListManager {
|
||||
}
|
||||
|
||||
fn json_fields(&self) -> Option<serde_json::Value> {
|
||||
todo!("dl.F19")
|
||||
let entries: Vec<_> = self.entries.iter().map(|entry| serde_json::json!({ "id": entry.id, "name": entry.name })).collect();
|
||||
let mut fields = serde_json::json!({ "name": self.name, "entries": entries });
|
||||
if let Some((_, text)) = &self.field {
|
||||
fields["field"] = serde_json::json!(text);
|
||||
}
|
||||
Some(fields)
|
||||
}
|
||||
|
||||
fn set_json_field(&mut self, _: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> {
|
||||
let _ = (field, value);
|
||||
todo!("dl.F19")
|
||||
let target = match field {
|
||||
"name" => Some(&mut self.name),
|
||||
"field" => self.field.as_mut().map(|(_, text)| text),
|
||||
"entries" => return Err(FieldRefusal::ReadOnly.message(field)),
|
||||
_ => None,
|
||||
}
|
||||
.ok_or_else(|| FieldRefusal::Unknown.message(field))?;
|
||||
*target = value.as_str().ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?.to_owned();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn key(&self) -> Option<&str> {
|
||||
@@ -489,7 +526,7 @@ impl<'a> ListManager<'a> {
|
||||
searchable: false,
|
||||
name: None,
|
||||
name_box: None,
|
||||
field: Default::default(), // P3(dialogs-w3): dl.F19
|
||||
field: None,
|
||||
open: None,
|
||||
renames: None,
|
||||
name_check: None,
|
||||
@@ -517,7 +554,8 @@ impl<'a> ListManager<'a> {
|
||||
cancel_label,
|
||||
under,
|
||||
} = self;
|
||||
let _ = field; // P3(dialogs-w3): dl.F19
|
||||
let field = RefCell::new(field);
|
||||
let field_text = RefCell::new(None::<String>);
|
||||
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();
|
||||
@@ -569,12 +607,21 @@ impl<'a> ListManager<'a> {
|
||||
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);
|
||||
let mut field = field.borrow_mut();
|
||||
let mut extra = field.as_mut().map(|(_, bind)| text_of(bind, cx));
|
||||
Stack::new()
|
||||
.header(|ui, _| {
|
||||
let mut text = text.borrow_mut();
|
||||
Field::new(name_label.clone()).show(ui, |ui, _| {
|
||||
TextField::new(name_label.clone(), Bind::bound(&mut *text)).select_on_focus().drives(list_id).show(ui);
|
||||
});
|
||||
if let Some((label, _)) = field.as_ref()
|
||||
&& let Some(extra) = &mut extra
|
||||
{
|
||||
Field::new(label.clone()).show(ui, |ui, _| {
|
||||
TextField::new(label.clone(), Bind::bound(&mut *extra)).show(ui);
|
||||
});
|
||||
}
|
||||
})
|
||||
.footer(|ui, _| {
|
||||
let text = text.borrow();
|
||||
@@ -656,6 +703,16 @@ impl<'a> ListManager<'a> {
|
||||
let _ = bind.reborrow().write(cx, &event);
|
||||
}
|
||||
typed.borrow_mut().clone_from(&text);
|
||||
if let Some((label, bind)) = field.as_mut()
|
||||
&& let Some(extra) = extra
|
||||
{
|
||||
let before = text_of(bind, cx);
|
||||
if extra != before {
|
||||
let event = EditEvent::set(Mixed::Same(before), extra.clone(), Arc::from(label.as_str()), None);
|
||||
let _ = bind.reborrow().write(cx, &event);
|
||||
}
|
||||
*field_text.borrow_mut() = Some(extra.trim().to_owned());
|
||||
}
|
||||
if let Some(at) = activated.get()
|
||||
&& actions[at].closes
|
||||
{
|
||||
@@ -668,18 +725,16 @@ impl<'a> ListManager<'a> {
|
||||
let choice = at.map(|at| {
|
||||
let typed = typed.take();
|
||||
let entry = entries.iter().find(|entry| is_named(entry, &folder, &typed) && accepts(&actions[at], entry));
|
||||
// P3(dialogs-w3): dl.F19
|
||||
ListManagerChoice {
|
||||
field: Default::default(),
|
||||
field: field_text.borrow().clone(),
|
||||
action: actions[at].id.clone(),
|
||||
entry: entry.map(|entry| entry.id.clone()),
|
||||
name: typed.trim().to_owned(),
|
||||
}
|
||||
});
|
||||
let rename = renamed.take().and_then(|(at, name)| {
|
||||
// P3(dialogs-w3): dl.F19
|
||||
entries.get(at).map(|entry| ListManagerChoice {
|
||||
field: Default::default(),
|
||||
field: field_text.borrow().clone(),
|
||||
action: ListManagerChoice::RENAME.to_owned(),
|
||||
entry: Some(entry.id.clone()),
|
||||
name,
|
||||
|
||||
@@ -146,7 +146,17 @@ fn hosted_list_manager(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
}
|
||||
|
||||
/// A button opens a hosted list manager with a second labelled field.
|
||||
#[crate::testing::story(ListManager<'static>, covers = [], drive = crate::testing::Drive::Never)]
|
||||
fn hosted_list_manager_field(_: &mut egui::Ui, _: &mut crate::testing::StoryData) -> crate::testing::StoryOutput {
|
||||
todo!("dl.F19")
|
||||
#[story(ListManager<'static>, covers = [], drive = Drive::Never)]
|
||||
fn hosted_list_manager_field(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let open = data.value("open", false);
|
||||
if clicked(&Button::new("Manage lists…").show(ui)) {
|
||||
*open = true;
|
||||
}
|
||||
hosted(ui, data, (), || {
|
||||
HostedListManager::new("lists", "Lists", "Name:", vec![ListManagerAction::new("create", "Create", ActionEnabled::OnValidName)])
|
||||
.name("Custom list 1")
|
||||
.field("Items:", "1,3,5")
|
||||
.empty("There are no saved lists.")
|
||||
.note("Enter the item numbers separated by commas.")
|
||||
})
|
||||
}
|
||||
@@ -78,8 +78,9 @@ pub struct PreferencesState {
|
||||
/// - **Layout.** [`layout`](PreferencesWindow::layout) passes a [`PreferencesLayout`] to the page:
|
||||
/// [`PreferencesLayout::Cards`] shows one scrolling column of cards with the search's match count, and the window
|
||||
/// opens narrower, as it needs no room for a page list.
|
||||
/// - **Live mode.** [`PreferencesMode::Live`] applies changes as they occur and shows only OK, which closes without
|
||||
/// applying again. Closing the window does not cancel changes. A failed apply shows its message until another edit.
|
||||
/// - **Live modes.** [`PreferencesMode::Live`] applies changes as they occur and shows only OK, which closes without
|
||||
/// applying again. [`PreferencesMode::LiveCancel`] also offers Cancel, reporting [`Closed::Cancel`] without a model
|
||||
/// call; the app owns any restoration. A failed apply shows its message until another edit.
|
||||
/// - **Nested dialogs.** While [`PreferencesModel::nested_open`] is true the window takes no input and refuses to
|
||||
/// close; [`PreferencesModel::nested`] draws the nested dialogs with the body's `Ui`, inside the window's own
|
||||
/// viewport.
|
||||
@@ -101,14 +102,15 @@ pub struct PreferencesWindow<'a> {
|
||||
/// Keeps the window's place and size across runs under `key`.
|
||||
#[prop]
|
||||
remember: Option<SaveKey>,
|
||||
/// Selects whether changes are staged or applied while the window is open.
|
||||
/// Selects staged changes, Live with OK, or LiveCancel with OK and Cancel.
|
||||
#[prop]
|
||||
mode: PreferencesMode,
|
||||
/// Lays the page out as `layout` says ([`PreferencesPage::layout`]); the default is [`PreferencesLayout::Paged`].
|
||||
#[prop]
|
||||
layout: PreferencesLayout,
|
||||
/// Escape keeps the typing in the focused field ([`Dialog::escape_keeps_typing`]): in [`PreferencesMode::Live`]
|
||||
/// the typed value stays applied when Escape closes the window. Off by default: Escape cancels the typing.
|
||||
/// and [`PreferencesMode::LiveCancel`] the typed value stays applied when Escape closes the window.
|
||||
/// Off by default: Escape cancels the typing.
|
||||
#[prop(flag)]
|
||||
escape_keeps_typing: bool,
|
||||
}
|
||||
@@ -192,8 +194,13 @@ impl<'a> PreferencesWindow<'a> {
|
||||
ok = ok.disabled_reason(words.cannot_ok.clone());
|
||||
}
|
||||
let apply = FooterButton::new(words.apply.clone(), DialogRole::Other).enabled(differs).stays_open(true);
|
||||
let buttons =
|
||||
if mode == PreferencesMode::Live { vec![ok] } else { vec![ok, apply, FooterButton::new(common.cancel.clone(), DialogRole::Cancel)] };
|
||||
let live = matches!(mode, PreferencesMode::Live | PreferencesMode::LiveCancel);
|
||||
let cancel = FooterButton::new(common.cancel.clone(), DialogRole::Cancel);
|
||||
let buttons = match mode {
|
||||
PreferencesMode::Live => vec![ok],
|
||||
PreferencesMode::LiveCancel => vec![ok, cancel],
|
||||
PreferencesMode::Staged => vec![ok, apply, cancel],
|
||||
};
|
||||
|
||||
let (size, least) = match layout {
|
||||
PreferencesLayout::Paged => (DEFAULT_SIZE, MIN_SIZE),
|
||||
@@ -222,7 +229,7 @@ impl<'a> PreferencesWindow<'a> {
|
||||
session.borrow_mut().apply(cx);
|
||||
}
|
||||
})
|
||||
.close_guard(|button, cx| mode == PreferencesMode::Live || button.role() != DialogRole::Accept || session.borrow_mut().apply(cx));
|
||||
.close_guard(|button, cx| live || button.role() != DialogRole::Accept || session.borrow_mut().apply(cx));
|
||||
if !embedded {
|
||||
dialog = dialog.viewport();
|
||||
}
|
||||
@@ -248,7 +255,8 @@ impl<'a> PreferencesWindow<'a> {
|
||||
pick_color = Some(request);
|
||||
}
|
||||
session.host.nested(ui);
|
||||
if mode == PreferencesMode::Live && session.work.error.is_none() && session.host.differs() {
|
||||
// Each pass applies its own edits; a successful apply clears differs before any second pass.
|
||||
if live && session.work.error.is_none() && session.host.differs() {
|
||||
session.apply(cx);
|
||||
}
|
||||
session.page = shown.page;
|
||||
|
||||
@@ -223,7 +223,103 @@ fn preferences_window_live(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
}
|
||||
|
||||
/// Live preferences show OK and Cancel.
|
||||
#[crate::testing::story(PreferencesWindow<'static>, covers = [], drive = crate::testing::Drive::Never)]
|
||||
fn preferences_window_live_cancel(_: &mut egui::Ui, _: &mut crate::testing::StoryData) -> crate::testing::StoryOutput {
|
||||
todo!("dl.F20")
|
||||
#[story(PreferencesWindow<'static>, covers = [], drive = Drive::Never)]
|
||||
fn preferences_window_live_cancel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let mut open = *data.value("open", false);
|
||||
if clicked(&Button::new("Open preferences").show(ui)) {
|
||||
open = true;
|
||||
}
|
||||
let mut demo = data.value("demo", Demo::default()).clone();
|
||||
let mut result = StoryOutput::default();
|
||||
if open {
|
||||
let state = data.value("state", PreferencesState::default());
|
||||
let shown = PreferencesWindow::new(Bind::bound(state))
|
||||
.mode(PreferencesMode::LiveCancel)
|
||||
.layout(PreferencesLayout::Cards)
|
||||
.embedded()
|
||||
.show(ui, &mut demo);
|
||||
open = shown.closed.is_none();
|
||||
result = shown.into();
|
||||
}
|
||||
*data.value("open", false) = open;
|
||||
*data.value("demo", Demo::default()) = demo;
|
||||
result
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, PartialEq)]
|
||||
struct ResetDemo {
|
||||
snap: bool,
|
||||
saved_snap: bool,
|
||||
resettable: bool,
|
||||
}
|
||||
|
||||
impl PreferencesModel for ResetDemo {
|
||||
fn pages(&self) -> Vec<PageSpec<'_>> {
|
||||
let page = PageSpec::new("general", "General", vec![RowSpec::new("snap", "Snap to grid", RowKind::Bool(self.snap))]);
|
||||
// PLAN: assumed PageSpec::resettable(self, on: bool) -> Self (dialogs-w17)
|
||||
vec![if self.resettable { page } else { page.resettable(false) }]
|
||||
}
|
||||
|
||||
fn set(&mut self, _: &str, value: PrefValue) {
|
||||
if let PrefValue::Bool(on) = value {
|
||||
self.snap = on;
|
||||
}
|
||||
}
|
||||
|
||||
fn custom_row(&mut self, _: &mut Ui, _: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn custom_page(&mut self, _: &mut Ui, _: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn reset_page(&mut self, _: &str) {
|
||||
self.snap = false;
|
||||
}
|
||||
}
|
||||
|
||||
impl PreferencesDraft for ResetDemo {
|
||||
fn differs(&self) -> bool {
|
||||
self.snap != self.saved_snap
|
||||
}
|
||||
|
||||
fn apply(&mut self) -> Result<(), String> {
|
||||
self.saved_snap = self.snap;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cancel(&mut self) {
|
||||
self.snap = self.saved_snap;
|
||||
}
|
||||
}
|
||||
|
||||
fn reset_window(ui: &mut Ui, data: &mut StoryData, resettable: bool) -> StoryOutput {
|
||||
let mut open = *data.value("open", false);
|
||||
if clicked(&Button::new("Open preferences").show(ui)) {
|
||||
open = true;
|
||||
}
|
||||
let mut model = data.value("model", ResetDemo { snap: true, saved_snap: true, resettable }).clone();
|
||||
let mut result = StoryOutput::default();
|
||||
if open {
|
||||
let state = data.value("state", PreferencesState::default());
|
||||
let shown = PreferencesWindow::new(Bind::bound(state)).mode(PreferencesMode::LiveCancel).embedded().show(ui, &mut model);
|
||||
open = shown.closed.is_none();
|
||||
result = shown.into();
|
||||
}
|
||||
*data.value("open", false) = open;
|
||||
*data.value("model", ResetDemo::default()) = model;
|
||||
result
|
||||
}
|
||||
|
||||
/// A page whose Reset Section action is available.
|
||||
#[story(PreferencesWindow<'static>, covers = [], drive = Drive::Never)]
|
||||
fn preferences_window_reset_section(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
reset_window(ui, data, true)
|
||||
}
|
||||
|
||||
/// A page whose host does not offer Reset Section.
|
||||
#[story(PreferencesWindow<'static>, covers = [], drive = Drive::Never)]
|
||||
fn preferences_window_without_reset_section(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
reset_window(ui, data, false)
|
||||
}
|
||||
@@ -4,8 +4,9 @@
|
||||
use craft_ui::contract::{Bind, Role};
|
||||
use craft_ui::dialog::{DialogHost, StackDialog as _};
|
||||
use craft_ui::patterns::form_dialogs::{
|
||||
AboutAppTab, AboutDialog, AboutInfo, AboutLayout, AboutLink, AboutTab, Contributor, Credits, HostedAbout, ModelCredit,
|
||||
AboutAppTab, AboutDialog, AboutInfo, AboutLayout, AboutLink, AboutTab, AboutWords, Contributor, Credits, HostedAbout, ModelCredit,
|
||||
};
|
||||
use craft_ui::runtime::env::Env;
|
||||
use craft_ui::testing::{Fixture, access, trial};
|
||||
use egui::Vec2;
|
||||
use serde_json::json;
|
||||
@@ -317,6 +318,51 @@ fn sort_by(fixture: &mut Fixture, head: &str) {
|
||||
fixture.click(&cell).idle(30);
|
||||
}
|
||||
|
||||
/// Timestamps and date-only credits share a calendar day; an absent date stays visibly undated.
|
||||
#[trial]
|
||||
fn a_commit_time_shows_as_its_day_and_no_date_as_a_mark() {
|
||||
let credits = Credits::new(
|
||||
vec![
|
||||
Contributor::new("timestamp").active("2026-10-07T18:45:23Z", "2026-10-07T18:45:23Z"),
|
||||
Contributor::new("day").active("2026-10-07", "2026-10-07"),
|
||||
Contributor::new("undated"),
|
||||
],
|
||||
Vec::new(),
|
||||
0,
|
||||
);
|
||||
let labels = Rc::new(RefCell::new((String::new(), String::new())));
|
||||
let resolved = labels.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let words = Env::of(ui).words::<AboutWords>();
|
||||
*resolved.borrow_mut() = (words.table.as_str().to_owned(), words.head_first.as_str().to_owned());
|
||||
let _ = AboutDialog::new(&INFO, &credits).tab(Bind::given(AboutTab::Contributors)).show(ui);
|
||||
});
|
||||
fixture.room(Vec2::new(1400.0, 1000.0)).settle();
|
||||
let (table_label, first_label) = labels.borrow().clone();
|
||||
let table = fixture.by_label(&table_label).expect("the table view choice");
|
||||
fixture.click(&table).settle();
|
||||
let tree = fixture.tree();
|
||||
// Header nodes and cell indices both follow the table's declared column order.
|
||||
let column = fixture
|
||||
.by_role(Role::COLUMN_HEADER)
|
||||
.iter()
|
||||
.position(|head| tree.name_of(head.node) == Some(first_label.as_str()))
|
||||
.expect("the first-commit column");
|
||||
let day_cell = |login: &str| {
|
||||
let row = fixture.by_label(login).expect("the contributor row");
|
||||
let cell = tree
|
||||
.children_of(row.node)
|
||||
.into_iter()
|
||||
.find(|node| tree.role_of(*node) == Some(Role::CELL) && tree.grid_of(*node).column_index == Some(column))
|
||||
.expect("the row's first-commit cell");
|
||||
tree.name_of(cell).expect("the displayed date or mark").to_owned()
|
||||
};
|
||||
let (timestamp, day, undated) = (day_cell("@timestamp"), day_cell("@day"), day_cell("@undated"));
|
||||
assert!(day.chars().any(|ch| ch.is_ascii_digit()), "a supplied day shows a date");
|
||||
assert_eq!(timestamp, day, "the time of day does not change the displayed calendar day");
|
||||
assert!(!undated.is_empty() && !undated.chars().any(|ch| ch.is_ascii_digit()), "an absent date shows a mark without a date");
|
||||
}
|
||||
|
||||
/// Guards the contributors' order: names compare without the `@` and without case, a display name sorts among the
|
||||
/// usernames, and a contributor with no commit date follows everyone with one whichever way the dates sort.
|
||||
#[trial]
|
||||
|
||||
@@ -185,6 +185,7 @@ fn a_hosted_list_manager_hands_over_kept_open_choices_and_answers_with_the_closi
|
||||
press(&mut fixture, "Delete");
|
||||
let deleted = choice(&host).expect("Delete hands its choice to the host");
|
||||
assert_eq!((deleted.action.as_str(), deleted.entry.as_deref()), ("delete", Some("b")));
|
||||
assert!(deleted.field.is_none(), "a manager without a second box reports none");
|
||||
assert_eq!(choice(&host), None, "the choice is taken once");
|
||||
assert!(host.borrow().is_open::<HostedListManager>(), "Delete keeps the list open");
|
||||
|
||||
@@ -196,4 +197,5 @@ fn a_hosted_list_manager_hands_over_kept_open_choices_and_answers_with_the_closi
|
||||
press(&mut fixture, "Run");
|
||||
let answered = host.borrow_mut().take::<HostedListManager>();
|
||||
assert!(matches!(&answered, Some(DialogResult::Ok(run)) if run.action == "run" && run.entry.as_deref() == Some("a")), "{answered:?}");
|
||||
assert!(matches!(&answered, Some(DialogResult::Ok(run)) if run.field.is_none()));
|
||||
}
|
||||
@@ -2,11 +2,15 @@
|
||||
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::patterns::preferences::{
|
||||
PageSpec, PrefValue, PreferencesDraft, PreferencesMode, PreferencesModel, PreferencesState, PreferencesWindow, RowKind, RowSpec,
|
||||
Closed, PageSpec, PrefValue, PreferencesDraft, PreferencesLayout, PreferencesMode, PreferencesModel, PreferencesState, PreferencesWindow,
|
||||
PreferencesWords, RowKind, RowSpec,
|
||||
};
|
||||
use craft_ui::runtime::env::Env;
|
||||
use craft_ui::runtime::words::CommonWords;
|
||||
use craft_ui::sections::SectionWords;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::Ui;
|
||||
use std::cell::RefCell;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -14,15 +18,28 @@ struct Model {
|
||||
draft: bool,
|
||||
saved: bool,
|
||||
applies: usize,
|
||||
sets: usize,
|
||||
cancels: usize,
|
||||
resets: usize,
|
||||
reset_disabled: bool,
|
||||
}
|
||||
|
||||
impl Model {
|
||||
fn calls(&self) -> (usize, usize, usize, usize) {
|
||||
(self.sets, self.applies, self.cancels, self.resets)
|
||||
}
|
||||
}
|
||||
|
||||
impl PreferencesModel for Model {
|
||||
fn pages(&self) -> Vec<PageSpec<'_>> {
|
||||
vec![PageSpec::new("general", "General", vec![RowSpec::new("snap", "Snap", RowKind::Bool(self.draft))])]
|
||||
let page = PageSpec::new("general", "General", vec![RowSpec::new("snap", "Snap", RowKind::Bool(self.draft))]);
|
||||
// PLAN: assumed PageSpec::resettable(self, on: bool) -> Self (dialogs-w17)
|
||||
vec![if self.reset_disabled { page.resettable(false) } else { page }]
|
||||
}
|
||||
fn set(&mut self, _: &str, value: PrefValue) {
|
||||
if let PrefValue::Bool(value) = value {
|
||||
self.draft = value;
|
||||
self.sets += 1;
|
||||
}
|
||||
}
|
||||
fn custom_row(&mut self, _: &mut Ui, _: &str) -> bool {
|
||||
@@ -33,6 +50,7 @@ impl PreferencesModel for Model {
|
||||
}
|
||||
fn reset_page(&mut self, _: &str) {
|
||||
self.draft = false;
|
||||
self.resets += 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +65,7 @@ impl PreferencesDraft for Model {
|
||||
}
|
||||
fn cancel(&mut self) {
|
||||
self.draft = self.saved;
|
||||
self.cancels += 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,3 +226,111 @@ fn escape_keeps_a_live_windows_typing_when_asked() {
|
||||
assert!(closed, "Escape closes the window");
|
||||
assert_eq!(saved, "Ada", "the typing stays applied");
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Answer {
|
||||
Ok,
|
||||
Cancel,
|
||||
Escape,
|
||||
Close,
|
||||
}
|
||||
|
||||
/// Guards live application and the close result used by an app that owns its opening snapshot.
|
||||
#[trial]
|
||||
fn a_live_cancel_window_applies_each_change_and_any_close_but_ok_is_a_cancel_with_no_model_call() {
|
||||
for answer in [Answer::Ok, Answer::Cancel, Answer::Escape, Answer::Close] {
|
||||
let model = Rc::new(RefCell::new(Model::default()));
|
||||
let closed = Rc::new(Cell::new(None::<Closed>));
|
||||
let labels = Rc::new(RefCell::new(Vec::new()));
|
||||
let rerun = Rc::new(Cell::new(false));
|
||||
let (shown, ended, words, twice) = (model.clone(), closed.clone(), labels.clone(), rerun.clone());
|
||||
let mut state = PreferencesState::default();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
if ended.get().is_some() {
|
||||
return;
|
||||
}
|
||||
if twice.get() && ui.ctx().current_pass_index() == 0 {
|
||||
ui.ctx().request_discard("exercise live edits in two passes of one frame");
|
||||
}
|
||||
let env = Env::of(ui);
|
||||
let common = env.words::<CommonWords>();
|
||||
let own = env.words::<PreferencesWords>();
|
||||
let section = env.words::<SectionWords>();
|
||||
*words.borrow_mut() = vec![common.ok.clone(), common.cancel.clone(), section.close.clone(), own.apply.clone()];
|
||||
let output = PreferencesWindow::new(Bind::bound(&mut state))
|
||||
.mode(PreferencesMode::LiveCancel)
|
||||
.embedded()
|
||||
.show(ui, &mut *shown.borrow_mut());
|
||||
if let Some(result) = output.closed {
|
||||
ended.set(Some(result));
|
||||
}
|
||||
});
|
||||
fixture.settle();
|
||||
let labels = labels.borrow().clone();
|
||||
let [ok, cancel, close, apply] = labels.as_slice() else { panic!("the dialog words") };
|
||||
assert!(fixture.by_label(ok.as_str()).is_some() && fixture.by_label(cancel.as_str()).is_some());
|
||||
assert!(fixture.by_label(apply.as_str()).is_none(), "LiveCancel has no Apply action");
|
||||
|
||||
let before = model.borrow().calls();
|
||||
let snap = fixture.by_label("Snap").expect("the setting");
|
||||
rerun.set(true);
|
||||
fixture.click(&snap).settle();
|
||||
assert!(model.borrow().saved, "the edit reaches the model before closing: {answer:?}");
|
||||
assert_eq!(model.borrow().applies, before.1 + 1, "a second pass must not apply the edit again");
|
||||
assert_eq!(model.borrow().sets, before.0 + 1, "only the pass receiving input edits the model");
|
||||
assert!(closed.get().is_none(), "an edit keeps the window open");
|
||||
|
||||
let before_close = model.borrow().calls();
|
||||
let label = match answer {
|
||||
Answer::Ok => Some(ok),
|
||||
Answer::Cancel => Some(cancel),
|
||||
Answer::Close => Some(close),
|
||||
Answer::Escape => None,
|
||||
};
|
||||
if let Some(label) = label {
|
||||
let button = fixture.by_label(label.as_str()).expect("the closing action");
|
||||
fixture.click(&button).settle();
|
||||
} else {
|
||||
fixture.key(egui::Key::Escape, egui::Modifiers::NONE).settle();
|
||||
}
|
||||
let expected = if matches!(answer, Answer::Ok) { Closed::Ok } else { Closed::Cancel };
|
||||
assert_eq!(closed.get(), Some(expected), "{answer:?} reports its semantic result");
|
||||
assert_eq!(model.borrow().calls(), before_close, "closing calls no model mutation: {answer:?}");
|
||||
assert!(model.borrow().saved, "the framework leaves restoration to the app");
|
||||
}
|
||||
}
|
||||
|
||||
/// A host can omit Reset Section in either layout without leaving a hidden action behind.
|
||||
#[trial]
|
||||
fn an_unavailable_reset_section_cannot_reset_the_page_in_either_layout() {
|
||||
for layout in [PreferencesLayout::Paged, PreferencesLayout::Cards] {
|
||||
let model = Rc::new(RefCell::new(Model { draft: true, saved: true, ..Model::default() }));
|
||||
let shown = model.clone();
|
||||
let reset_label = Rc::new(RefCell::new(String::new()));
|
||||
let words = reset_label.clone();
|
||||
let mut state = PreferencesState::default();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
*words.borrow_mut() = Env::of(ui).words::<PreferencesWords>().reset_section.as_str().to_owned();
|
||||
let _ = PreferencesWindow::new(Bind::bound(&mut state))
|
||||
.mode(PreferencesMode::LiveCancel)
|
||||
.layout(layout)
|
||||
.embedded()
|
||||
.show(ui, &mut *shown.borrow_mut());
|
||||
});
|
||||
fixture.settle();
|
||||
let reset = fixture.by_label(reset_label.borrow().as_str()).expect("reset is available by default");
|
||||
let before = model.borrow().resets;
|
||||
fixture.click(&reset).settle();
|
||||
assert!(model.borrow().resets > before && !model.borrow().saved, "the default action resets and applies");
|
||||
|
||||
model.borrow_mut().reset_disabled = true;
|
||||
fixture.settle();
|
||||
assert!(fixture.by_label(reset_label.borrow().as_str()).is_none(), "the host can omit Reset Section");
|
||||
let snap = fixture.by_label("Snap").expect("the setting remains editable");
|
||||
fixture.click(&snap).settle();
|
||||
let before = model.borrow().calls();
|
||||
fixture.click(&reset).settle();
|
||||
assert_eq!(model.borrow().calls(), before, "the omitted action has no hit target");
|
||||
assert!(model.borrow().saved, "the edited value stays applied");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user