mirror of
https://github.com/storytold/craft-libs.git
synced 2026-12-01 10:48:15 +01:00
Merge #4383 into the batch
This commit is contained in:
commit
0ef4e09a9b
6 files changed
+220
-11
No files matched your search
@@ -640,6 +640,8 @@ pub(crate) struct RowOptions {
|
||||
codec: Option<NumberCodec>,
|
||||
/// The step arrows of a number row's field.
|
||||
step_arrows: Option<StepArrows>,
|
||||
/// A number row takes whole numbers only ([`Param::whole_only`]).
|
||||
whole_only: bool,
|
||||
/// The labelled marks of a range row's slider.
|
||||
marks: Vec<(f64, Label)>,
|
||||
/// The link the row's help button reports ([`Param::help_link`]).
|
||||
@@ -697,6 +699,11 @@ impl RowOptions {
|
||||
self.step_arrows
|
||||
}
|
||||
|
||||
/// Whether a number row takes whole numbers only.
|
||||
pub(crate) fn whole_only(&self) -> bool {
|
||||
self.whole_only
|
||||
}
|
||||
|
||||
/// The labelled marks of a range row's slider.
|
||||
pub(crate) fn marks(&self) -> &[(f64, Label)] {
|
||||
&self.marks
|
||||
@@ -1102,6 +1109,17 @@ impl Param {
|
||||
self
|
||||
}
|
||||
|
||||
/// The `Number` row takes whole numbers only (`NumberField::whole_only`): a typed number with a fraction commits
|
||||
/// rounded to the nearest whole number with the range alert ([`HostedParamDialog::take_range_alert`](super::HostedParamDialog::take_range_alert)), and the
|
||||
/// Enter that commits it leaves the dialog open, as one past the range does in such a row. It applies to a plain
|
||||
/// number row and to one shown in a shared unit ([`Param::number_in_units`]); a row with a unit menu of its own
|
||||
/// ([`Param::number_with_units`]) does not take it.
|
||||
#[must_use]
|
||||
pub fn whole_only(mut self) -> Self {
|
||||
self.options.get_or_insert_default().whole_only = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Passes labelled `marks` to the `Range` row's slider.
|
||||
#[must_use]
|
||||
pub fn marks_labelled<L: Into<Label>>(mut self, marks: impl IntoIterator<Item = (f64, L)>) -> Self {
|
||||
|
||||
@@ -1007,6 +1007,9 @@ impl<'p> Pass<'p> {
|
||||
if let Some(arrows) = option.step_arrows() {
|
||||
field = field.step_arrows(arrows);
|
||||
}
|
||||
if option.whole_only() {
|
||||
field = field.whole_only(true);
|
||||
}
|
||||
let shown = field.show(ui);
|
||||
self.alert(shown.out_of_range);
|
||||
self.unparsed |= shown.edit.unparsed;
|
||||
@@ -1038,6 +1041,9 @@ impl<'p> Pass<'p> {
|
||||
if let Some(range) = range.clone() {
|
||||
field = field.range(range);
|
||||
}
|
||||
if option.whole_only() {
|
||||
field = field.whole_only(true);
|
||||
}
|
||||
let shown = field.show(ui);
|
||||
self.alert(shown.out_of_range);
|
||||
self.unparsed |= shown.edit.unparsed;
|
||||
|
||||
@@ -8,11 +8,11 @@ use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{Bind, Outcome as _, Props as _, Role, SaveKey, Show as _, clicked};
|
||||
use craft_ui::dialog::{DialogHost, DialogResult, HeldAnswer, HeldOk, dialog_id};
|
||||
use craft_ui::patterns::form_dialogs::{
|
||||
DialogFields, FieldValue, FormButtons, FormDialog, HostedParamDialog, PagerStep, PanePager, Param, ParamDialog, ParamKind, ParamLayout,
|
||||
ParamResult, PreviewState,
|
||||
DialogFields, FieldValue, FormButtons, FormDialog, HostedParamDialog, NumberUnit, PagerStep, PanePager, Param, ParamDialog, ParamKind,
|
||||
ParamLayout, ParamResult, PreviewState,
|
||||
};
|
||||
use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::runtime::env::{Label, UnitKind};
|
||||
use craft_ui::runtime::memory::{Lifetime, saved_value};
|
||||
use craft_ui::runtime::overlay::CloseReason;
|
||||
use craft_ui::sections::{DialogRole, FooterButton};
|
||||
@@ -1016,6 +1016,87 @@ fn a_row_whose_text_does_not_parse_holds_ok() {
|
||||
assert_eq!(answered.borrow().as_ref().and_then(|fields| fields.int("size")), Some(42), "OK answers the typed value");
|
||||
}
|
||||
|
||||
/// Where a test dialog files the values of its answer.
|
||||
type Answered = Rc<RefCell<Option<DialogFields>>>;
|
||||
|
||||
/// An Opacity row of whole percents from 1 to 100.
|
||||
fn opacity() -> Param {
|
||||
Param::new("opacity", "Opacity", ParamKind::number(Some(1.0), Some(100.0), 100.0, 1.0, 0))
|
||||
}
|
||||
|
||||
/// Runs a one-row dialog over `row`, labelled Opacity; the values of its answer and the number of range alerts it
|
||||
/// raised are filed in the returned cells.
|
||||
fn opacity_row(row: Param) -> (Fixture, Answered, Rc<Cell<usize>>) {
|
||||
let (answered, alerts) = (Rc::new(RefCell::new(None::<DialogFields>)), Rc::new(Cell::new(0)));
|
||||
let (out, seen) = (Rc::clone(&answered), Rc::clone(&alerts));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let shown = ParamDialog::new("row", "Row", vec![row.clone()]).show(ui);
|
||||
if shown.rows.is_some_and(|rows| rows.out_of_range.is_some()) {
|
||||
seen.set(seen.get() + 1);
|
||||
}
|
||||
if let Some(result) = shown.result {
|
||||
*out.borrow_mut() = Some(result.fields);
|
||||
}
|
||||
});
|
||||
// A decimal point, whatever the machine's region is. English is the source language, not a catalog.
|
||||
let (i18n, problems) = craft_i18n::I18n::from_owned(
|
||||
[(
|
||||
"de".to_owned(),
|
||||
String::new(),
|
||||
"@id trial.save Speichern
|
||||
"
|
||||
.to_owned(),
|
||||
)],
|
||||
&["de"],
|
||||
);
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
i18n.set_format(craft_i18n::Format::from_tag("en"));
|
||||
fixture.host(std::sync::Arc::new(
|
||||
craft_host::Host::builder(craft_host::AppInfo { id: "trial", name: "Trial", version: "0" }).i18n(std::sync::Arc::new(i18n)).build(),
|
||||
));
|
||||
(fixture, answered, alerts)
|
||||
}
|
||||
|
||||
// In a whole-only row, the Enter that commits a typed fraction raises the range alert and leaves the dialog open with
|
||||
// the rounded value, which the next Enter answers; a whole number answers at once. A row shown in a shared unit does
|
||||
// the same. A row that is not whole-only keeps the fraction and answers it.
|
||||
#[trial]
|
||||
fn enter_over_a_fraction_in_a_whole_only_row_raises_the_alert_and_holds_ok() {
|
||||
let typed_enter = |fixture: &mut Fixture, text: &str| {
|
||||
let field = fixture.by_label("Opacity").expect("the opacity row has a field");
|
||||
fixture.click(&field).settle();
|
||||
fixture.key(Key::A, Modifiers::COMMAND).type_text(text);
|
||||
fixture.key(Key::Enter, Modifiers::NONE).settle();
|
||||
};
|
||||
let opacity_of = |answered: &Answered| answered.borrow().as_ref().and_then(|fields| fields.number("opacity"));
|
||||
|
||||
let percent = vec![NumberUnit::new("percent", UnitKind::Percent, "Percent", 1.0)];
|
||||
let rows = [
|
||||
("a plain row", opacity().whole_only()),
|
||||
("a row in a shared unit", Param::number_in_units("opacity", "Opacity", 100.0, 1.0, 0, "units", percent).whole_only()),
|
||||
];
|
||||
for (kind, row) in rows {
|
||||
let (mut fixture, answered, alerts) = opacity_row(row);
|
||||
fixture.settle();
|
||||
typed_enter(&mut fixture, "20.5");
|
||||
assert_eq!(alerts.get(), 1, "{kind}: the fraction raises the range alert");
|
||||
assert!(answered.borrow().is_none(), "{kind}: the Enter that raised it answers nothing");
|
||||
fixture.key(Key::Enter, Modifiers::NONE).settle();
|
||||
assert_eq!(opacity_of(&answered), Some(21.0), "{kind}: the next Enter answers the rounded value");
|
||||
assert_eq!(alerts.get(), 1, "{kind}: and raises no second alert");
|
||||
}
|
||||
|
||||
let (mut fixture, answered, alerts) = opacity_row(opacity().whole_only());
|
||||
fixture.settle();
|
||||
typed_enter(&mut fixture, "50.0");
|
||||
assert_eq!((opacity_of(&answered), alerts.get()), (Some(50.0), 0), "a whole number answers at once");
|
||||
|
||||
let (mut fixture, answered, alerts) = opacity_row(opacity());
|
||||
fixture.settle();
|
||||
typed_enter(&mut fixture, "20.5");
|
||||
assert_eq!((opacity_of(&answered), alerts.get()), (Some(20.5), 0), "a row that is not whole-only answers the fraction");
|
||||
}
|
||||
|
||||
// Shift+Enter in a row's field confirms the dialog with the typed value.
|
||||
#[trial]
|
||||
fn shift_enter_in_a_row_answers_ok() {
|
||||
|
||||
@@ -21,8 +21,8 @@ use crate::runtime::frame;
|
||||
use crate::style::{ComponentStyle, StyleColor, StyleCx, SurfaceLook, TextLook, TypeRole};
|
||||
use craft_behavior::nav::{LARGE_STEPS, StepResult, ValueAxes, ValueSteps};
|
||||
use craft_behavior::{
|
||||
Codec, ColumnKey, Granularity, HitLevel, HitPriority, HoldRepeat, Metrics, MoveMods, NavMove, NumberCodec, PartKey, PressPhase, Sense, ValueDrag,
|
||||
decimals_for_step, wheel_step,
|
||||
Codec, ColumnKey, Granularity, HitLevel, HitPriority, HoldRepeat, Intent, Metrics, MoveMods, NavMove, NumberCodec, PartKey, PressPhase, Sense,
|
||||
ValueDrag, decimals_for_step, wheel_step,
|
||||
};
|
||||
use craft_theme::{Rgba, Stateful, States};
|
||||
use egui::{CornerRadius, Rect, Vec2};
|
||||
@@ -204,6 +204,12 @@ pub struct NumberField<'a, V: NumberValue + 'static = Option<f64>> {
|
||||
/// decimals of its own shows none when this is 0 ("10%").
|
||||
#[prop]
|
||||
commit_decimals: Option<usize>,
|
||||
/// The field takes whole numbers only, as `commit_decimals(0)` does, and a typed number with a fraction is
|
||||
/// reported like one past the range ([`NumberOutput::out_of_range`]): it commits rounded to the nearest whole
|
||||
/// number, half away from zero, then held to the range. The Enter that commits a reported value stays with the
|
||||
/// field, so an enclosing dialog's default button waits until the host has shown its alert.
|
||||
#[prop]
|
||||
whole_only: bool,
|
||||
/// An empty field means automatic: it shows the "Auto" word as its placeholder.
|
||||
#[prop]
|
||||
automatic: bool,
|
||||
@@ -319,6 +325,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
|
||||
mixed_word: false,
|
||||
derived: false,
|
||||
commit_decimals: None,
|
||||
whole_only: false,
|
||||
fixed_decimals: None,
|
||||
explicit_plus: false,
|
||||
name_number: None,
|
||||
@@ -506,6 +513,11 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
|
||||
value.and_then(NumberValue::number).map(|stored| self.to_shown(stored))
|
||||
}
|
||||
|
||||
/// The decimals a committed value is rounded to: none for a field that takes whole numbers only.
|
||||
fn commit_places(&self) -> Option<usize> {
|
||||
if self.whole_only { Some(0) } else { self.commit_decimals }
|
||||
}
|
||||
|
||||
/// Whether the field counts percent: it shows its sign right after the number.
|
||||
fn is_percent(&self) -> bool {
|
||||
self.codec.is_none() && self.unit_kind == Some(UnitKind::Percent)
|
||||
@@ -516,7 +528,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
|
||||
/// (`commit_decimals(0)`).
|
||||
fn percent_decimals(&self) -> Option<usize> {
|
||||
(self.is_percent() && self.fixed_decimals.is_none() && self.max_decimals.is_none()).then(|| match self.precision {
|
||||
NumberPrecision::Standard => self.commit_decimals.unwrap_or(1).min(1),
|
||||
NumberPrecision::Standard => self.commit_places().unwrap_or(1).min(1),
|
||||
NumberPrecision::Measured => 0,
|
||||
})
|
||||
}
|
||||
@@ -586,7 +598,8 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
|
||||
inner: self.number_codec(&env.units()),
|
||||
rule: self.rule(),
|
||||
snap: self.snap_typed,
|
||||
decimals: self.commit_decimals,
|
||||
decimals: self.commit_places(),
|
||||
whole_only: self.whole_only,
|
||||
mixed,
|
||||
positive_only: self.positive_only,
|
||||
names,
|
||||
@@ -696,7 +709,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
|
||||
typed,
|
||||
kept: kept.unwrap_or_else(|| rule.settle(typed)),
|
||||
range: rule.bounds(),
|
||||
whole: self.commit_decimals == Some(0) || self.decimals() == 0,
|
||||
whole: self.commit_places() == Some(0) || self.decimals() == 0,
|
||||
unit: self.unit.clone(),
|
||||
unit_kind: self.unit_kind,
|
||||
decimals: self.shown_decimals(),
|
||||
@@ -976,6 +989,11 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
|
||||
}
|
||||
cx.set(V::of_number(self.to_stored(rule.settle(next))));
|
||||
}
|
||||
// The Enter that committed a value the host reports is the alert's: the enclosing dialog does not take it as
|
||||
// its default button.
|
||||
if self.whole_only && cx.text(&text_part::<V>()).and_then(|outcome| outcome.committed).is_some_and(|note| note.held.is_some()) {
|
||||
cx.intents().take(Intent::Submit);
|
||||
}
|
||||
}
|
||||
|
||||
/// The edit menu, the presets list and the popup slider.
|
||||
|
||||
@@ -108,6 +108,8 @@ pub(super) struct Ruled<V> {
|
||||
pub(super) rule: Rule,
|
||||
pub(super) snap: bool,
|
||||
pub(super) decimals: Option<usize>,
|
||||
/// A typed number with a fraction is held like one past the range (`NumberField::whole_only`).
|
||||
pub(super) whole_only: bool,
|
||||
pub(super) mixed: bool,
|
||||
pub(super) positive_only: bool,
|
||||
pub(super) names: Vec<(u32, String)>,
|
||||
@@ -126,6 +128,7 @@ impl<V> Clone for Ruled<V> {
|
||||
rule: self.rule.clone(),
|
||||
snap: self.snap,
|
||||
decimals: self.decimals,
|
||||
whole_only: self.whole_only,
|
||||
mixed: self.mixed,
|
||||
positive_only: self.positive_only,
|
||||
names: self.names.clone(),
|
||||
@@ -207,8 +210,9 @@ impl<V: NumberValue> Codec for Ruled<V> {
|
||||
self.parse_tagged(text, start).map(|(value, _)| value)
|
||||
}
|
||||
|
||||
/// The inner codec's note, with `held` set to the number read (in shown units) when it lies outside the range;
|
||||
/// snapping and rounding are not holding. A name or a blank gives the default note.
|
||||
/// The inner codec's note, with `held` set to the number read (in shown units) when it lies outside the range, or
|
||||
/// has a fraction in a field that takes whole numbers only; snapping and other rounding are not holding. A name or
|
||||
/// a blank gives the default note.
|
||||
fn parse_tagged(&self, text: &str, start: &V) -> Result<(V, ParseNote), NotAValue> {
|
||||
if let Some(name) = self.name_of(text) {
|
||||
return Ok((name, ParseNote::default()));
|
||||
@@ -222,7 +226,8 @@ impl<V: NumberValue> Codec for Ruled<V> {
|
||||
if self.positive_only && number <= 0.0 {
|
||||
return Err(NotAValue);
|
||||
}
|
||||
note.held = (number < self.rule.low || number > self.rule.high).then_some(number);
|
||||
let fraction = self.whole_only && number.fract() != 0.0;
|
||||
note.held = (fraction || number < self.rule.low || number > self.rule.high).then_some(number);
|
||||
Ok((V::of_number(self.held(number) / self.scale), note))
|
||||
}
|
||||
None => V::blank().map(|blank| (blank, ParseNote::default())).ok_or(NotAValue),
|
||||
|
||||
@@ -210,6 +210,87 @@ fn a_localised_decimal_types_in() {
|
||||
assert_eq!(typed(Some(host), None, "12,5"), Some(12.5));
|
||||
}
|
||||
|
||||
/// A whole-only field over 1 to 100 under `host`'s locale, with `text` typed over 50 and committed with Tab: the value
|
||||
/// kept and the range alert the commit reported.
|
||||
fn whole_typed(host: Option<Arc<Host>>, text: &str) -> (Option<f64>, Option<craft_ui::text::RangeAlert>) {
|
||||
let mut frames = Frames::new();
|
||||
if let Some(host) = host {
|
||||
frames.host(host);
|
||||
}
|
||||
let value = RefCell::new(Some(50.0));
|
||||
let alert = RefCell::new(None);
|
||||
let at = Cell::new(Pos2::ZERO);
|
||||
let mut show = |ui: &mut Ui| {
|
||||
let mut guard = value.borrow_mut();
|
||||
let out = NumberField::new("Opacity", Bind::bound(&mut *guard)).id_salt("opacity").range(1.0..=100.0).whole_only(true).show(ui);
|
||||
at.set(out.response.rect.center());
|
||||
if out.out_of_range.is_some() {
|
||||
*alert.borrow_mut() = out.out_of_range.clone();
|
||||
}
|
||||
// Where Tab takes the focus, so the field commits.
|
||||
NumberField::new("Other", Bind::bound(&mut Some(1.0))).id_salt("other").show(ui);
|
||||
};
|
||||
frames.idle(3, &mut show);
|
||||
click(&mut frames, at.get(), &mut show);
|
||||
frames.frame(vec![key_press(Key::A, Modifiers::COMMAND)], &mut show);
|
||||
frames.frame(vec![Event::Text(text.into())], &mut show);
|
||||
frames.idle(1, &mut show);
|
||||
frames.frame(vec![key_press(Key::Tab, Modifiers::NONE)], &mut show);
|
||||
frames.idle(3, &mut show);
|
||||
(value.into_inner(), alert.into_inner())
|
||||
}
|
||||
|
||||
/// A host whose number format is the region `tag`'s, whatever the machine's region is.
|
||||
fn region_host(tag: &str) -> Arc<Host> {
|
||||
// English is the source language, not a catalog: one catalog loaded, the format set apart.
|
||||
let (i18n, problems) = craft_i18n::I18n::from_owned(
|
||||
[(
|
||||
"de".to_owned(),
|
||||
String::new(),
|
||||
"@id trial.save Speichern
|
||||
"
|
||||
.to_owned(),
|
||||
)],
|
||||
&["de"],
|
||||
);
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
i18n.set_format(craft_i18n::Format::from_tag(tag));
|
||||
Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).i18n(Arc::new(i18n)).build())
|
||||
}
|
||||
|
||||
/// A field that takes whole numbers only rounds a typed fraction to the nearest whole number, half up, and reports it
|
||||
/// as it reports a value past the range, written with the locale's decimal symbol; a zero fraction or a trailing
|
||||
/// separator is a whole number and reports nothing. A fraction past the range is held to its end.
|
||||
#[trial]
|
||||
fn a_whole_only_field_rounds_a_typed_fraction_and_reports_it() {
|
||||
let comma = region_host("de");
|
||||
for (text, kept) in [
|
||||
("12,3", 12.0),
|
||||
("12,4", 12.0),
|
||||
("12,5", 13.0),
|
||||
("12,7", 13.0),
|
||||
("1,5", 2.0),
|
||||
("99,5", 100.0),
|
||||
("50,01", 50.0),
|
||||
("0,4", 1.0),
|
||||
("150,5", 100.0),
|
||||
] {
|
||||
let (value, alert) = whole_typed(Some(Arc::clone(&comma)), text);
|
||||
assert_eq!(value, Some(kept), "{text}");
|
||||
let alert = alert.unwrap_or_else(|| panic!("{text} is reported"));
|
||||
assert!(alert.whole && alert.kept == kept && alert.typed != kept, "{text}: {alert:?}");
|
||||
}
|
||||
for (text, kept) in [("50,0", 50.0), ("50,00", 50.0), ("12,", 12.0)] {
|
||||
assert_eq!(whole_typed(Some(Arc::clone(&comma)), text), (Some(kept), None), "{text} is a whole number");
|
||||
}
|
||||
for (text, kept) in [("12.3", 12.0), ("12.7", 13.0)] {
|
||||
let (value, alert) = whole_typed(Some(region_host("en")), text);
|
||||
assert_eq!(value, Some(kept), "{text} under a decimal point");
|
||||
assert!(alert.is_some(), "{text} is reported");
|
||||
}
|
||||
assert_eq!(whole_typed(Some(region_host("en")), "42"), (Some(42.0), None), "a whole number in range reports nothing");
|
||||
}
|
||||
|
||||
/// A field over 0 to 100 with a popup slider.
|
||||
fn with_slider(ui: &mut Ui, data: &mut craft_ui::testing::StoryData) -> craft_ui::testing::StoryOutput {
|
||||
NumberField::new("Opacity", data.bind("value", Some(50.0))).range(0.0..=100.0).popup_slider(0.0..=100.0).show(ui).into()
|
||||
|
||||
Reference in new issue
Block a user