makeover_immediate/lib.rs
1//! The immediate-mode renderer for [`makeover_layout`].
2//!
3//! <!-- wiki: makeover-immediate -->
4//!
5//! Named for the mode, not the library, the way `makeover-tui` is named for
6//! the target and not for ratatui. Immediate mode is the constraint that
7//! actually separates this renderer from the other two, and egui is the
8//! backend it is written against.
9//!
10//! It is the harshest renderer the description has to survive: no
11//! `box-shadow`, no `inset`, no cascade, no retained tree to mutate, and
12//! `Visuals.widgets.*.bg_stroke` is a single stroke with no per-side control.
13//! A two-tone lit edge is not something egui can be configured into producing,
14//! so it gets painted by hand here, once, instead of in every consuming app.
15//!
16//! # What this crate does and does not own
17//!
18//! It owns the *expression*: two mitred polylines for a bevel and a `Frame`
19//! for a filled region. It owns no colours and no sizes, and no longer owns a
20//! substitution: it briefly supplied the page for a well, which was a stand-in
21//! for `surface-well` before makeover derived it, and every consumer reads the
22//! real token now. [`Palette`] is supplied by the caller,
23//! already resolved, and every radius, margin and stroke width arrives in
24//! [`FrameStyle`].
25//!
26//! That split is why the crate has no dependency on `makeover` itself: the app
27//! already resolves a theme, and coupling a renderer to a colour crate's
28//! version would buy nothing.
29//!
30//! # The cascade is the real difference
31//!
32//! A stylesheet can say "a pressed button inverts its bevel" once and let the
33//! cascade carry it. An immediate-mode renderer has nowhere to put that, so
34//! every call site decides. [`makeover_layout::Depth::pressed`] is what keeps
35//! the decision from being re-derived per widget.
36//!
37//! # 0.11.0: the overlay becomes reachable
38//!
39//! 0.10.0 answered what overlaying means in immediate mode with
40//! [`Palette::cast`], and nothing could ask: the description had no
41//! `Depth::Overlay` until `makeover-layout` 0.14.0, so the answer sat beside a
42//! question that could not be posed. [`frame`] now hands the cast shadow to the
43//! `egui::Frame` for any depth whose fill is [`Fill::Overlay`], keyed off the
44//! fill rather than the variant.
45//!
46//! The same release brings `makeover_layout::CellPart`, which 0.11.0 carried
47//! and did not draw. [`table`] draws it, below.
48//!
49//! # 0.12.0: the table
50//!
51//! [`table`] is the vocabulary 0.11.0 took without using. The consumer is
52//! audiofiles, whose file list is the only table in the tree exercising all four
53//! of what the description says about one at once: sortable headings with
54//! carets, fixed and remainder tracks, and buttons inside cells.
55//!
56//! Two things it forces, both named where they land:
57//!
58//! - **`egui_extras`**, this crate's first dependency past egui. egui has no
59//! table, and `Grid` gives no per-column sizing, no sticky header and no
60//! scroll sync, which is why audiofiles reached for `egui_extras` rather than
61//! building on `Grid`. A third answer here would reimplement that crate worse.
62//! - **[`Palette::action`]**, on the footing [`Palette::content`] arrived on: a
63//! link in a cell is the first thing here needing the action intent.
64//!
65//! Narrowing works differently from the terminal's and the module header says
66//! why: a content column cannot be measured before the app's closure has drawn
67//! it, so `egui_extras` sizes it and the declared floor budgets it.
68//!
69//! # 0.13.0: what the adoption found missing
70//!
71//! 0.12.0 shipped [`table`] before audiofiles had taken it, and taking it found
72//! three things the file list already did that the function could not say. All
73//! three are host idiom rather than description, which is why they land here and
74//! not in `makeover-layout`, and all three are answered on a handle the app
75//! never sees: the `egui_extras` row and builder this crate owns. That is
76//! [`table::cell`]'s reasoning again: what the app cannot reach, the renderer
77//! owes it.
78//!
79//! - **A selected row.** [`table::Body::selected`], a predicate asked per row,
80//! because `set_selected` is a method on the row. Without it a file list has
81//! no way to show what is selected, which is most of what a file list does.
82//! - **Scrolling a row into view.** [`table::Body::scroll_to`], because
83//! `scroll_to_row` is a method on the builder. A keyboard cursor that moves
84//! off-screen and stays there is the bug this prevents.
85//! - **Dragging a divider.** [`table::TableStyle::resizable`], which passes the
86//! test `sticky_header` failed in 0.12.0: egui_extras offers two settings here
87//! and a renderer can honestly make either choice.
88//!
89//! A fourth was found and is not a knob. Cells are centred on the row's centre
90//! line, always, because there is no second honest answer and egui's own default
91//! (top-aligned) is the one thing it cannot be.
92//!
93//! [`table::Body`] is also what splits a table's per-frame facts from its
94//! description and from its style. A row count, a selection and a scroll request
95//! are none of them style, and none of them survive the frame.
96//!
97//! # 0.18.0: the nodes that were not fields, tables or frames
98//!
99//! [`widget`] draws a meter, a token, a control and a figure. `makeover-tui` has
100//! had all four for releases and this crate had none of them, which stayed
101//! invisible while the only consumer was an app calling [`field`] and [`table`]
102//! directly. It stopped being invisible the moment anything tried to draw a
103//! whole `quasi_router::Screen` in egui: the four are ordinary nodes, so a
104//! screen walk would have had to draw them itself, one copy per consumer.
105//!
106//! [`Palette`] grows the three status intents with it. They arrive together
107//! rather than one per widget for the reason [`Palette::fill`] is an `Option`:
108//! `Tone` is five members wide, and a resolver missing one has to invent a
109//! colour, which is the substitution 0.2.0 spent a release removing.
110//!
111//! # Forms
112//!
113//! 0.5.0 adds the field vocabulary on top of the depth vocabulary:
114//! [`makeover_layout::Field`] rendered to egui widgets, in [`field`], and a set
115//! of them laid down a column in [`group`]. Before it, a description saying
116//! "text field, labelled, required, with this hint" had no way to become a
117//! widget here, and audiofiles' forms stayed hand-rolled.
118//!
119//! `makeover-webview` got there first and its form emitter is the precedent
120//! followed rather than re-derived, including the parts that are bug fixes: a
121//! select handed a value none of its options carries keeps that value visible
122//! instead of silently reading as the first option, which is a save-the-wrong-
123//! thing bug goingson hit for real.
124//!
125//! What differs is forced by the mode and not chosen:
126//!
127//! - **The value arrives as a `&mut`.** [`Filling`] borrows the app's own field
128//! and the widget writes through it. There is no DOM to read back out of,
129//! which is also why the description deliberately does not carry the value.
130//! - **A text control is drawn as a well and a select is not.** The description
131//! holds that a well is for anything the user looks *into*, and a text field
132//! is its own example; a select and a checkbox are pressed rather than looked
133//! into, so they keep egui's own control painting.
134//! - **Focus is not describable, and egui owns all of it here.** **Reach**,
135//! **focus** and the **focus ring** are this renderer's three answers and
136//! egui already has all three: its own id stack decides what is reachable,
137//! its own state decides what holds the keyboard, and it paints exactly one
138//! ring. A description states none of them — `makeover_layout` removed the
139//! member that used to try in 0.19.0 — and drawing a second ring on top of
140//! egui's would break the one-ring rule it would have come from. The terms
141//! are defined once in `makeover_layout`'s crate header, "Reach, focus and
142//! the focus ring". [`makeover_layout::State::Disabled`] *is* drawn, because
143//! egui has no opinion about it until told.
144//! - **App-level chrome is not drawn here, and it is not this crate's to
145//! draw.** `quasi-router` names the affordances that outlive one screen: a
146//! `Chrome` of key bindings, and an `Outcome::Over` for a screen drawn over
147//! another. Both are answered by `quasi-webview` and `quasi-tui`, and neither
148//! is answerable here, because this crate depends on `makeover-layout` and
149//! not on `quasi-router` — it is the peer of `makeover-webview` and
150//! `makeover-tui`, one layer below the renderers that consume a `Screen`.
151//! What is missing is the egui crate at *that* layer, which does not exist:
152//! nothing renders a quasi `Screen` in egui at all, and chrome is one item on
153//! the list such a crate would owe. Said here because this is where a reader
154//! looks for it, and because the silent version reads as "egui does not need
155//! a palette" rather than "nobody has built the renderer yet".
156
157//! # 0.28.0: the slider, the unanswered chooser, and the option that is not
158//! offered yet
159//!
160//! Three things `makeover-layout` 0.28.0 lets a description say, all three
161//! found by audiofiles' forms port hitting a wall it could not describe its way
162//! past.
163//!
164//! - **[`FieldKind::Range`] is a fifth control shape**, `Control::Slid`, and
165//! the first one added since 0.5.0. egui has `Slider` and this crate had no
166//! way to be asked for one, so four sliders in the only consuming app stayed
167//! hand-rolled against a vocabulary that could not name them. A range missing
168//! an end falls back to a well rather than to invented bounds, which is what
169//! `makeover_layout::Field::bounded` is for.
170//! - **`Field::placeholder` finally reads on a chooser.** It was sayable and
171//! this renderer ignored it, so a select with nothing chosen showed an empty
172//! box. Nothing new is described; the renderer caught up.
173//! - **`Choice::unavailable` is drawn rather than dropped.** The option stays
174//! in the list, inert, with its precondition beside it instead of behind a
175//! hover — a greyed row with no reason reads as a dead end, which is the
176//! whole finding.
177//!
178//! The value still arrives as a `&mut String` and a slider is a number, so the
179//! parse and the write-back are this renderer's, and the write happens only on
180//! a real drag: a value the app put there that this host cannot read survives
181//! being looked at.
182
183#![forbid(unsafe_code)]
184
185use egui::{
186 Color32, ComboBox, CornerRadius, Margin, Painter, Rect, Response, RichText, Shape, Slider,
187 Stroke, TextEdit, Ui,
188};
189use makeover_layout::{Bevel, Choice, Depth, Edge, Field, FieldKind, Fill, State, Tone};
190use std::ops::RangeInclusive;
191
192/// Columns, narrowing, cell parts and the sort caret, over `egui_extras`.
193pub mod table;
194pub mod widget;
195
196/// The resolved colours this renderer needs, as flat values.
197///
198/// Built by the app from whatever it already uses to resolve a theme, then
199/// held and reused. Deliberately not a trait and not string-keyed: a bevel is
200/// painted per widget per frame, and a map lookup per edge is a cost with
201/// nothing to show for it.
202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
203pub struct Palette {
204 /// `surface-page`.
205 pub page: Color32,
206 /// `surface-raised`.
207 pub raised: Color32,
208 /// `surface-overlay`.
209 pub overlay: Color32,
210 /// `surface-well`.
211 ///
212 /// Required, not optional. makeover derives it for every theme from 2.3.0,
213 /// so a resolved palette without a well is not a thing that exists here.
214 /// It was an `Option` while that was untrue, and this renderer substituted
215 /// the page; `makeover-tui` keeps its own `Option` for a different reason,
216 /// since a terminal can have the colour and still be unable to show it.
217 pub well: Color32,
218 /// `surface-sunken`.
219 ///
220 /// A surface set back from the one it sits on, by colour and nothing else.
221 /// Not a well: a well is a hole with an edge, and this has no edge. An
222 /// immediate-mode renderer paints an arbitrary rect, so unlike
223 /// `makeover-tui` it has no excuse for declining this one.
224 ///
225 /// Required rather than optional, on the same footing as `well`: all 31
226 /// themes makeover embeds author it.
227 pub sunken: Color32,
228 /// `bevel-light`.
229 pub bevel_light: Color32,
230 /// `bevel-dark`.
231 pub bevel_dark: Color32,
232 /// `elevation`.
233 ///
234 /// What a surface that floats OVER the page is cast onto it with. The one
235 /// intent here that is about a surface's relationship to the page rather
236 /// than about the surface, which is why it is a translucent near-black on
237 /// every theme rather than something read off the palette's own ramp.
238 ///
239 /// **Only for a surface that overlays.** A menu, a tooltip, a modal. A
240 /// surface *in* the layout takes a bevel, and reaching for this on a panel
241 /// or a card is how a pre-Platinum look survives a conversion under a new
242 /// name.
243 ///
244 /// egui has a real answer for this where a terminal does not: see
245 /// [`Palette::cast`], which is the shadow to hand an
246 /// [`egui::Frame`](egui::Frame).
247 pub elevation: Color32,
248 /// `content`.
249 ///
250 /// Ordinary text. Added 0.5.0 with the field renderer, which is the first
251 /// thing here that draws any: until then this crate painted surfaces and
252 /// edges and let the caller's own egui visuals answer for text.
253 pub content: Color32,
254 /// `content-secondary`.
255 ///
256 /// Inactive but usable: it still answers a press. The middle tone of the
257 /// three (wiki `three-tone-convention`), and the one an unchosen option in
258 /// a choice field takes. Added 0.26.0 for that widget, which drew every
259 /// option at full `content` and so said nothing about which one was
260 /// chosen beyond the dot egui paints.
261 ///
262 /// Not [`content_muted`](Self::content_muted), which carries a claim:
263 /// `State::Disabled` resolves to it, so a live control wearing it tells the
264 /// user it will not answer. `makeover-tui` draws the same widget the same
265 /// way from `makeover-tui@230bf63`.
266 ///
267 /// A step of `content` toward the page, derived at load by `makeover`
268 /// rather than authored, so it is read off the resolved theme here like
269 /// any other token and never re-derived.
270 pub content_secondary: Color32,
271 /// `content-muted`.
272 ///
273 /// A field's hint, and what
274 /// [`makeover_layout::State::Disabled`](makeover_layout::State::Disabled)
275 /// resolves to. Both readings come from the description rather than from
276 /// here: `State::Disabled` names this intent by token.
277 pub content_muted: Color32,
278 /// `action-primary`.
279 ///
280 /// What a control is drawn in. Added 0.12.0 with the table renderer, for the
281 /// reason `content` was added 0.5.0 with the field renderer: a link in a
282 /// cell is the first thing here that needs the action intent, and a palette
283 /// should carry what is used.
284 ///
285 /// This is the intent [`CellPart`](makeover_layout::CellPart) exists to
286 /// separate. A cell holding a control took the cell's text colour until the
287 /// description could say otherwise, which is the drift `makeover-layout`
288 /// 0.14.0 named and `makeover-webview` 0.25.0 fixed on its own side.
289 pub action: Color32,
290 /// `danger`.
291 ///
292 /// A field's error message, a destructive control, a bar that has run over.
293 pub danger: Color32,
294 /// `success`.
295 ///
296 /// Added 0.18.0 with [`widget`], which is the first thing here that draws a
297 /// [`Tone`]. The three status intents arrive together and not one at a
298 /// time: [`Tone`] is five members wide and a resolver missing one has to
299 /// invent a colour for it, which is the substitution this crate spent
300 /// 0.2.0 removing from [`Palette::fill`].
301 pub success: Color32,
302 /// `warning`.
303 pub warning: Color32,
304 /// `info`.
305 pub info: Color32,
306}
307
308impl Palette {
309 /// Resolve a surface intent, or `None` for one this renderer does not know.
310 ///
311 /// A plain lookup. There is still no substitution: the old one existed only
312 /// while `surface-well` was underived, and every consumer reads the real
313 /// token now.
314 ///
315 /// `Option` since 0.3.0, because [`Fill`] became `#[non_exhaustive]` in
316 /// `makeover-layout` 0.4.0 and a total function over an open enum can only
317 /// stay total by inventing a colour for a member it has never heard of.
318 /// That is the substitution this crate spent 0.2.0 removing, so the return
319 /// type moved instead. Every member the description has today is answered
320 /// with `Some`.
321 #[must_use]
322 pub const fn fill(&self, fill: Fill) -> Option<Color32> {
323 match fill {
324 Fill::Page => Some(self.page),
325 Fill::Raised => Some(self.raised),
326 Fill::Overlay => Some(self.overlay),
327 Fill::Well => Some(self.well),
328 Fill::Sunken => Some(self.sunken),
329 _ => None,
330 }
331 }
332
333 /// The colour a [`Tone`] reads as.
334 ///
335 /// Total, unlike [`fill`](Self::fill), and the difference is not an
336 /// inconsistency. `Fill` is `#[non_exhaustive]` and `Tone` is not: the
337 /// description layer settled tone at five members and grows surfaces, so a
338 /// total function here cannot be made to invent a colour by an upstream
339 /// release the way a total `fill` could.
340 ///
341 /// [`Tone::Neutral`] is [`content`](Self::content) rather than a colour of
342 /// its own, which is what "an ordinary fact" means: a neutral badge is text
343 /// in a box, not a fifth status.
344 #[must_use]
345 pub const fn tone(&self, tone: Tone) -> Color32 {
346 match tone {
347 Tone::Neutral => self.content,
348 Tone::Info => self.info,
349 Tone::Success => self.success,
350 Tone::Warning => self.warning,
351 Tone::Danger => self.danger,
352 }
353 }
354
355 /// The cast shadow for a surface that overlays the page.
356 ///
357 /// What "overlaying" means in immediate mode, answered rather than skipped.
358 /// egui already paints shadows for its menus and windows through
359 /// [`egui::Frame::shadow`], so the honest port is to hand that machinery the
360 /// theme's tone instead of egui's own default, not to invent a painter here
361 /// the way [`paint_bevel`] had to.
362 ///
363 /// The geometry matches what `makeover-webview` composes, in points rather
364 /// than pixels: a small downward offset and a wide soft blur. A Platinum-era
365 /// menu sits just off the page rather than hovering above it.
366 ///
367 /// ```no_run
368 /// # let palette: makeover_immediate::Palette = unimplemented!();
369 /// # let ui: &mut egui::Ui = unimplemented!();
370 /// egui::Frame::popup(ui.style())
371 /// .shadow(palette.cast())
372 /// .show(ui, |ui| { ui.label("over the page"); });
373 /// ```
374 #[must_use]
375 pub const fn cast(&self) -> egui::Shadow {
376 egui::Shadow {
377 offset: [0, 2],
378 blur: 24,
379 spread: 0,
380 color: self.elevation,
381 }
382 }
383
384 /// Resolve a bevel edge intent.
385 #[must_use]
386 pub const fn edge(&self, edge: Edge) -> Color32 {
387 match edge {
388 Edge::Light => self.bevel_light,
389 Edge::Dark => self.bevel_dark,
390 }
391 }
392}
393
394/// The geometry a framed region is drawn with.
395///
396/// Every field is a value, which is why they all arrive from the caller:
397/// radius and border width belong to `makeover-geometry`, and margins come
398/// from its relational gaps.
399#[derive(Debug, Clone, Copy, PartialEq)]
400pub struct FrameStyle {
401 /// Corner radius. Square under the Platinum default.
402 pub radius: CornerRadius,
403 /// Inner margin between the frame and its contents.
404 pub margin: Margin,
405 /// Bevel stroke width, in points.
406 pub stroke: f32,
407}
408
409impl Default for FrameStyle {
410 /// A one-point square frame with no inner margin.
411 fn default() -> Self {
412 Self {
413 radius: CornerRadius::ZERO,
414 margin: Margin::ZERO,
415 stroke: 1.0,
416 }
417 }
418}
419
420/// Paint a two-tone edge just inside `rect`.
421///
422/// Fill first, bevel after: this adds two polylines and nothing else, so it
423/// composes over whatever is already there. That is what lets it go over an
424/// [`egui::TextEdit`] after `ui.add`, where the widget's own fill has landed.
425///
426/// Two three-point polylines meeting at opposite corners, rather than four
427/// segments, so egui mitres the corner joins instead of leaving a notch.
428///
429/// The dark polyline is drawn second, so the two corners where the runs meet
430/// take its tone. That is the right answer here rather than a concession.
431/// [`makeover_layout::Bevel`] holds those corners to belong to both edges, and
432/// a renderer with room to divide one should; at the default one-point stroke
433/// the corner is a one-point square, so the division is sub-pixel and
434/// antialiasing resolves it to the same blend the mitre already gives. Splitting
435/// it would add a seam and no information. `makeover-tui` does split, because a
436/// terminal cell is large enough that not splitting costs a visible cell of edge
437/// weight — the same rule, at a resolution where it has something to say.
438pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) {
439 let (top_left, bottom_right) = bevel.edges();
440
441 // Inset by half a stroke so the line lands inside `rect` rather than
442 // straddling its edge, which on a fractional-scale display is the
443 // difference between one crisp pixel and two dim ones.
444 let r = rect.shrink(stroke / 2.0);
445
446 painter.add(Shape::line(
447 vec![r.left_bottom(), r.left_top(), r.right_top()],
448 Stroke::new(stroke, palette.edge(top_left)),
449 ));
450 painter.add(Shape::line(
451 vec![r.right_top(), r.right_bottom(), r.left_bottom()],
452 Stroke::new(stroke, palette.edge(bottom_right)),
453 ));
454}
455
456/// Draw a region at a given [`Depth`]: its fill and its edge, together.
457///
458/// [`Depth::Flat`] gets neither, and inherits whatever it sits on. That is the
459/// difference between level-with and painted-the-same-colour, and it is the
460/// reason `Depth::fill` returns an [`Option`] rather than defaulting to the
461/// page.
462pub fn frame<R>(
463 ui: &mut Ui,
464 depth: Depth,
465 palette: &Palette,
466 style: FrameStyle,
467 add_contents: impl FnOnce(&mut Ui) -> R,
468) -> R {
469 let mut f = egui::Frame::new()
470 .corner_radius(style.radius)
471 .inner_margin(style.margin);
472 // Two ways there is no fill to paint, and they collapse to the same
473 // outcome: the depth names none (Depth::Flat), or it names one this
474 // renderer cannot resolve. Either way the frame goes unfilled and the
475 // bevel below carries the depth on its own, which is the rule this
476 // module already documents for Flat.
477 if let Some(fill) = depth.fill().and_then(|f| palette.fill(f)) {
478 f = f.fill(fill);
479 }
480 // A surface that overlays the page is cast onto it. [`Palette::cast`] has
481 // answered what that means here since 0.10.0 and nothing could reach it: a
482 // description had no way to say Overlay until makeover-layout 0.14.0, so
483 // the answer sat beside the question. Keyed off the fill rather than the
484 // variant, so it stays right for whatever else the description calls an
485 // overlay later.
486 if depth.fill() == Some(Fill::Overlay) {
487 f = f.shadow(palette.cast());
488 }
489 let framed = f.show(ui, add_contents);
490 if let Some(bevel) = depth.bevel() {
491 paint_bevel(
492 ui.painter(),
493 framed.response.rect,
494 bevel,
495 palette,
496 style.stroke,
497 );
498 }
499 framed.inner
500}
501
502/// The geometry a field group is drawn with.
503///
504/// Values again, for the reason [`FrameStyle`] is: every number here belongs to
505/// `makeover-geometry` and arrives already resolved.
506#[derive(Debug, Clone, Copy, PartialEq)]
507pub struct FieldStyle {
508 /// The well a text control sits in.
509 pub frame: FrameStyle,
510 /// Between a field's own parts: its label, its control, its hint and its
511 /// error.
512 pub gap: f32,
513 /// Between one field and the next.
514 pub group_gap: f32,
515 /// What marks a required field, appended to its label.
516 ///
517 /// A knob rather than a constant, because it is the one piece of *copy* in
518 /// this crate and copy is not a renderer's call. A webview does not need it
519 /// at all — it emits the `required` attribute and the browser answers — so
520 /// this renderer is the first place where a compulsory field either shows
521 /// that it is or silently does not.
522 pub required_marker: &'static str,
523}
524
525impl Default for FieldStyle {
526 /// The default frame, no gaps, and an asterisk.
527 fn default() -> Self {
528 Self {
529 frame: FrameStyle::default(),
530 gap: 0.0,
531 group_gap: 0.0,
532 required_marker: "*",
533 }
534 }
535}
536
537/// What the field currently holds, borrowed from wherever the app keeps it.
538///
539/// The immediate-mode counterpart of `makeover_webview::form::Value`, and the
540/// place the two renderers are forced apart: there the value is read back out
541/// of the DOM after the fact, and here the widget writes through this borrow as
542/// it is edited. Same reason the description carries neither.
543///
544/// An enum rather than a bag of options, on the reasoning
545/// `makeover_webview::form::Value` records: a checkbox holding a string is
546/// unsayable here, where a struct would let it be said and then have to cope.
547#[derive(Debug, Default)]
548pub enum Filling<'a> {
549 /// Nothing to edit. The control is drawn and does not answer.
550 #[default]
551 Absent,
552 /// The buffer behind anything that takes typed text, a select included:
553 /// what a select holds is the `value` of one of its [`Choice`]s.
554 ///
555 /// [`Choice`]: makeover_layout::Choice
556 Text(&'a mut String),
557 /// A checkbox, on or off.
558 On(&'a mut bool),
559}
560
561/// The label, marked if the field is compulsory.
562fn label_text(field: &Field<'_>, style: &FieldStyle) -> String {
563 if field.required {
564 format!("{} {}", field.label, style.required_marker)
565 } else {
566 field.label.to_owned()
567 }
568}
569
570/// The four shapes a control comes in here, which is fewer than there are
571/// kinds.
572///
573/// [`FieldKind`] is `#[non_exhaustive]` and grows; this does not, because the
574/// ways egui has of asking for a value do not. Reducing the open set to this
575/// closed one in one total function is what keeps a new kind from needing a new
576/// arm at every match below.
577#[derive(Debug, Clone, Copy, PartialEq, Eq)]
578enum Control {
579 /// Typed into, so it is drawn as a well: the user looks into it.
580 Typed,
581 /// Picked from a control that shows one option at a time. Pressed rather
582 /// than looked into, so egui's own control painting stands.
583 Chosen,
584 /// Picked from options that are all on screen at once.
585 ///
586 /// Apart from [`Chosen`](Self::Chosen) because the description holds them
587 /// apart, and holding them apart is the whole content of
588 /// [`FieldKind::Radio`]: same question, and an answer the user can read
589 /// without opening anything.
590 Listed,
591 /// Held on or off.
592 Toggled,
593 /// Dragged across an extent that is on screen the whole time.
594 ///
595 /// Apart from [`Typed`](Self::Typed) for the reason
596 /// [`FieldKind::Range`] is apart from `Number`: the two ends are what the
597 /// question means, so a well with a figure in it is not a quieter version
598 /// of this control, it is a different one.
599 Slid,
600}
601
602/// Which shape a kind takes.
603///
604/// The wildcard falls to [`Control::Typed`] on purpose: a kind added to the
605/// description since this renderer was built degrades to a text box, which
606/// accepts any value the others would, rather than to nothing drawn at all.
607///
608/// `FieldKind::File` lands there as of makeover-layout 0.11.0, and it is left
609/// there rather than grown a shape of its own. egui's honest answer is a button
610/// that opens a native picker, which is a fifth control and a file-dialog
611/// dependency; no consumer of this crate asks for a file field yet. Same
612/// position this crate took on `Meter` at 0.10.0: the membership test is that
613/// every renderer *could* answer honestly, not that each one does on the day.
614/// A path in a text box is not nothing, and it is what an app that needs this
615/// tomorrow gets today.
616///
617/// `FieldKind::Date` and `FieldKind::DateTime` land there too, as of
618/// makeover-layout 0.15.0, on the same footing and with one thing owed. A
619/// calendar is a sixth control and bare `egui` has none, so a typed value is
620/// the honest answer here; what the app gets is the format the description
621/// names, `makeover_layout::DATE_FORMAT` and `DATETIME_FORMAT`, which is why
622/// those are constants rather than a sentence. audiofiles is the only consumer
623/// of this crate and asks for neither today. A calendar popup is the upgrade
624/// whenever one does.
625const fn control_shape(kind: FieldKind) -> Control {
626 match kind {
627 FieldKind::Select => Control::Chosen,
628 FieldKind::Radio => Control::Listed,
629 FieldKind::Checkbox => Control::Toggled,
630 FieldKind::Range => Control::Slid,
631 _ => Control::Typed,
632 }
633}
634
635/// The shape the field actually gets, which is the kind's unless the field is
636/// missing what that shape needs.
637///
638/// One case, and `makeover-layout` names it: a [`FieldKind::Range`] carries its
639/// extent in [`Field::min`] and [`Field::max`], and a range missing an end has
640/// nothing to slide across. egui's `Slider` demands a `RangeInclusive`, so
641/// inventing one would be this renderer picking bounds the app never stated and
642/// the user then dragging against them.
643///
644/// It falls back to [`Control::Typed`], which is where every kind this renderer
645/// cannot draw natively already lands: a number in a well is a true report of
646/// the value and takes any answer the slider would.
647fn shape_of(field: &Field<'_>) -> Control {
648 match control_shape(field.kind) {
649 Control::Slid if !field.bounded() => Control::Typed,
650 shape => shape,
651 }
652}
653
654/// The two ends of a range, as egui wants them.
655///
656/// `None` when either end is missing or is not a number this host can read.
657/// The description carries the bounds as text on purpose — the bound of a date
658/// is a date — so parsing them is the renderer's job and failing to is a real
659/// outcome rather than an assertion.
660fn extent(field: &Field<'_>) -> Option<RangeInclusive<f64>> {
661 let min = field.min?.parse::<f64>().ok()?;
662 let max = field.max?.parse::<f64>().ok()?;
663 Some(min..=max)
664}
665
666/// How many decimals to write a dragged value back with.
667///
668/// Read off [`Field::step`], which is the only thing that says what
669/// granularity the question has: a step of `0.01` is a two-decimal question and
670/// a step of `1` is a whole-number one. Without a step the host's own
671/// granularity stands, and egui's is continuous, so the value is written back
672/// at whatever precision it round-trips at.
673fn decimals(step: Option<&str>) -> Option<usize> {
674 let step = step?;
675 Some(match step.split_once('.') {
676 Some((_, fraction)) => fraction.trim_end_matches('0').len(),
677 None => 0,
678 })
679}
680
681/// What a select shows for the value it currently holds.
682///
683/// A value no option carries stays on screen as itself rather than reading as
684/// whichever option happens to be first. goingson saved a backup retention of
685/// 10 against a 1/3/7/14/0 list and the browser silently showed it as 1, so the
686/// next save wrote a value nobody chose; `makeover-webview` grew the fix as a
687/// stray `<option>` and this is the same fix in the shape egui allows.
688///
689/// The empty value is the one case that reads as unanswered rather than as an
690/// answer, and [`chosen_text`] is what puts the field's ghost text there.
691fn shown_label<'a>(options: &'a [Choice<'a>], value: &'a str) -> &'a str {
692 options
693 .iter()
694 .find(|opt| opt.value == value)
695 .map_or(value, |opt| opt.label)
696}
697
698/// What a select's closed control reads, and in which tone.
699///
700/// A chooser with nothing chosen showed an empty box: `shown_label` falls back
701/// to the value, and the unanswered value is the empty string. So an app with
702/// an instruction to give — audiofiles' "Select device..." — had nowhere to put
703/// it but a disabled button elsewhere on the screen, which is the affordance
704/// this vocabulary keeps moving messages *off*.
705///
706/// [`Field::placeholder`] is already the description's word for "what the field
707/// reads while it is empty" and was honoured by the typed kinds alone, so
708/// nothing new is said here; the renderer is what had not caught up. Muted
709/// because it is not an answer, the same tone the typed kinds' ghost text takes
710/// three lines up.
711///
712/// A value no option carries but that is *not* empty stays as itself, in
713/// `content`: that is the goingson retention bug and it is a wrong answer
714/// rather than an absent one.
715///
716/// Returns the words and the tone rather than a built [`RichText`], because
717/// what it decides is both of them and only one of them is readable back off a
718/// `RichText`.
719///
720/// [`Field::placeholder`]: makeover_layout::Field::placeholder
721fn chosen_text<'a>(field: &'a Field<'a>, value: &'a str, palette: &Palette) -> (&'a str, Color32) {
722 match field.placeholder {
723 Some(ghost) if value.is_empty() => (ghost, palette.content_muted),
724 _ => (shown_label(field.options, value), palette.content),
725 }
726}
727
728/// What one option in a choice field is drawn in.
729///
730/// The chosen one is the emphasised thing and takes `content`; the rest take
731/// [`content_secondary`](Palette::content_secondary), because an option that is
732/// not chosen is still an option and pressing it chooses it. Muted would be the
733/// lie: [`State::Disabled`] resolves to it, so a five-option field read as one
734/// live row and four dead ones. `makeover-tui` draws it the same way
735/// (`makeover-tui@230bf63`); wiki `three-tone-convention` is the table.
736fn option_color(value: &str, option: &str, palette: &Palette) -> Color32 {
737 if value == option {
738 palette.content
739 } else {
740 palette.content_secondary
741 }
742}
743
744/// The control alone, without its label, hint or error.
745fn control(
746 ui: &mut Ui,
747 field: &Field<'_>,
748 filling: Filling<'_>,
749 palette: &Palette,
750 style: &FieldStyle,
751) -> Response {
752 // The mismatch path: described as one thing and filled as another. Nothing
753 // here can fix it, so it is drawn as the empty, inert version of what was
754 // described — visible on screen, in the way an empty select is at the
755 // webview renderer, rather than reported in a log nobody reads.
756 let mut discard = String::new();
757 let mut off = false;
758
759 match shape_of(field) {
760 Control::Slid => {
761 let value = match filling {
762 Filling::Text(text) => text,
763 _ => &mut discard,
764 };
765 // `shape_of` has already refused an unbounded range, so the extent
766 // is only missing here if a bound is not a number — a date range,
767 // say, which this control cannot draw either.
768 let Some(extent) = extent(field) else {
769 return ui.label(RichText::new(value.as_str()).color(palette.content));
770 };
771
772 // A value the host cannot read starts at the low end rather than at
773 // zero, which may be outside the extent entirely. Nothing is
774 // written back until the user drags, so an unreadable value the app
775 // put there survives being looked at.
776 let mut number = value.parse::<f64>().unwrap_or(*extent.start());
777 let mut slider = Slider::new(&mut number, extent).text("");
778 if let Some(places) = decimals(field.step) {
779 slider = slider.max_decimals(places);
780 }
781 if let Some(step) = field.step.and_then(|s| s.parse::<f64>().ok()) {
782 slider = slider.step_by(step);
783 }
784 let response = ui.add(slider);
785 if response.changed() {
786 *value = match decimals(field.step) {
787 Some(places) => format!("{number:.places$}"),
788 None => number.to_string(),
789 };
790 }
791 response
792 }
793 Control::Typed => {
794 let text = match filling {
795 Filling::Text(text) => text,
796 _ => &mut discard,
797 };
798 // An empty frame and no margin: the well is this crate's, and egui's
799 // own control background and padding would sit underneath it saying
800 // something different about both.
801 let mut edit = if matches!(field.kind, FieldKind::Textarea) {
802 TextEdit::multiline(text)
803 } else {
804 TextEdit::singleline(text)
805 }
806 .frame(egui::Frame::NONE)
807 .margin(Margin::ZERO)
808 .text_color(palette.content)
809 .password(field.kind.confidential());
810 if let Some(ghost) = field.placeholder {
811 edit = edit.hint_text(RichText::new(ghost).color(palette.content_muted));
812 }
813 frame(ui, Depth::Well, palette, style.frame, |ui| ui.add(edit))
814 }
815 Control::Toggled => {
816 let on = match filling {
817 Filling::On(on) => on,
818 _ => &mut off,
819 };
820 ui.checkbox(on, RichText::new(field.label).color(palette.content))
821 }
822 Control::Listed => {
823 let value = match filling {
824 Filling::Text(text) => text,
825 _ => &mut discard,
826 };
827 // No `shown_label` counterpart, and none is needed: a value no
828 // option carries leaves every button unfilled, which is already
829 // the honest report on screen. The select needs the fix because it
830 // has one slot and must put *something* in it.
831 let group = ui.vertical(|ui| {
832 let mut answered: Option<Response> = None;
833 for opt in field.options {
834 // An option that cannot be picked yet is drawn and does not
835 // answer, with the precondition beside it rather than
836 // behind a hover: a greyed row with no reason reads as a
837 // dead end, which is the state `Choice::unavailable` exists
838 // to stop being sayable.
839 let picked = if let Some(reason) = opt.unavailable {
840 ui.horizontal(|ui| {
841 let picked = ui
842 .add_enabled_ui(false, |ui| {
843 ui.radio_value(
844 value,
845 opt.value.to_owned(),
846 RichText::new(opt.label).color(palette.content_muted),
847 )
848 })
849 .inner;
850 ui.label(RichText::new(reason).color(palette.content_muted));
851 picked
852 })
853 .inner
854 } else {
855 ui.radio_value(
856 value,
857 opt.value.to_owned(),
858 RichText::new(opt.label).color(option_color(value, opt.value, palette)),
859 )
860 };
861 answered = Some(match answered {
862 Some(prev) => prev.union(picked),
863 None => picked,
864 });
865 }
866 answered
867 });
868 // A group described with no options answers as its own empty area
869 // rather than as no response at all, which keeps the caller's
870 // `.changed()` chain working on a field whose option list has not
871 // loaded yet.
872 group.inner.unwrap_or(group.response)
873 }
874 Control::Chosen => {
875 let value = match filling {
876 Filling::Text(text) => text,
877 _ => &mut discard,
878 };
879 let (shown, tone) = chosen_text(field, value, palette);
880 ComboBox::from_id_salt(field.name)
881 .selected_text(RichText::new(shown).color(tone))
882 .show_ui(ui, |ui| {
883 for opt in field.options {
884 // Same rule as the radio group: shown, inert, and
885 // saying why. A closed control hides its list, so the
886 // reason has to travel with the row it belongs to.
887 if let Some(reason) = opt.unavailable {
888 ui.add_enabled_ui(false, |ui| {
889 ui.selectable_value(
890 value,
891 opt.value.to_owned(),
892 RichText::new(format!("{} {reason}", opt.label))
893 .color(palette.content_muted),
894 );
895 });
896 continue;
897 }
898 ui.selectable_value(
899 value,
900 opt.value.to_owned(),
901 RichText::new(opt.label).color(option_color(value, opt.value, palette)),
902 );
903 }
904 })
905 .response
906 }
907 }
908}
909
910/// One field, as the column the app drops into its form.
911///
912/// The anatomy is `makeover-webview`'s, so the two renderers put a form
913/// together the same way: label, control, hint, error, top to bottom, with a
914/// checkbox labelling itself instead of taking a label above.
915///
916/// Returns [`None`] for a [`FieldKind::Hidden`] field, which is what
917/// [`FieldKind::visible`] means and is the honest answer here: a webview still
918/// emits an input for it because the form submits, and an immediate-mode
919/// renderer has no form and no submission, so a hidden field is a value the app
920/// already holds and there is nothing to draw or to respond to.
921///
922/// `state` is the description's interaction axis.
923/// [`State::Disabled`] greys the field and stops it answering, through
924/// [`State::suppresses_interaction`] rather than through a second reading of
925/// what disabled means. Focus is not on that axis and never reaches here: egui
926/// owns reach, focus and the ring for this renderer, and one ring means not a
927/// second one per renderer that happens to have opinions.
928pub fn field(
929 ui: &mut Ui,
930 field: &Field<'_>,
931 filling: Filling<'_>,
932 state: Option<State>,
933 palette: &Palette,
934 style: &FieldStyle,
935) -> Option<Response> {
936 if !field.kind.visible() {
937 return None;
938 }
939 let enabled = !state.is_some_and(State::suppresses_interaction);
940 let text = if enabled {
941 palette.content
942 } else {
943 palette.content_muted
944 };
945
946 let response = ui
947 .vertical(|ui| {
948 ui.spacing_mut().item_spacing.y = style.gap;
949
950 // A checkbox labels itself, on the right of the box.
951 // `FieldKind::labels_itself` is the description saying so, and both
952 // webview apps special-cased it inline before it did.
953 if !field.kind.labels_itself() {
954 ui.label(RichText::new(label_text(field, style)).color(text));
955 }
956
957 let response = ui
958 .add_enabled_ui(enabled, |ui| control(ui, field, filling, palette, style))
959 .inner;
960
961 // Standing help first, then what is wrong now. Both, in that order,
962 // for the reason the webview renderer names both in
963 // `aria-describedby`: an error appearing must not take the hint
964 // away with it.
965 if let Some(hint) = field.hint {
966 ui.label(RichText::new(hint).color(palette.content_muted));
967 }
968 if let Some(error) = field.error {
969 ui.label(RichText::new(error).color(palette.danger));
970 }
971 response
972 })
973 .inner;
974
975 Some(response)
976}
977
978/// A set of fields, laid down a column.
979///
980/// `show_extended` is the disclosure, and it is a parameter rather than state
981/// held here because the disclosure belongs to the *form* and not to any field:
982/// [`Field::extended`] marks which fields are behind one, and the app owns
983/// whether it is open. That is the same division `makeover-webview` draws when
984/// it marks the group `data-extended` and emits no control to toggle it.
985///
986/// `draw` is called once per field that should be visible, in order. Taking a
987/// callback rather than a slice of [`Filling`]s is what keeps the app's own
988/// values borrowed one at a time: a form's fields usually live in different
989/// structs, and a parallel array would have to be built each frame and kept in
990/// step with the description by hand.
991pub fn group<'a>(
992 ui: &mut Ui,
993 fields: &'a [Field<'a>],
994 show_extended: bool,
995 style: &FieldStyle,
996 mut draw: impl FnMut(&mut Ui, &'a Field<'a>),
997) {
998 ui.vertical(|ui| {
999 ui.spacing_mut().item_spacing.y = style.group_gap;
1000 for f in fields {
1001 if f.extended && !show_extended {
1002 continue;
1003 }
1004 draw(ui, f);
1005 }
1006 });
1007}
1008
1009#[cfg(test)]
1010mod tests {
1011 use super::*;
1012
1013 fn palette(well: Color32) -> Palette {
1014 Palette {
1015 page: Color32::from_rgb(1, 1, 1),
1016 raised: Color32::from_rgb(2, 2, 2),
1017 overlay: Color32::from_rgb(3, 3, 3),
1018 well,
1019 sunken: Color32::from_rgb(4, 4, 4),
1020 bevel_light: Color32::WHITE,
1021 bevel_dark: Color32::BLACK,
1022 elevation: Color32::from_black_alpha(46),
1023 content: Color32::from_rgb(5, 5, 5),
1024 content_secondary: Color32::from_rgb(55, 55, 55),
1025 content_muted: Color32::from_rgb(6, 6, 6),
1026 action: Color32::from_rgb(7, 7, 7),
1027 danger: Color32::from_rgb(8, 8, 8),
1028 success: Color32::from_rgb(9, 9, 9),
1029 warning: Color32::from_rgb(10, 10, 10),
1030 info: Color32::from_rgb(11, 11, 11),
1031 }
1032 }
1033
1034 /// The cast is egui's own shadow type carrying the theme's tone, which is
1035 /// the whole of what this crate had to decide for it: unlike a bevel, egui
1036 /// already knows how to paint one.
1037 #[test]
1038 fn the_cast_hands_egui_the_themes_tone() {
1039 let p = palette(Color32::from_rgb(9, 9, 9));
1040 let cast = p.cast();
1041 assert_eq!(cast.color, p.elevation);
1042 assert!(cast.blur > 0, "a cast shadow is soft");
1043 assert_eq!(cast.offset, [0, 2], "it falls downward and only a little");
1044 }
1045
1046 #[test]
1047 fn a_well_resolves_to_its_own_token() {
1048 // No substitution left. The page-filled well was a stand-in for a
1049 // token that did not exist yet; it exists now.
1050 let w = Color32::from_rgb(9, 9, 9);
1051 let p = palette(w);
1052 assert_eq!(p.fill(Fill::Well), Some(w));
1053 assert_ne!(p.fill(Fill::Well), Some(p.page));
1054 }
1055
1056 #[test]
1057 fn every_intent_is_a_plain_lookup() {
1058 let p = palette(Color32::from_rgb(9, 9, 9));
1059 assert_eq!(p.fill(Fill::Page), Some(p.page));
1060 assert_eq!(p.fill(Fill::Raised), Some(p.raised));
1061 assert_eq!(p.fill(Fill::Overlay), Some(p.overlay));
1062 }
1063
1064 /// Sunken is its own colour, not the well's and not the page's. The two
1065 /// are authored in opposite directions and an earlier cut of the
1066 /// description conflated them.
1067 #[test]
1068 fn sunken_is_neither_the_well_nor_the_page() {
1069 let p = palette(Color32::from_rgb(9, 9, 9));
1070 assert_eq!(p.fill(Fill::Sunken), Some(p.sunken));
1071 assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Well));
1072 assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Page));
1073 }
1074
1075 #[test]
1076 fn a_raised_region_never_resolves_to_the_well_fill() {
1077 // The cross-app bug, asserted at the renderer boundary this time.
1078 let p = palette(Color32::from_rgb(9, 9, 9));
1079 let raised = Depth::Raised.fill().and_then(|f| p.fill(f));
1080 let well = Depth::Well.fill().and_then(|f| p.fill(f));
1081 assert_eq!(raised, Some(p.raised));
1082 assert_ne!(raised, well);
1083 }
1084
1085 #[test]
1086 fn an_overlay_is_cast_onto_the_page_and_takes_no_edge() {
1087 // makeover-layout 0.14.0 is what made this reachable. The answer was
1088 // already here at 0.10.0 and the question could not be asked.
1089 let p = palette(Color32::from_rgb(9, 9, 9));
1090 assert_eq!(
1091 Depth::Overlay.fill().and_then(|f| p.fill(f)),
1092 Some(p.overlay)
1093 );
1094 assert_eq!(Depth::Overlay.bevel(), None);
1095 // The shadow `frame` reaches for is the theme's tone rather than
1096 // egui's default, which is the whole reason `cast` exists.
1097 assert_eq!(p.cast().color, p.elevation);
1098 }
1099
1100 #[test]
1101 fn the_lit_edge_swaps_when_a_card_is_pressed() {
1102 let p = palette(Color32::from_rgb(9, 9, 9));
1103 let (tl, _) = Depth::Raised.bevel().unwrap().edges();
1104 let (ptl, _) = Depth::Raised.pressed().bevel().unwrap().edges();
1105 assert_eq!(p.edge(tl), p.bevel_light);
1106 assert_eq!(p.edge(ptl), p.bevel_dark);
1107 }
1108
1109 #[test]
1110 fn flat_asks_for_neither_fill_nor_edge() {
1111 assert!(Depth::Flat.fill().is_none());
1112 assert!(Depth::Flat.bevel().is_none());
1113 }
1114
1115 #[test]
1116 fn a_select_keeps_a_value_none_of_its_options_carries() {
1117 // The save-the-wrong-thing bug, asserted at the second renderer so it
1118 // is not re-found there. goingson's own numbers.
1119 let options = [
1120 Choice::plain("1"),
1121 Choice::plain("3"),
1122 Choice::plain("7"),
1123 Choice::plain("14"),
1124 ];
1125 assert_eq!(shown_label(&options, "10"), "10");
1126 // And a value that does match reads as its label, not as itself.
1127 let spelled = [Choice::new("7", "One week")];
1128 assert_eq!(shown_label(&spelled, "7"), "One week");
1129 }
1130
1131 #[test]
1132 fn an_unanswered_chooser_reads_its_ghost_text_and_reads_it_muted() {
1133 let p = palette(Color32::from_rgb(9, 9, 9));
1134 let options = [Choice::new("sp404", "SP-404")];
1135 let field = Field {
1136 placeholder: Some("Select device..."),
1137 ..Field::select("device", "Conform for device", &options)
1138 };
1139
1140 assert_eq!(
1141 chosen_text(&field, "", &p),
1142 ("Select device...", p.content_muted),
1143 "ghost text is not an answer, so it takes the tone the typed kinds' ghost text does"
1144 );
1145
1146 // Answered, and it is the label that reads rather than the value.
1147 assert_eq!(chosen_text(&field, "sp404", &p), ("SP-404", p.content));
1148 }
1149
1150 #[test]
1151 fn a_wrong_answer_is_not_an_absent_one() {
1152 // The retention-10 bug and the ghost text meet here: a value no option
1153 // carries still reads as itself, because the field IS answered and the
1154 // answer is wrong. Only the empty value is unanswered.
1155 let p = palette(Color32::from_rgb(9, 9, 9));
1156 let options = [Choice::plain("1"), Choice::plain("7")];
1157 let field = Field {
1158 placeholder: Some("Pick one"),
1159 ..Field::select("retention", "Keep backups for", &options)
1160 };
1161
1162 assert_eq!(chosen_text(&field, "10", &p), ("10", p.content));
1163 }
1164
1165 #[test]
1166 fn a_chooser_with_no_ghost_text_is_unchanged() {
1167 // The whole change is opt-in from the description. A field that says
1168 // nothing about its empty state still shows an empty box.
1169 let p = palette(Color32::from_rgb(9, 9, 9));
1170 let options = [Choice::plain("1")];
1171 let field = Field::select("retention", "Keep backups for", &options);
1172 assert_eq!(chosen_text(&field, "", &p), ("", p.content));
1173 }
1174
1175 #[test]
1176 fn a_range_is_slid_and_a_number_is_typed_into() {
1177 // The distinction the kind was added for, at the renderer that has to
1178 // act on it. A well with a figure in it is not a quiet slider.
1179 assert_eq!(control_shape(FieldKind::Range), Control::Slid);
1180 assert_eq!(control_shape(FieldKind::Number), Control::Typed);
1181 }
1182
1183 #[test]
1184 fn a_range_missing_an_end_falls_back_to_a_well() {
1185 // egui's `Slider` demands both ends, so inventing one would be this
1186 // renderer picking bounds the app never stated and the user then
1187 // dragging against them. A typed number takes every answer the slider
1188 // would.
1189 let whole = Field::range("review", "Review above", "0", "1");
1190 assert_eq!(shape_of(&whole), Control::Slid);
1191
1192 let half = Field {
1193 max: Some("1"),
1194 ..Field::new(FieldKind::Range, "review", "Review above")
1195 };
1196 assert_eq!(shape_of(&half), Control::Typed);
1197 assert_eq!(extent(&half), None);
1198
1199 // A bound this host cannot read is the same outcome by a different
1200 // route: the description carries bounds as text because the bound of a
1201 // date is a date.
1202 let dated = Field::range("when", "When", "2026-08-01", "2026-08-31");
1203 assert_eq!(extent(&dated), None);
1204 }
1205
1206 #[test]
1207 fn the_step_decides_how_a_dragged_value_is_written_back() {
1208 // Without it a 0-to-1 threshold writes back whatever float the drag
1209 // landed on, which is the host's granularity and is what the
1210 // description says an absent step means.
1211 assert_eq!(decimals(None), None);
1212 assert_eq!(decimals(Some("1")), Some(0));
1213 assert_eq!(decimals(Some("0.01")), Some(2));
1214 // Trailing zeros are not precision: 0.10 is a one-decimal question.
1215 assert_eq!(decimals(Some("0.10")), Some(1));
1216 }
1217
1218 #[test]
1219 fn an_unavailable_option_is_drawn_muted_rather_than_dropped() {
1220 // The tone rule, at the one place it is a claim rather than a
1221 // preference: this option genuinely will not answer, so muted is the
1222 // truth. The available ones beside it keep the secondary intent.
1223 let p = palette(Color32::from_rgb(9, 9, 9));
1224 let options = [
1225 Choice::new("chromatic", "Chromatic"),
1226 Choice::new("multi", "Multi-sample").unless("Drop a second sample."),
1227 ];
1228 assert!(options[0].available());
1229 assert!(!options[1].available());
1230 assert_eq!(
1231 option_color("chromatic", options[0].value, &p),
1232 p.content,
1233 "the chosen option is the emphasised thing"
1234 );
1235 assert_eq!(
1236 option_color("chromatic", options[1].value, &p),
1237 p.content_secondary,
1238 "and `option_color` never mutes: the unavailable path is what does"
1239 );
1240 }
1241
1242 #[test]
1243 fn only_a_required_field_is_marked() {
1244 let style = FieldStyle::default();
1245 let plain = Field::new(FieldKind::Text, "title", "Title");
1246 assert_eq!(label_text(&plain, &style), "Title");
1247
1248 let required = Field {
1249 required: true,
1250 ..plain
1251 };
1252 assert_eq!(label_text(&required, &style), "Title *");
1253
1254 // The marker is copy and the app owns it, which is why it is a knob.
1255 let house = FieldStyle {
1256 required_marker: "(required)",
1257 ..style
1258 };
1259 assert_eq!(label_text(&required, &house), "Title (required)");
1260 }
1261
1262 #[test]
1263 fn a_select_and_a_checkbox_are_pressed_and_everything_else_is_typed_into() {
1264 // What decides whether the control gets a well. A well is for what the
1265 // user looks into, and only one of these is.
1266 assert_eq!(control_shape(FieldKind::Select), Control::Chosen);
1267 assert_eq!(control_shape(FieldKind::Radio), Control::Listed);
1268 assert_eq!(control_shape(FieldKind::Checkbox), Control::Toggled);
1269 for k in [
1270 FieldKind::Text,
1271 FieldKind::Secret,
1272 FieldKind::Number,
1273 FieldKind::Email,
1274 FieldKind::Url,
1275 FieldKind::Tel,
1276 FieldKind::Textarea,
1277 ] {
1278 assert_eq!(control_shape(k), Control::Typed, "{k:?} is typed into");
1279 }
1280 }
1281
1282 #[test]
1283 fn the_two_option_taking_kinds_are_drawn_differently_on_purpose() {
1284 // The description holds Select and Radio apart, and a renderer that
1285 // collapsed them would silently answer a question the app did not ask:
1286 // audiofiles' storage style is irreversible and its alternatives have
1287 // to be readable without opening anything. Asserting the two shapes
1288 // differ is asserting that distinction survives the trip.
1289 assert!(FieldKind::Select.offers_options());
1290 assert!(FieldKind::Radio.offers_options());
1291 assert_ne!(
1292 control_shape(FieldKind::Select),
1293 control_shape(FieldKind::Radio)
1294 );
1295 }
1296
1297 #[test]
1298 fn an_unchosen_option_is_secondary_and_never_muted() {
1299 let p = palette(Color32::from_rgb(4, 4, 4));
1300 assert_eq!(option_color("wav", "wav", &p), p.content);
1301 assert_eq!(option_color("wav", "aiff", &p), p.content_secondary);
1302 // The whole point of the distinction: muted is what Disabled resolves
1303 // to, so an option wearing it would claim it does not answer a press.
1304 assert_ne!(option_color("wav", "aiff", &p), p.content_muted);
1305 }
1306
1307 #[test]
1308 fn a_hidden_field_draws_nothing_and_answers_nothing() {
1309 // Where the two renderers legitimately part: a webview still emits an
1310 // input because the form submits, and there is no form here.
1311 let f = Field::new(FieldKind::Hidden, "id", "Id");
1312 let p = palette(Color32::from_rgb(9, 9, 9));
1313 egui::__run_test_ui(|ui| {
1314 let drawn = field(ui, &f, Filling::Absent, None, &p, &FieldStyle::default());
1315 assert!(drawn.is_none());
1316 });
1317 }
1318
1319 #[test]
1320 fn a_disabled_field_stops_answering_and_an_unstated_one_does_not() {
1321 let f = Field::new(FieldKind::Text, "title", "Title");
1322 let p = palette(Color32::from_rgb(9, 9, 9));
1323 let style = FieldStyle::default();
1324 egui::__run_test_ui(|ui| {
1325 let mut text = String::from("x");
1326 let disabled = field(
1327 ui,
1328 &f,
1329 Filling::Text(&mut text),
1330 Some(State::Disabled),
1331 &p,
1332 &style,
1333 )
1334 .unwrap();
1335 assert!(!disabled.enabled());
1336
1337 // Stating no state is the ordinary case and answers. Focus used to
1338 // be the counter-example here; it is egui's now and a description
1339 // cannot state it at all.
1340 let mut text = String::from("x");
1341 let plain = field(ui, &f, Filling::Text(&mut text), None, &p, &style).unwrap();
1342 assert!(plain.enabled(), "an unstated field still answers");
1343 });
1344 }
1345
1346 #[test]
1347 fn a_field_described_one_way_and_filled_another_is_drawn_inert() {
1348 // No panic and no write-through. A checkbox handed a string cannot be
1349 // filled, so it is drawn off and left alone.
1350 let f = Field::new(FieldKind::Checkbox, "done", "Done");
1351 let p = palette(Color32::from_rgb(9, 9, 9));
1352 let mut text = String::from("untouched");
1353 egui::__run_test_ui(|ui| {
1354 let drawn = field(
1355 ui,
1356 &f,
1357 Filling::Text(&mut text),
1358 None,
1359 &p,
1360 &FieldStyle::default(),
1361 );
1362 assert!(drawn.is_some());
1363 });
1364 assert_eq!(text, "untouched");
1365 }
1366
1367 #[test]
1368 fn the_disclosure_belongs_to_the_form_and_not_to_the_field() {
1369 let fields = [
1370 Field::new(FieldKind::Text, "title", "Title"),
1371 Field {
1372 extended: true,
1373 ..Field::new(FieldKind::Text, "notes", "Notes")
1374 },
1375 ];
1376 let style = FieldStyle::default();
1377
1378 let mut closed = Vec::new();
1379 egui::__run_test_ui(|ui| {
1380 group(ui, &fields, false, &style, |_, f| closed.push(f.name));
1381 });
1382 assert_eq!(closed, ["title"]);
1383
1384 let mut open = Vec::new();
1385 egui::__run_test_ui(|ui| {
1386 group(ui, &fields, true, &style, |_, f| open.push(f.name));
1387 });
1388 assert_eq!(open, ["title", "notes"]);
1389 }
1390
1391 #[test]
1392 fn the_default_frame_is_square_and_one_point() {
1393 let d = FrameStyle::default();
1394 assert_eq!(d.radius, CornerRadius::ZERO);
1395 assert_eq!(d.margin, Margin::ZERO);
1396 assert!((d.stroke - 1.0).abs() < f32::EPSILON);
1397 }
1398}