Bound unary sign parsing and preserve signs on length fields

This commit is contained in:
skylartaylor committed 2026-11-29 17:44:16 +01:00
1 parent b67e72ea6b
commit f2c57998d2
5 files changed
+57 -44

No files matched your search

+25 -25
View File
@@ -336,37 +336,22 @@ impl NumberCodec {
self
}
/// [`parse_tagged`](Self::parse_tagged), reading a share of the start value only when `share` and the codec both say
/// so: the number after an explicit `+` is absolute, so `+50%` in a share field is 50, not half the start again.
fn parse_tagged_with(&self, text: &str, start: &Option<f64>, share: bool) -> Result<(Option<f64>, ParseNote), NotAValue> {
let trimmed = text.trim();
if trimmed.is_empty() {
return Ok((None, ParseNote::default()));
}
fn parse_builtin(&self, trimmed: &str, start: Option<f64>) -> Result<(Option<f64>, ParseNote), NotAValue> {
if self.zoom {
return self.read_zoom(trimmed).map(|(number, note)| (Some(number), note));
}
// The `+` an explicit-plus field writes is the number's sign when it is typed back, not a relative edit: what
// follows, a number ("+2.50", "+ 2.50", "+٣") or an expression ("+(2+3)"), is read on its own, so it re-enters
// neither the reader's relative `+` (which would add it to the start value) nor the share of the start value.
// A lone "+" is no number, so it falls through to the reader, which refuses it.
// Whatever the reader accepts after the sign is read on its own; text it does not read (a word the field's
// `or_parse` stands for) falls through with its `+`, which is the text a custom parser is given.
if self.plus
&& let Some(rest) = trimmed.strip_prefix('+').map(str::trim_start)
&& !rest.is_empty()
&& let Ok(read) = self.parse_tagged_with(rest, &None, false)
// Without an edit-start operand the reader already treats a leading `+` as a unary sign. Take that
// path directly rather than retrying each shorter suffix, and leave signed shares as absolute amounts.
let absolute_plus = self.plus && trimmed.starts_with('+');
if self.share
&& !absolute_plus
&& let Some(share_of_start) = self.reader.share(trimmed)
{
return Ok(read);
}
if share && let Some(share_of_start) = self.reader.share(trimmed) {
return start.map(|start| (Some(start * share_of_start), ParseNote::default())).ok_or(NotAValue);
}
match self.reader.read_tagged(text, *start) {
match self.reader.read_tagged(trimmed, if absolute_plus { None } else { start }) {
Ok((number, tag)) => Ok((Some(number), ParseNote { unit: tag, ..ParseNote::default() })),
Err(rejected) => {
self.custom.as_ref().and_then(|parse| parse(text.trim())).map(|number| (Some(number), ParseNote::default())).ok_or(rejected)
}
Err(rejected) => self.custom.as_ref().and_then(|parse| parse(trimmed)).map(|number| (Some(number), ParseNote::default())).ok_or(rejected),
}
}
@@ -445,7 +430,7 @@ impl Codec for NumberCodec {
if let Some(parse) = &self.primary {
return parse(trimmed).filter(|number| number.is_finite()).map(|number| (Some(number), ParseNote::default())).ok_or(NotAValue);
}
self.parse_tagged_with(text, start, self.share)
self.parse_builtin(trimmed, *start)
}
/// Zoom typing takes ASCII digits, `/` and the decimal separator, with an optional minus; other fields take every character.
@@ -534,4 +519,19 @@ mod review_tests {
assert_eq!(share.parse("50%", &Some(10.0)).ok(), Some(Some(5.0)), "an unsigned one is the share of the start");
assert_eq!(share.parse("+50", &Some(10.0)).ok(), Some(Some(50.0)), "and a signed number is absolute too");
}
#[test]
fn explicit_plus_still_gives_the_authoritative_reader_the_whole_signed_input() {
let codec = NumberCodec::default().parse_with(|text| (text == "+12").then_some(17.0)).explicit_plus();
assert_eq!(codec.parse(" +12 ", &Some(50.0)), Ok(Some(17.0)));
assert_eq!(codec.parse("+(2+3)", &Some(50.0)), Err(NotAValue), "rejects instead of falling back to the expression reader");
assert_eq!(codec.format(&Some(17.0)), "+17");
}
#[test]
fn an_explicit_plus_codec_reads_a_long_run_of_unary_signs_without_recursing() {
let codec = NumberCodec::default().explicit_plus();
let long = "+ ".repeat(32_768);
assert_eq!(codec.parse(&format!("{long}--(2+3)"), &Some(10.0)), Ok(Some(5.0)));
assert_eq!(codec.parse(&long, &Some(10.0)), Err(NotAValue));
}
}
+8 -10
View File
@@ -198,15 +198,12 @@ impl Parse<'_> {
/// A factor; `scaled` says it starts a term, where a number with no unit counts as the reader's bare factor.
/// Otherwise it is a multiplier, which may be a percentage.
fn factor(&mut self, scaled: bool) -> Result<f64, NotAValue> {
match self.peek() {
Some('-') => {
self.at += 1;
self.factor(scaled).map(|value| -value)
}
Some('+') => {
self.at += 1;
self.factor(scaled)
}
let mut negative = false;
while let Some(sign @ ('+' | '-')) = self.peek() {
negative ^= sign == '-';
self.at += 1;
}
let value = match self.peek() {
Some('(') => {
self.at += 1;
let value = self.expr()?;
@@ -214,7 +211,8 @@ impl Parse<'_> {
Ok(value)
}
_ => self.quantity(scaled),
}
}?;
Ok(if negative { -value } else { value })
}
/// A number and the longest registered unit spelling at the start of the letters after it, or after a `/` when a
-8
View File
@@ -62,11 +62,3 @@ fn codec_override_preserves_formatting_filter_equality_and_all_default_grammars(
assert_eq!(default.clone().or_parse(|text| (text == "Auto").then_some(99.0)).parse("Auto", &None), Ok(Some(99.0)));
assert_eq!(default.zoom_typing().parse("8/4", &None), Ok(Some(200.0)));
}
#[test]
fn explicit_plus_still_gives_the_authoritative_reader_the_whole_signed_input() {
let codec = NumberCodec::default().parse_with(|text| (text == "+12").then_some(17.0)).explicit_plus();
assert_eq!(codec.parse(" +12 ", &Some(50.0)), Ok(Some(17.0)));
assert_eq!(codec.parse("+(2+3)", &Some(50.0)), Err(NotAValue), "rejects instead of falling back to the expression reader");
assert_eq!(codec.format(&Some(17.0)), "+17");
}
+1 -1
View File
@@ -440,7 +440,6 @@ impl Look {
Some(decimals) => field.fixed_decimals(decimals.min(12)),
None => field,
};
let field = if self.explicit_plus { field.explicit_plus() } else { field };
let field = match self.unit_kind {
Some(kind) => field.unit_kind(kind),
None => field,
@@ -460,6 +459,7 @@ impl Look {
None => field,
};
let field = if self.select_on_focus { field.select_on_focus() } else { field };
let field = if self.explicit_plus { field.explicit_plus() } else { field };
let field = match self.field_sizing {
Some(sizing) => field.sizing(sizing),
None => field,
@@ -3,6 +3,7 @@
use craft_ui::contract::{Bind, Show as _};
use craft_ui::form::SliderField;
use craft_ui::runtime::env::{LengthUnits, UnitKind};
use craft_ui::testing::{Fixture, trial};
use craft_ui::text::NumberField;
use egui::{Key, Modifiers};
@@ -65,3 +66,25 @@ fn a_slider_field_writes_its_value_with_the_sign_it_is_given() {
fixture.settle();
assert!(fixture.texts().iter().any(|painted| painted.text == "+2.5"), "the number shows its sign: {:?}", fixture.texts());
}
#[trial]
fn a_length_slider_field_uses_its_sign_without_adding_the_starting_length() {
let value = Rc::new(Cell::new(144.0));
let held = Rc::clone(&value);
let mut fixture = Fixture::new(move |ui| {
let mut now = held.get();
SliderField::new("Depth", Bind::bound(&mut now), 0.0..=720.0)
.lengths(LengthUnits::new(UnitKind::Points, UnitKind::Inches, 72.0))
.step(18.0)
.explicit_plus()
.show(ui);
held.set(now);
});
fixture.settle();
assert!(fixture.texts().iter().any(|text| text.text == "+2"), "the positive length shows its sign in inches");
let field = fixture.by_label("Depth").expect("the length field");
fixture.click(&field).settle();
fixture.key(Key::A, Modifiers::COMMAND).type_text("+1.25");
fixture.key(Key::Enter, Modifiers::NONE).settle();
assert_eq!(value.get(), 90.0, "the typed length is 1.25 inches, not 2 + 1.25 inches");
}