Merge #2384: Fit the full zoom percentage in the status bar

This commit is contained in:
David Mann committed 2026-11-20 12:51:37 +01:00
commit e350ca1a17
5 files changed
+176 -15

No files matched your search

+1 -1
View File
@@ -219,7 +219,7 @@ impl<'a> StatusReadout<'a> {
};
let field = Field::new(words.readout_zoom.clone())
.side(SideLabel::new().kind(LabelKind::Hidden))
.show(ui, |ui, _| ZoomField::new(words.readout_zoom.clone(), current, document).scrub(true).show(ui));
.show(ui, |ui, _| ZoomField::new(words.readout_zoom.clone(), current, document).scrub(true).status_bar().show(ui));
let field = field.inner.map(|zoom| {
invalid_zoom = zoom.invalid_zoom;
events = zoom.view;
+43 -8
View File
@@ -22,8 +22,9 @@ use craft_behavior::nav::{LARGE_STEPS, StepResult, ValueAxes, ValueSteps};
use craft_behavior::{
Codec, ColumnKey, HitLevel, HitPriority, Metrics, NavMove, NumberCodec, PartKey, PressPhase, Sense, ValueDrag, decimals_for_step, wheel_step,
};
use craft_theme::{Stateful, States};
use egui::{Rect, Vec2};
use craft_theme::{Rgba, Stateful, States};
use egui::{CornerRadius, Rect, Vec2};
use std::borrow::Cow;
use std::marker::PhantomData;
use std::ops::RangeInclusive;
@@ -128,6 +129,8 @@ pub struct NumberField<'a, V: NumberValue + 'static = Option<f64>> {
/// Whether the unit is drawn inside the field or left to the host to draw after it.
#[prop]
unit_placement: UnitPlacement,
#[style_key]
status_zoom: bool,
/// The rows of the list a chevron after the field opens; Alt+Down opens it too.
#[prop]
presets: Option<&'a [Entry<NumberPick>]>,
@@ -203,6 +206,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
stepper: None,
unit: None,
unit_placement: UnitPlacement::Inside,
status_zoom: false,
presets: None,
popup_slider: None,
snap_popup_slider: true,
@@ -238,6 +242,13 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
self
}
/// Keeps the entire zoom percentage together in an unframed well in the status bar.
#[must_use]
pub(super) fn status_zoom(mut self) -> Self {
self.status_zoom = true;
self.sizing(Sizing::Content)
}
/// A drag on the field's side label scrubs the value too, with or without the focus in the field.
#[must_use]
pub fn scrub_by_label(mut self) -> Self {
@@ -261,7 +272,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
/// The unit drawn inside the field after the number: the field's own, else the symbol of its unit kind; none when
/// the host draws it after the field.
fn shown_unit(&self, units: &Units) -> Option<Label> {
if self.unit_placement == UnitPlacement::After {
if self.status_zoom || self.unit_placement == UnitPlacement::After {
return None;
}
self.unit.clone().or_else(|| self.unit_kind.map(|kind| units.symbol(kind).into()))
@@ -287,6 +298,11 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
value.and_then(NumberValue::number).map(|stored| self.to_shown(stored))
}
/// Whether the field uses the dash for a missing or invalid value.
fn shows_blank(&self, shown: Option<&V>) -> bool {
shown.is_none() || non_finite(shown) || (self.status_zoom && shown.and_then(NumberValue::number).is_none())
}
/// The field's codec: the one set, else the env's locale and the spellings of the unit kind (a length field
/// reads every length spelling).
fn number_codec(&self, units: &Units) -> NumberCodec {
@@ -334,6 +350,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
decimals: self.commit_decimals,
mixed,
names,
suffix: self.status_zoom.then(|| units.symbol(UnitKind::Percent)),
scale: self.scale,
value: PhantomData,
}
@@ -403,12 +420,23 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
type Style = NumberStyle;
type Output = NumberOutput<V>;
fn style(cx: &StyleCx<'_>, _: NumberFieldStyleKey<V>) -> NumberStyle {
fn style(cx: &StyleCx<'_>, key: NumberFieldStyleKey<V>) -> NumberStyle {
let field = FieldStyle::at(cx);
let mut surface = field.surface.clone();
if key.status_zoom {
surface.kind = None;
surface.radius = CornerRadius::ZERO;
// Use the theme's recessed field color; focus and invalid states still use the usual borders.
surface.fill = Stateful::new(cx.color(cx.tokens.color.surface.sunken));
let clear = cx.color(Rgba::TRANSPARENT);
if let Some(border) = &mut surface.border {
border.off = States::new(clear, clear, clear, clear);
}
}
let faint = cx.color(cx.tokens.color.text.faint);
let muted = cx.color(cx.tokens.color.text.muted);
NumberStyle {
surface: field.surface.clone(),
surface,
// The width is the value area, at most a number cell, and the adornments beside it, at least a cell
// (`measure`); the style's minimum is only the height.
metrics: field.clone().sized_by_content().metrics,
@@ -438,8 +466,15 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
let content = content_sized(cx);
// A mixed field is sized as it is with a value, so it keeps its width when the selection changes.
let blank = V::blank().unwrap_or_else(|| V::of_number(self.rule().blank()));
let sample = codec.sample(cx.value().unwrap_or(&blank));
let mut text = cx.field_text(&TextRun::new(sample.as_ref()).role(TypeRole::Mono));
let shown = cx.value();
let no_zoom_value = self.status_zoom && self.shows_blank(shown);
let (sample, role) = if no_zoom_value {
// Text editors draw their hint in the proportional face.
(Cow::Borrowed(BLANK), self.options.role)
} else {
(codec.sample(shown.unwrap_or(&blank)), TypeRole::Mono)
};
let mut text = cx.field_text(&TextRun::new(sample.as_ref()).role(role));
if content {
text.x = crate::layout::ambient_width(cx.ui.ctx(), &VALUES, text.x).map_or(text.x, |width| width.max(text.x));
}
@@ -474,7 +509,7 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
self.options.steps_value = self.presets.is_none() && self.popup_slider.is_none();
let shown = cx.value();
if self.options.placeholder.is_none() {
if shown.is_none() || non_finite(shown) {
if self.shows_blank(shown) {
self.options.placeholder = Some(BLANK.into());
} else if self.automatic {
self.options.placeholder = Some(cx.words::<TextWords>().automatic.clone());
+20 -5
View File
@@ -110,6 +110,7 @@ pub(super) struct Ruled<V> {
pub(super) decimals: Option<usize>,
pub(super) mixed: bool,
pub(super) names: Vec<(u32, String)>,
pub(super) suffix: Option<String>,
/// How many shown units make one stored unit (1 for a field that shows what it holds).
pub(super) scale: f64,
pub(super) value: PhantomData<fn() -> V>,
@@ -124,6 +125,7 @@ impl<V> Clone for Ruled<V> {
decimals: self.decimals,
mixed: self.mixed,
names: self.names.clone(),
suffix: self.suffix.clone(),
scale: self.scale,
value: PhantomData,
}
@@ -141,6 +143,19 @@ impl<V: NumberValue> Ruled<V> {
v.number().filter(|number| number.is_finite()).map(|number| number * self.scale)
}
fn with_suffix(&self, mut text: String) -> String {
if let Some(suffix) = &self.suffix
&& !text.is_empty()
{
text.push_str(suffix);
}
text
}
fn without_suffix<'a>(&self, text: &'a str) -> &'a str {
self.suffix.as_deref().and_then(|suffix| text.trim_end().strip_suffix(suffix)).unwrap_or(text)
}
/// The name `text` spells, as a value of the field's type.
fn name_of(&self, text: &str) -> Option<V> {
let text = text.trim();
@@ -158,7 +173,7 @@ impl<V: NumberValue> Codec for Ruled<V> {
}
match v.named().and_then(|id| self.names.iter().find(|(name, _)| *name == id)) {
Some((_, label)) => label.clone(),
None => self.inner.format(&self.shown(v)),
None => self.with_suffix(self.inner.format(&self.shown(v))),
}
}
@@ -175,7 +190,7 @@ impl<V: NumberValue> Codec for Ruled<V> {
if text.trim().is_empty() && (self.mixed || V::blank().is_none()) {
return Err(NotAValue);
}
let (read, mut note) = self.inner.parse_tagged(text, &self.shown(start))?;
let (read, mut note) = self.inner.parse_tagged(self.without_suffix(text), &self.shown(start))?;
match read {
Some(number) => {
note.held = (number < self.rule.low || number > self.rule.high).then_some(number);
@@ -186,7 +201,7 @@ impl<V: NumberValue> Codec for Ruled<V> {
}
fn applies_as_typed(&self, text: &str) -> bool {
!self.snap && !self.mixed && is_plain(text) && matches!(self.inner.parse(text, &None), Ok(Some(_)))
!self.snap && !self.mixed && is_plain(text) && matches!(self.inner.parse(self.without_suffix(text), &None), Ok(Some(_)))
}
fn filter(&self, c: char) -> bool {
@@ -196,7 +211,7 @@ impl<V: NumberValue> Codec for Ruled<V> {
fn normalise(&self, text: &str, v: &V) -> String {
match v.named() {
Some(_) => self.format(v),
None => self.inner.normalise(text, &self.shown(v)),
None => self.with_suffix(self.inner.normalise(self.without_suffix(text), &self.shown(v))),
}
}
@@ -210,7 +225,7 @@ impl<V: NumberValue> Codec for Ruled<V> {
// A field that rounds what it commits shows no more places than that.
None if self.rule.low.is_finite() && self.rule.high.is_finite() => {
let codec = self.decimals.map_or_else(|| self.inner.clone(), |places| self.inner.clone().at_most(places));
Cow::Owned(codec.widest(&(self.rule.low..=self.rule.high)))
Cow::Owned(self.with_suffix(codec.widest(&(self.rule.low..=self.rule.high))))
}
None => Cow::Owned(self.format(current)),
}
+12 -1
View File
@@ -32,12 +32,13 @@ pub struct ZoomField {
stepper: bool,
scrub: bool,
enabled: bool,
status_bar: bool,
}
impl ZoomField {
/// A zoom field named `label` over `view` (`None` when no view is known) of a document of `document` units.
pub fn new(label: impl Into<Label>, view: Option<CanvasView>, document: Size) -> Self {
ZoomField { label: label.into(), view, document, stepper: false, scrub: false, enabled: true }
ZoomField { label: label.into(), view, document, stepper: false, scrub: false, enabled: true, status_bar: false }
}
/// The arrow keys and the wheel step along the zoom ladder.
@@ -61,6 +62,13 @@ impl ZoomField {
self
}
/// Uses the status bar's space and field appearance.
#[must_use]
pub(crate) fn status_bar(mut self) -> Self {
self.status_bar = true;
self
}
/// Shows the field and reports the view changes it made.
pub fn show(self, ui: &mut Ui) -> ZoomFieldOutput {
let env = Env::of(ui);
@@ -83,6 +91,9 @@ impl ZoomField {
if self.scrub {
field = field.scrub_by_label();
}
if self.status_bar {
field = field.status_zoom();
}
let shown = field.show(ui);
let invalid_zoom = range.filter(|_| shown.cut).map(|range| InvalidZoom { low: *range.start(), high: *range.end() });
let view = match self.view {
+100
View File
@@ -322,6 +322,106 @@ fn a_narrow_bar_gives_way_from_its_end_so_the_message_elides_before_the_readout(
assert!(!cut(&narrow, "Doc"), "the readout's text was cut while the message after it could still give way");
}
fn status_zoom(zoom: f64, comma: bool) -> Fixture {
let mut fixture = Fixture::new(move |ui| {
let size = Size::new(2000.0, 1500.0);
let canvas = Rect::from_min_max(egui::Pos2::ZERO, egui::Pos2::new(800.0, 600.0));
let scale = craft_ui::runtime::env::Env::of(ui).scale.0;
let view = CanvasView::new(canvas, Point::new(1000.0, 750.0), zoom / f64::from(scale));
Bar::new("Status", BarKind::Status).show(ui, |ui, _| {
StatusReadout::new(Bind::given(view), size, StatusItem::DocumentSizes, &StatusValues::default()).show(ui);
});
});
if comma {
use craft_host::{AppInfo, Host};
use std::sync::Arc;
let (i18n, problems) = craft_i18n::I18n::from_owned([("de".to_owned(), String::new(), String::new())], &["de"]);
assert!(problems.is_empty(), "{problems:?}");
i18n.set_format(craft_i18n::Format::from_tag("de"));
fixture.host(Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).i18n(Arc::new(i18n)).build()));
}
fixture.room(Vec2::new(600.0, 80.0)).settle();
fixture
}
#[trial]
fn the_status_zoom_shows_its_complete_value_and_percent() {
for (zoom, comma, expected) in [(0.7969, false, "79.69%"), (0.7969, true, "79,69%"), (32.0, false, "3200%"), (31.9999, false, "3199.99%")] {
let fixture = status_zoom(zoom, comma);
let number = fixture.texts().iter().find(|text| text.text == expected).expect(expected);
assert!(
!number.elided && number.rect.min.x + SLACK >= number.clip.min.x && number.rect.max.x <= number.clip.max.x + SLACK,
"{expected} is clipped: {:?} outside {:?}",
number.rect,
number.clip,
);
}
}
#[trial]
fn the_status_zoom_shows_the_complete_dash_without_a_view() {
use craft_behavior::Mixed;
use craft_ui::runtime::env::Scale;
let mut fixture = Fixture::new(|ui| {
let mut values = StatusValues::default();
values.document_sizes = Some((1024, 4096));
Bar::new("Status", BarKind::Status).show(ui, |ui, _| {
StatusReadout::new(Bind::given(Mixed::<CanvasView>::Mixed), Size::new(2000.0, 1500.0), StatusItem::DocumentSizes, &values).show(ui);
});
});
fixture.scale(Scale::new(1.25)).room(Vec2::new(600.0, 80.0)).settle();
let zoom = fixture.by_label("Zoom").expect("the status zoom field");
assert!(fixture.tree().is_disabled_key(zoom.node));
let dash = fixture.texts().iter().find(|text| text.text == "—" && zoom.rect.contains(text.rect.center())).expect("a dash inside the zoom field");
assert!(
!dash.elided && dash.rect.min.x + SLACK >= dash.clip.min.x && dash.rect.max.x <= dash.clip.max.x + SLACK,
"the empty zoom dash is clipped: {:?} outside {:?}",
dash.rect,
dash.clip,
);
}
#[trial]
fn the_status_zoom_still_scrubs_and_applies_edited_text() {
use egui::{Event, Key, Modifiers};
let view = Rc::new(Cell::new(CanvasView::new(Rect::from_min_size(egui::Pos2::ZERO, Vec2::new(800.0, 600.0)), Point::ZERO, 1.0)));
let shown = view.clone();
let committed = Rc::new(Cell::new(None));
let seen = committed.clone();
let mut fixture = Fixture::new(move |ui| {
let mut view = shown.get();
Bar::new("Status", BarKind::Status).show(ui, |ui, _| {
let output =
StatusReadout::new(Bind::bound(&mut view), Size::new(2000.0, 1500.0), StatusItem::DocumentSizes, &StatusValues::default()).show(ui);
if let Some(view) = output.view.committed() {
seen.set(Some(view.zoom));
}
});
shown.set(view);
});
fixture.room(Vec2::new(600.0, 80.0)).settle();
let zoom = fixture.by_label("Zoom").expect("the status zoom field");
fixture.drag(&zoom, Vec2::new(12.0, 0.0)).settle();
let scrubbed = view.get().zoom;
assert!(scrubbed > 1.0, "the status bar still scrubs the zoom to the right");
fixture.click(&zoom).settle();
fixture.key(Key::A, Modifiers::COMMAND);
fixture.frame(vec![Event::Paste("079.69%".to_owned())]).settle();
let before_tab = view.get().zoom;
committed.set(None);
fixture.key(Key::Tab, Modifiers::NONE).settle();
assert_eq!(view.get().zoom, before_tab, "Tab does not change the current zoom");
assert_eq!(committed.get(), None, "Tab does not commit the draft");
let zoom = fixture.by_label("Zoom").expect("the status zoom field");
assert_eq!(fixture.tree().value_of(zoom.node), Some("79.69%"), "Tab rewrites the draft with its suffix");
fixture.key(Key::Enter, Modifiers::NONE).settle();
assert!(committed.get().is_some_and(|value| (value - 0.7969).abs() < 1e-7), "Enter commits the percent-bearing zoom");
}
/// A Row in a Bar under right-to-left measures in a room unbounded at its start edge, the left one: a labelled check
/// box there lays out with finite rects inside the bar, after the button before it in reading order. Guards against a
/// label row built from the room's start and width, which was NaN there.