Field adornments carry text: a unit after a number is a text adornment

Adornment::text(label, role) is measured with the field and placed by place/reserve like a glyph or a button, against the text with no gap. NumberField's unit is its first trailing adornment; its own unit layout goes.
This commit is contained in:
aiongg
2026-11-12 14:32:42 +00:00
parent 6fe24f64b2
commit d0a903d69a
2 changed files with 116 additions and 86 deletions
+88 -47
View File
@@ -3,59 +3,95 @@
use super::FieldStyle;
use crate::buttons::IconButton;
use crate::contract::{PaintUi, Props as _};
use crate::primitives::IconSpec;
use crate::contract::{MeasureCx, PaintUi, Props as _};
use crate::primitives::{IconSpec, TextRun};
use crate::runtime::env::Label;
use crate::style::StyleColor;
use crate::style::{StyleColor, TypeRole};
use craft_behavior::{Flow, PartKey};
use craft_theme::ControlSize;
use egui::{Rect, vec2};
use egui::{Rect, Vec2, vec2};
use smallvec::SmallVec;
/// Something a field draws beside its text.
pub struct Adornment {
icon: IconSpec<'static>,
button: Option<(PartKey, Label)>,
kind: Kind,
}
enum Kind {
Glyph(IconSpec<'static>),
Button(PartKey, IconSpec<'static>, Label),
/// Text in the line, of `role`; `size` is its measured run, zero until [`Adornment::measured`].
Text {
label: Label,
role: TypeRole,
size: Vec2,
},
}
impl Adornment {
/// A decorative icon of the style's glyph side.
pub fn glyph(icon: impl Into<IconSpec<'static>>) -> Adornment {
Adornment { icon: icon.into(), button: None }
Adornment { kind: Kind::Glyph(icon.into()) }
}
/// An icon button, the part `part` named `name`, of the style's button side.
pub fn button(part: PartKey, icon: impl Into<IconSpec<'static>>, name: Label) -> Adornment {
Adornment { icon: icon.into(), button: Some((part, name)) }
Adornment { kind: Kind::Button(part, icon.into(), name) }
}
/// The part key of a button; `None` for a glyph.
/// Text in the field's line, in `role`: a unit after a number, a fixed `#` before hex digits. It takes the width of
/// its run, which the field measures with [`Adornment::measured`] before placing it, and sits against the text
/// with no gap between them.
pub fn text(label: impl Into<Label>, role: TypeRole) -> Adornment {
Adornment { kind: Kind::Text { label: label.into(), role, size: Vec2::ZERO } }
}
/// The adornment with a text adornment's run measured in `cx`; a glyph or a button is returned as it is.
pub fn measured<C: crate::contract::Component>(mut self, cx: &MeasureCx<'_, C>) -> Adornment {
if let Kind::Text { label, role, size } = &mut self.kind {
*size = cx.layout(&TextRun::new(label.as_str()).role(*role)).size();
}
self
}
/// The part key of a button; `None` for a glyph or text.
pub fn part(&self) -> Option<PartKey> {
self.button.as_ref().map(|(part, _)| *part)
}
/// The side of the square the adornment takes in the line.
fn side(&self, style: &FieldStyle) -> f32 {
if self.button.is_some() { style.button } else { style.glyph.side }
}
/// The icon, painted in `color` when there is one.
fn spec(&self, color: Option<StyleColor>) -> IconSpec<'static> {
IconSpec {
source: self.icon.source.clone(),
ink: self.icon.ink,
color: color.or(self.icon.color),
mirror: self.icon.mirror,
set: self.icon.set,
match &self.kind {
Kind::Button(part, ..) => Some(*part),
_ => None,
}
}
/// Paints the adornment in `rect`, one of `place`'s rects: a glyph in `glyph_color`, a button as an icon button face
/// over its part.
pub fn paint(&self, ui: &mut PaintUi<'_>, rect: Rect, glyph_color: StyleColor) {
match &self.button {
None => ui.draw().icon(rect, &self.spec(Some(glyph_color))),
Some((part, name)) => ui.face(*part, IconButton::new(self.spec(None)).label(name.clone()).focusable(false).size(ControlSize::Sm)),
/// The size the adornment takes in the line: a square for a glyph or a button, the run for text.
fn extent(&self, style: &FieldStyle) -> Vec2 {
match &self.kind {
Kind::Glyph(_) => Vec2::splat(style.glyph.side),
Kind::Button(..) => Vec2::splat(style.button),
Kind::Text { size, .. } => *size,
}
}
/// The gap between the adornment and its neighbour towards the text: none for text, which reads as part of it.
fn gap_after(&self, style: &FieldStyle, innermost: bool) -> f32 {
if innermost && matches!(self.kind, Kind::Text { .. }) { 0.0 } else { style.metrics.gap }
}
/// The icon, painted in `color` when there is one.
fn spec(icon: &IconSpec<'static>, color: Option<StyleColor>) -> IconSpec<'static> {
IconSpec { source: icon.source.clone(), ink: icon.ink, color: color.or(icon.color), mirror: icon.mirror, set: icon.set }
}
/// Paints the adornment in `rect`, one of `place`'s rects: a glyph or text in `color`, a button as an icon button
/// face over its part.
pub fn paint(&self, ui: &mut PaintUi<'_>, rect: Rect, color: StyleColor) {
match &self.kind {
Kind::Glyph(icon) => ui.draw().icon(rect, &Self::spec(icon, Some(color))),
Kind::Button(part, icon, name) => {
ui.face(*part, IconButton::new(Self::spec(icon, None)).label(name.clone()).focusable(false).size(ControlSize::Sm))
}
Kind::Text { label, role, .. } => {
ui.draw().text(rect, &TextRun::new(label.as_str()).role(*role).color(color));
}
}
}
}
@@ -76,7 +112,7 @@ pub struct Placed {
/// the button sits in the line's square. A glyph keeps the field's padding.
fn inset(style: &FieldStyle, first: Option<&Adornment>, padding: f32) -> f32 {
match first {
Some(adornment) if adornment.button.is_some() => ((style.metrics.min_size.y - adornment.side(style)) / 2.0).max(0.0),
Some(adornment) if adornment.part().is_some() => ((style.metrics.min_size.y - adornment.extent(style).y) / 2.0).max(0.0),
_ => padding,
}
}
@@ -87,34 +123,39 @@ pub fn reserve(style: &FieldStyle, leading: &[Adornment], trailing: &[Adornment]
let metrics = style.metrics;
let edges = inset(style, leading.first(), metrics.padding.start) - metrics.padding.start + inset(style, trailing.last(), metrics.padding.end)
- metrics.padding.end;
edges + leading.iter().chain(trailing).map(|adornment| adornment.side(style) + style.metrics.gap).sum::<f32>()
// The adornment next to the text is the last leading one and the first trailing one.
let room = |adornments: &[Adornment], innermost: usize| {
adornments.iter().enumerate().map(|(at, adornment)| adornment.extent(style).x + adornment.gap_after(style, at == innermost)).sum::<f32>()
};
edges + room(leading, leading.len().saturating_sub(1)) + room(trailing, 0)
}
/// Places `leading` from the reading start and `trailing` from the reading end of the field's box (`content`, the
/// content rect, with the padding added back), each
/// `style.metrics.gap` from its neighbour and centred on the line, and leaves the rest to the text. A glyph at an
/// edge sits one padding from it and a button `(line - side) / 2` from it. `trailing` is in reading order: its last
/// adornment is at the end.
/// content rect, with the padding added back), each `style.metrics.gap` from its neighbour and centred on the line,
/// and leaves the rest to the text; a text adornment next to the text sits against it. A glyph or text at an edge
/// sits one padding from it and a button `(line - side) / 2` from it. `trailing` is in reading order: its last
/// adornment is at the end. Text adornments are measured first ([`Adornment::measured`]).
pub fn place(content: Rect, style: &FieldStyle, leading: &[Adornment], trailing: &[Adornment], rtl: bool) -> Placed {
let gap = style.metrics.gap;
let padding = style.metrics.padding;
let centred = |cell: Rect, side: f32| Rect::from_center_size(cell.center(), vec2(cell.width(), side));
let centred = |cell: Rect, height: f32| Rect::from_center_size(cell.center(), vec2(cell.width(), height));
let (before, after) = if rtl { (padding.end, padding.start) } else { (padding.start, padding.end) };
let rect = Rect::from_min_max(content.min - vec2(before, 0.0), content.max + vec2(after, 0.0));
let mut flow = Flow::new(rect, rtl);
flow = flow.take_start(inset(style, leading.first(), padding.start)).1;
flow = flow.take_end(inset(style, trailing.last(), padding.end)).1;
let mut lead = SmallVec::new();
for adornment in leading {
let (cell, rest) = flow.take_start(adornment.side(style));
lead.push(centred(cell, adornment.side(style)));
flow = rest.take_start(gap).1;
for (at, adornment) in leading.iter().enumerate() {
let extent = adornment.extent(style);
let (cell, rest) = flow.take_start(extent.x);
lead.push(centred(cell, extent.y));
flow = rest.take_start(adornment.gap_after(style, at + 1 == leading.len())).1;
}
let mut trail: SmallVec<[Rect; 2]> = SmallVec::new();
for adornment in trailing.iter().rev() {
let (cell, rest) = flow.take_end(adornment.side(style));
trail.push(centred(cell, adornment.side(style)));
flow = rest.take_end(gap).1;
for (at, adornment) in trailing.iter().enumerate().rev() {
let extent = adornment.extent(style);
let (cell, rest) = flow.take_end(extent.x);
trail.push(centred(cell, extent.y));
flow = rest.take_end(adornment.gap_after(style, at == 0)).1;
}
trail.reverse();
Placed { text: flow.rect(), leading: lead, trailing: trail }
+28 -39
View File
@@ -23,7 +23,7 @@ use craft_behavior::{
Codec, Flow, HitLevel, HitPriority, Metrics, NavMove, NumberCodec, PartKey, PressPhase, Sense, ValueDrag, decimals_for_step, wheel_step,
};
use craft_theme::{Stateful, States};
use egui::{Pos2, Rect, Vec2};
use egui::{Rect, Vec2};
use std::borrow::Cow;
use std::marker::PhantomData;
use std::ops::RangeInclusive;
@@ -131,7 +131,8 @@ pub struct NumberField<'a, V: NumberValue + 'static = Option<f64>> {
/// as a drag on the slider would.
track: f32,
picked: Option<NumberPick>,
unit_size: Vec2,
/// The unit and the chevrons after the text, measured in measure and parts for paint.
trailing: Vec<Adornment>,
}
impl<'a> NumberField<'a, Option<f64>> {
@@ -183,7 +184,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
scrub: false,
track: 0.0,
picked: None,
unit_size: Vec2::ZERO,
trailing: Vec::new(),
}
.label(label)
}
@@ -279,11 +280,6 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
}
}
/// The unit's size, the room it takes and the gap before it.
fn unit_extent(&self, cx: &MeasureCx<'_, Self>) -> Vec2 {
self.unit.as_ref().map_or(Vec2::ZERO, |unit| cx.layout(&TextRun::new(unit.as_str()).role(cx.style.unit.role)).size())
}
/// The chevrons after the text, in order, with their parts and accessible names.
fn chevrons(&self, words: &TextWords) -> Vec<(PartKey, Label)> {
let mut chevrons = Vec::new();
@@ -296,22 +292,17 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
chevrons
}
fn adornments(chevrons: &[(PartKey, Label)]) -> Vec<Adornment> {
chevrons.iter().map(|(key, name)| Adornment::button(*key, crate::controls::disclosure::DisclosureGlyph::dropdown(), name.clone())).collect()
/// The unit, measured, then the chevrons: what sits after the text.
fn after_text(&self, cx: &MeasureCx<'_, Self>, chevrons: &[(PartKey, Label)]) -> Vec<Adornment> {
let unit = self.unit.iter().map(|unit| Adornment::text(unit.clone(), cx.style.unit.role).measured(cx));
let chevrons =
chevrons.iter().map(|(key, name)| Adornment::button(*key, crate::controls::disclosure::DisclosureGlyph::dropdown(), name.clone()));
unit.chain(chevrons).collect()
}
/// The rect of the text and the chevrons inside `rect`.
fn laid_out(style: &NumberStyle, rect: Rect, rtl: bool, chevrons: &[(PartKey, Label)]) -> Placed {
place(rect, &style.field, &[], &Self::adornments(chevrons), rtl)
}
/// The text rect and the unit's: the unit sits between the text and the chevrons.
fn text_and_unit(&self, text: Rect, rtl: bool) -> (Rect, Option<Rect>) {
if self.unit_size.x <= 0.0 {
return (text, None);
}
let (unit, rest) = Flow::new(text, rtl).take_end(self.unit_size.x);
(rest.rect(), Some(unit))
/// The rect of the text, the unit and the chevrons inside `rect`.
fn laid_out(&self, style: &NumberStyle, rect: Rect, rtl: bool) -> Placed {
place(rect, &style.field, &[], &self.trailing, rtl)
}
}
impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
@@ -351,26 +342,24 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
let digit = cx.layout(&TextRun::new("0")).size();
Vec2::new(digit.x + caret, digit.y)
};
self.unit_size = self.unit_extent(cx);
let unit = self.unit_size.x;
// The chevrons take their own room and the change of the edge inset a button makes.
let adornments = reserve(&cx.style.field, &[], &Self::adornments(&self.chevrons(&cx.words::<TextWords>())));
let width = text.x + unit + adornments;
self.trailing = self.after_text(cx, &self.chevrons(&cx.words::<TextWords>()));
// The unit and the chevrons take their own room and the change of the edge inset a button makes.
let width = text.x + reserve(&cx.style.field, &[], &self.trailing);
// A field is one number cell wide, the unit and the chevrons inside it, so a column of fields ends at one edge;
// it grows only when the room left for the number drops below one digit and the caret.
let field = cx.style.field.metrics();
let width = width.max(cx.tokens.size.length.number - field.padding.start - field.padding.end);
Vec2::new(width, text.y.max(self.unit_size.y))
Vec2::new(width, text.y)
}
fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) {
self.settle_lengths(&cx.env.units());
self.unit_size = self.unit_extent(cx);
self.track = cx.tokens.size.length.track;
let rtl = cx.flow.is_rtl();
let chevrons = self.chevrons(&cx.words::<TextWords>());
let placed = Self::laid_out(cx.style, cx.content_rect, rtl, &chevrons);
let (text, _) = self.text_and_unit(placed.text, rtl);
self.trailing = self.after_text(cx, &chevrons);
let placed = self.laid_out(cx.style, cx.content_rect, rtl);
let text = placed.text;
self.options.centred = true;
self.options.steps_value = self.presets.is_none() && self.popup_slider.is_none();
let shown = cx.value();
@@ -386,7 +375,8 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
cx.text(text_part::<V>(), text, &self.ruled(&cx.env.units(), shown.is_none(), names), shown.unwrap_or(&blank), &self.options);
let slider_reason =
if self.presets.is_some() { "Alt+Down opens the presets list; the slider opens by pointer" } else { "Alt+Down opens the slider" };
for ((key, _), at) in chevrons.iter().zip(&placed.trailing) {
let chevron_rects = &placed.trailing[placed.trailing.len() - chevrons.len()..];
for ((key, _), at) in chevrons.iter().zip(chevron_rects) {
let reason = if *key == PRESETS { "Alt+Down opens the list" } else { slider_reason };
let popup = if *key == PRESETS { "presets" } else { "slider" };
cx.part(*key, *at)
@@ -507,14 +497,13 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let rtl = cx.flow.is_rtl();
let chevrons = self.chevrons(&cx.words::<TextWords>());
let placed = Self::laid_out(cx.style, cx.content_rect, rtl, &chevrons);
let (_, unit) = self.text_and_unit(placed.text, rtl);
let placed = self.laid_out(cx.style, cx.content_rect, rtl);
// A mixed value shows the dash alone: a unit beside it would claim a measure the selection does not have.
if let (Some(unit), Some(label), Some(_)) = (unit, &self.unit, cx.value().filter(|value| !non_finite(Some(*value)))) {
let top = unit.center().y - self.unit_size.y / 2.0;
let at = unit;
let run = TextRun::new(label.as_str()).role(cx.style.unit.role).color(cx.resolve(&cx.style.unit.color));
ui.draw().text(Rect::from_min_size(Pos2::new(at.min.x, top), Vec2::new(at.width(), self.unit_size.y)), &run);
if self.unit.is_some()
&& cx.value().is_some_and(|value| !non_finite(Some(value)))
&& let (Some(unit), Some(at)) = (self.trailing.first(), placed.trailing.first())
{
unit.paint(ui, *at, cx.resolve(&cx.style.unit.color));
}
for (key, name) in chevrons {
ui.face(key, IconButton::new(crate::controls::disclosure::DisclosureGlyph::dropdown()).label(name));