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/// makeover-layout 0.31.0 added `Field::accept` and `Field::multiple`, and this
618/// position is what they land on: both are the picker's arguments, and this
619/// renderer has no picker to give them to. They are not lost — the description
620/// still carries them, and the day the native dialog arrives here it is opened
621/// with them rather than with a filter written twice.
622///
623/// `FieldKind::Date` and `FieldKind::DateTime` land there too, as of
624/// makeover-layout 0.15.0, on the same footing and with one thing owed. A
625/// calendar is a sixth control and bare `egui` has none, so a typed value is
626/// the honest answer here; what the app gets is the format the description
627/// names, `makeover_layout::DATE_FORMAT` and `DATETIME_FORMAT`, which is why
628/// those are constants rather than a sentence. audiofiles is the only consumer
629/// of this crate and asks for neither today. A calendar popup is the upgrade
630/// whenever one does.
631const fn control_shape(kind: FieldKind) -> Control {
632 match kind {
633 FieldKind::Select => Control::Chosen,
634 FieldKind::Radio => Control::Listed,
635 FieldKind::Checkbox => Control::Toggled,
636 FieldKind::Range => Control::Slid,
637 _ => Control::Typed,
638 }
639}
640
641/// The shape the field actually gets, which is the kind's unless the field is
642/// missing what that shape needs.
643///
644/// One case, and `makeover-layout` names it: a [`FieldKind::Range`] carries its
645/// extent in [`Field::min`] and [`Field::max`], and a range missing an end has
646/// nothing to slide across. egui's `Slider` demands a `RangeInclusive`, so
647/// inventing one would be this renderer picking bounds the app never stated and
648/// the user then dragging against them.
649///
650/// It falls back to [`Control::Typed`], which is where every kind this renderer
651/// cannot draw natively already lands: a number in a well is a true report of
652/// the value and takes any answer the slider would.
653fn shape_of(field: &Field<'_>) -> Control {
654 match control_shape(field.kind) {
655 Control::Slid if !field.bounded() => Control::Typed,
656 shape => shape,
657 }
658}
659
660/// The two ends of a range, as egui wants them.
661///
662/// `None` when either end is missing or is not a number this host can read.
663/// The description carries the bounds as text on purpose — the bound of a date
664/// is a date — so parsing them is the renderer's job and failing to is a real
665/// outcome rather than an assertion.
666fn extent(field: &Field<'_>) -> Option<RangeInclusive<f64>> {
667 let min = field.min?.parse::<f64>().ok()?;
668 let max = field.max?.parse::<f64>().ok()?;
669 Some(min..=max)
670}
671
672/// How many decimals to write a dragged value back with.
673///
674/// Read off [`Field::step`], which is the only thing that says what
675/// granularity the question has: a step of `0.01` is a two-decimal question and
676/// a step of `1` is a whole-number one. Without a step the host's own
677/// granularity stands, and egui's is continuous, so the value is written back
678/// at whatever precision it round-trips at.
679fn decimals(step: Option<&str>) -> Option<usize> {
680 let step = step?;
681 Some(match step.split_once('.') {
682 Some((_, fraction)) => fraction.trim_end_matches('0').len(),
683 None => 0,
684 })
685}
686
687/// What a select shows for the value it currently holds.
688///
689/// A value no option carries stays on screen as itself rather than reading as
690/// whichever option happens to be first. goingson saved a backup retention of
691/// 10 against a 1/3/7/14/0 list and the browser silently showed it as 1, so the
692/// next save wrote a value nobody chose; `makeover-webview` grew the fix as a
693/// stray `<option>` and this is the same fix in the shape egui allows.
694///
695/// The empty value is the one case that reads as unanswered rather than as an
696/// answer, and [`chosen_text`] is what puts the field's ghost text there.
697fn shown_label<'a>(options: &'a [Choice<'a>], value: &'a str) -> &'a str {
698 options
699 .iter()
700 .find(|opt| opt.value == value)
701 .map_or(value, |opt| opt.label)
702}
703
704/// What a select's closed control reads, and in which tone.
705///
706/// A chooser with nothing chosen showed an empty box: `shown_label` falls back
707/// to the value, and the unanswered value is the empty string. So an app with
708/// an instruction to give — audiofiles' "Select device..." — had nowhere to put
709/// it but a disabled button elsewhere on the screen, which is the affordance
710/// this vocabulary keeps moving messages *off*.
711///
712/// [`Field::placeholder`] is already the description's word for "what the field
713/// reads while it is empty" and was honoured by the typed kinds alone, so
714/// nothing new is said here; the renderer is what had not caught up. Muted
715/// because it is not an answer, the same tone the typed kinds' ghost text takes
716/// three lines up.
717///
718/// A value no option carries but that is *not* empty stays as itself, in
719/// `content`: that is the goingson retention bug and it is a wrong answer
720/// rather than an absent one.
721///
722/// Returns the words and the tone rather than a built [`RichText`], because
723/// what it decides is both of them and only one of them is readable back off a
724/// `RichText`.
725///
726/// [`Field::placeholder`]: makeover_layout::Field::placeholder
727fn chosen_text<'a>(field: &'a Field<'a>, value: &'a str, palette: &Palette) -> (&'a str, Color32) {
728 match field.placeholder {
729 Some(ghost) if value.is_empty() => (ghost, palette.content_muted),
730 _ => (shown_label(field.options, value), palette.content),
731 }
732}
733
734/// What one option in a choice field is drawn in.
735///
736/// The chosen one is the emphasised thing and takes `content`; the rest take
737/// [`content_secondary`](Palette::content_secondary), because an option that is
738/// not chosen is still an option and pressing it chooses it. Muted would be the
739/// lie: [`State::Disabled`] resolves to it, so a five-option field read as one
740/// live row and four dead ones. `makeover-tui` draws it the same way
741/// (`makeover-tui@230bf63`); wiki `three-tone-convention` is the table.
742fn option_color(value: &str, option: &str, palette: &Palette) -> Color32 {
743 if value == option {
744 palette.content
745 } else {
746 palette.content_secondary
747 }
748}
749
750/// The control alone, without its label, hint or error.
751fn control(
752 ui: &mut Ui,
753 field: &Field<'_>,
754 filling: Filling<'_>,
755 palette: &Palette,
756 style: &FieldStyle,
757) -> Response {
758 // The mismatch path: described as one thing and filled as another. Nothing
759 // here can fix it, so it is drawn as the empty, inert version of what was
760 // described — visible on screen, in the way an empty select is at the
761 // webview renderer, rather than reported in a log nobody reads.
762 let mut discard = String::new();
763 let mut off = false;
764
765 match shape_of(field) {
766 Control::Slid => {
767 let value = match filling {
768 Filling::Text(text) => text,
769 _ => &mut discard,
770 };
771 // `shape_of` has already refused an unbounded range, so the extent
772 // is only missing here if a bound is not a number — a date range,
773 // say, which this control cannot draw either.
774 let Some(extent) = extent(field) else {
775 return ui.label(RichText::new(value.as_str()).color(palette.content));
776 };
777
778 // A value the host cannot read starts at the low end rather than at
779 // zero, which may be outside the extent entirely. Nothing is
780 // written back until the user drags, so an unreadable value the app
781 // put there survives being looked at.
782 let mut number = value.parse::<f64>().unwrap_or(*extent.start());
783 let mut slider = Slider::new(&mut number, extent).text("");
784 if let Some(places) = decimals(field.step) {
785 slider = slider.max_decimals(places);
786 }
787 if let Some(step) = field.step.and_then(|s| s.parse::<f64>().ok()) {
788 slider = slider.step_by(step);
789 }
790 let response = ui.add(slider);
791 if response.changed() {
792 *value = match decimals(field.step) {
793 Some(places) => format!("{number:.places$}"),
794 None => number.to_string(),
795 };
796 }
797 response
798 }
799 Control::Typed => {
800 let text = match filling {
801 Filling::Text(text) => text,
802 _ => &mut discard,
803 };
804 // An empty frame and no margin: the well is this crate's, and egui's
805 // own control background and padding would sit underneath it saying
806 // something different about both.
807 // Keyed on the description's own `multiline` and not on the
808 // member: a markdown field is several lines by definition, and a
809 // single-line edit would be a control the value cannot fit in. egui
810 // does nothing else with the markdown, which is the honest answer
811 // rather than a gap -- the source is text, and editing it as text
812 // loses none of it.
813 let mut edit = if field.kind.multiline() {
814 TextEdit::multiline(text)
815 } else {
816 TextEdit::singleline(text)
817 }
818 .frame(egui::Frame::NONE)
819 .margin(Margin::ZERO)
820 .text_color(palette.content)
821 .password(field.kind.confidential());
822 if let Some(ghost) = field.placeholder {
823 edit = edit.hint_text(RichText::new(ghost).color(palette.content_muted));
824 }
825 frame(ui, Depth::Well, palette, style.frame, |ui| ui.add(edit))
826 }
827 Control::Toggled => {
828 let on = match filling {
829 Filling::On(on) => on,
830 _ => &mut off,
831 };
832 ui.checkbox(on, RichText::new(field.label).color(palette.content))
833 }
834 Control::Listed => {
835 let value = match filling {
836 Filling::Text(text) => text,
837 _ => &mut discard,
838 };
839 // No `shown_label` counterpart, and none is needed: a value no
840 // option carries leaves every button unfilled, which is already
841 // the honest report on screen. The select needs the fix because it
842 // has one slot and must put *something* in it.
843 let group = ui.vertical(|ui| {
844 let mut answered: Option<Response> = None;
845 for opt in field.options {
846 // An option that cannot be picked yet is drawn and does not
847 // answer, with the precondition beside it rather than
848 // behind a hover: a greyed row with no reason reads as a
849 // dead end, which is the state `Choice::unavailable` exists
850 // to stop being sayable.
851 let picked = if let Some(reason) = opt.unavailable {
852 ui.horizontal(|ui| {
853 let picked = ui
854 .add_enabled_ui(false, |ui| {
855 ui.radio_value(
856 value,
857 opt.value.to_owned(),
858 RichText::new(opt.label).color(palette.content_muted),
859 )
860 })
861 .inner;
862 ui.label(RichText::new(reason).color(palette.content_muted));
863 picked
864 })
865 .inner
866 } else {
867 ui.radio_value(
868 value,
869 opt.value.to_owned(),
870 RichText::new(opt.label).color(option_color(value, opt.value, palette)),
871 )
872 };
873 answered = Some(match answered {
874 Some(prev) => prev.union(picked),
875 None => picked,
876 });
877 }
878 answered
879 });
880 // A group described with no options answers as its own empty area
881 // rather than as no response at all, which keeps the caller's
882 // `.changed()` chain working on a field whose option list has not
883 // loaded yet.
884 group.inner.unwrap_or(group.response)
885 }
886 Control::Chosen => {
887 let value = match filling {
888 Filling::Text(text) => text,
889 _ => &mut discard,
890 };
891 let (shown, tone) = chosen_text(field, value, palette);
892 ComboBox::from_id_salt(field.name)
893 .selected_text(RichText::new(shown).color(tone))
894 .show_ui(ui, |ui| {
895 for opt in field.options {
896 // Same rule as the radio group: shown, inert, and
897 // saying why. A closed control hides its list, so the
898 // reason has to travel with the row it belongs to.
899 if let Some(reason) = opt.unavailable {
900 ui.add_enabled_ui(false, |ui| {
901 ui.selectable_value(
902 value,
903 opt.value.to_owned(),
904 RichText::new(format!("{} {reason}", opt.label))
905 .color(palette.content_muted),
906 );
907 });
908 continue;
909 }
910 ui.selectable_value(
911 value,
912 opt.value.to_owned(),
913 RichText::new(opt.label).color(option_color(value, opt.value, palette)),
914 );
915 }
916 })
917 .response
918 }
919 }
920}
921
922/// One field, as the column the app drops into its form.
923///
924/// The anatomy is `makeover-webview`'s, so the two renderers put a form
925/// together the same way: label, control, hint, error, top to bottom, with a
926/// checkbox labelling itself instead of taking a label above.
927///
928/// Returns [`None`] for a [`FieldKind::Hidden`] field, which is what
929/// [`FieldKind::visible`] means and is the honest answer here: a webview still
930/// emits an input for it because the form submits, and an immediate-mode
931/// renderer has no form and no submission, so a hidden field is a value the app
932/// already holds and there is nothing to draw or to respond to.
933///
934/// `state` is the description's interaction axis.
935/// [`State::Disabled`] greys the field and stops it answering, through
936/// [`State::suppresses_interaction`] rather than through a second reading of
937/// what disabled means. Focus is not on that axis and never reaches here: egui
938/// owns reach, focus and the ring for this renderer, and one ring means not a
939/// second one per renderer that happens to have opinions.
940pub fn field(
941 ui: &mut Ui,
942 field: &Field<'_>,
943 filling: Filling<'_>,
944 state: Option<State>,
945 palette: &Palette,
946 style: &FieldStyle,
947) -> Option<Response> {
948 if !field.kind.visible() {
949 return None;
950 }
951 let enabled = !state.is_some_and(State::suppresses_interaction);
952 let text = if enabled {
953 palette.content
954 } else {
955 palette.content_muted
956 };
957
958 let response = ui
959 .vertical(|ui| {
960 ui.spacing_mut().item_spacing.y = style.gap;
961
962 // A checkbox labels itself, on the right of the box.
963 // `FieldKind::labels_itself` is the description saying so, and both
964 // webview apps special-cased it inline before it did.
965 if !field.kind.labels_itself() {
966 ui.label(RichText::new(label_text(field, style)).color(text));
967 }
968
969 let response = ui
970 .add_enabled_ui(enabled, |ui| control(ui, field, filling, palette, style))
971 .inner;
972
973 // Standing help first, then what is wrong now. Both, in that order,
974 // for the reason the webview renderer names both in
975 // `aria-describedby`: an error appearing must not take the hint
976 // away with it.
977 if let Some(hint) = field.hint {
978 ui.label(RichText::new(hint).color(palette.content_muted));
979 }
980 if let Some(error) = field.error {
981 ui.label(RichText::new(error).color(palette.danger));
982 }
983 response
984 })
985 .inner;
986
987 Some(response)
988}
989
990/// A set of fields, laid down a column.
991///
992/// `show_extended` is the disclosure, and it is a parameter rather than state
993/// held here because the disclosure belongs to the *form* and not to any field:
994/// [`Field::extended`] marks which fields are behind one, and the app owns
995/// whether it is open. That is the same division `makeover-webview` draws when
996/// it marks the group `data-extended` and emits no control to toggle it.
997///
998/// `draw` is called once per field that should be visible, in order. Taking a
999/// callback rather than a slice of [`Filling`]s is what keeps the app's own
1000/// values borrowed one at a time: a form's fields usually live in different
1001/// structs, and a parallel array would have to be built each frame and kept in
1002/// step with the description by hand.
1003pub fn group<'a>(
1004 ui: &mut Ui,
1005 fields: &'a [Field<'a>],
1006 show_extended: bool,
1007 style: &FieldStyle,
1008 mut draw: impl FnMut(&mut Ui, &'a Field<'a>),
1009) {
1010 ui.vertical(|ui| {
1011 ui.spacing_mut().item_spacing.y = style.group_gap;
1012 for f in fields {
1013 if f.extended && !show_extended {
1014 continue;
1015 }
1016 draw(ui, f);
1017 }
1018 });
1019}
1020
1021#[cfg(test)]
1022mod tests {
1023 use super::*;
1024
1025 fn palette(well: Color32) -> Palette {
1026 Palette {
1027 page: Color32::from_rgb(1, 1, 1),
1028 raised: Color32::from_rgb(2, 2, 2),
1029 overlay: Color32::from_rgb(3, 3, 3),
1030 well,
1031 sunken: Color32::from_rgb(4, 4, 4),
1032 bevel_light: Color32::WHITE,
1033 bevel_dark: Color32::BLACK,
1034 elevation: Color32::from_black_alpha(46),
1035 content: Color32::from_rgb(5, 5, 5),
1036 content_secondary: Color32::from_rgb(55, 55, 55),
1037 content_muted: Color32::from_rgb(6, 6, 6),
1038 action: Color32::from_rgb(7, 7, 7),
1039 danger: Color32::from_rgb(8, 8, 8),
1040 success: Color32::from_rgb(9, 9, 9),
1041 warning: Color32::from_rgb(10, 10, 10),
1042 info: Color32::from_rgb(11, 11, 11),
1043 }
1044 }
1045
1046 /// The cast is egui's own shadow type carrying the theme's tone, which is
1047 /// the whole of what this crate had to decide for it: unlike a bevel, egui
1048 /// already knows how to paint one.
1049 #[test]
1050 fn the_cast_hands_egui_the_themes_tone() {
1051 let p = palette(Color32::from_rgb(9, 9, 9));
1052 let cast = p.cast();
1053 assert_eq!(cast.color, p.elevation);
1054 assert!(cast.blur > 0, "a cast shadow is soft");
1055 assert_eq!(cast.offset, [0, 2], "it falls downward and only a little");
1056 }
1057
1058 #[test]
1059 fn a_well_resolves_to_its_own_token() {
1060 // No substitution left. The page-filled well was a stand-in for a
1061 // token that did not exist yet; it exists now.
1062 let w = Color32::from_rgb(9, 9, 9);
1063 let p = palette(w);
1064 assert_eq!(p.fill(Fill::Well), Some(w));
1065 assert_ne!(p.fill(Fill::Well), Some(p.page));
1066 }
1067
1068 #[test]
1069 fn every_intent_is_a_plain_lookup() {
1070 let p = palette(Color32::from_rgb(9, 9, 9));
1071 assert_eq!(p.fill(Fill::Page), Some(p.page));
1072 assert_eq!(p.fill(Fill::Raised), Some(p.raised));
1073 assert_eq!(p.fill(Fill::Overlay), Some(p.overlay));
1074 }
1075
1076 /// Sunken is its own colour, not the well's and not the page's. The two
1077 /// are authored in opposite directions and an earlier cut of the
1078 /// description conflated them.
1079 #[test]
1080 fn sunken_is_neither_the_well_nor_the_page() {
1081 let p = palette(Color32::from_rgb(9, 9, 9));
1082 assert_eq!(p.fill(Fill::Sunken), Some(p.sunken));
1083 assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Well));
1084 assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Page));
1085 }
1086
1087 #[test]
1088 fn a_raised_region_never_resolves_to_the_well_fill() {
1089 // The cross-app bug, asserted at the renderer boundary this time.
1090 let p = palette(Color32::from_rgb(9, 9, 9));
1091 let raised = Depth::Raised.fill().and_then(|f| p.fill(f));
1092 let well = Depth::Well.fill().and_then(|f| p.fill(f));
1093 assert_eq!(raised, Some(p.raised));
1094 assert_ne!(raised, well);
1095 }
1096
1097 #[test]
1098 fn an_overlay_is_cast_onto_the_page_and_takes_no_edge() {
1099 // makeover-layout 0.14.0 is what made this reachable. The answer was
1100 // already here at 0.10.0 and the question could not be asked.
1101 let p = palette(Color32::from_rgb(9, 9, 9));
1102 assert_eq!(
1103 Depth::Overlay.fill().and_then(|f| p.fill(f)),
1104 Some(p.overlay)
1105 );
1106 assert_eq!(Depth::Overlay.bevel(), None);
1107 // The shadow `frame` reaches for is the theme's tone rather than
1108 // egui's default, which is the whole reason `cast` exists.
1109 assert_eq!(p.cast().color, p.elevation);
1110 }
1111
1112 #[test]
1113 fn the_lit_edge_swaps_when_a_card_is_pressed() {
1114 let p = palette(Color32::from_rgb(9, 9, 9));
1115 let (tl, _) = Depth::Raised.bevel().unwrap().edges();
1116 let (ptl, _) = Depth::Raised.pressed().bevel().unwrap().edges();
1117 assert_eq!(p.edge(tl), p.bevel_light);
1118 assert_eq!(p.edge(ptl), p.bevel_dark);
1119 }
1120
1121 #[test]
1122 fn flat_asks_for_neither_fill_nor_edge() {
1123 assert!(Depth::Flat.fill().is_none());
1124 assert!(Depth::Flat.bevel().is_none());
1125 }
1126
1127 #[test]
1128 fn a_select_keeps_a_value_none_of_its_options_carries() {
1129 // The save-the-wrong-thing bug, asserted at the second renderer so it
1130 // is not re-found there. goingson's own numbers.
1131 let options = [
1132 Choice::plain("1"),
1133 Choice::plain("3"),
1134 Choice::plain("7"),
1135 Choice::plain("14"),
1136 ];
1137 assert_eq!(shown_label(&options, "10"), "10");
1138 // And a value that does match reads as its label, not as itself.
1139 let spelled = [Choice::new("7", "One week")];
1140 assert_eq!(shown_label(&spelled, "7"), "One week");
1141 }
1142
1143 #[test]
1144 fn an_unanswered_chooser_reads_its_ghost_text_and_reads_it_muted() {
1145 let p = palette(Color32::from_rgb(9, 9, 9));
1146 let options = [Choice::new("sp404", "SP-404")];
1147 let field = Field {
1148 placeholder: Some("Select device..."),
1149 ..Field::select("device", "Conform for device", &options)
1150 };
1151
1152 assert_eq!(
1153 chosen_text(&field, "", &p),
1154 ("Select device...", p.content_muted),
1155 "ghost text is not an answer, so it takes the tone the typed kinds' ghost text does"
1156 );
1157
1158 // Answered, and it is the label that reads rather than the value.
1159 assert_eq!(chosen_text(&field, "sp404", &p), ("SP-404", p.content));
1160 }
1161
1162 #[test]
1163 fn a_wrong_answer_is_not_an_absent_one() {
1164 // The retention-10 bug and the ghost text meet here: a value no option
1165 // carries still reads as itself, because the field IS answered and the
1166 // answer is wrong. Only the empty value is unanswered.
1167 let p = palette(Color32::from_rgb(9, 9, 9));
1168 let options = [Choice::plain("1"), Choice::plain("7")];
1169 let field = Field {
1170 placeholder: Some("Pick one"),
1171 ..Field::select("retention", "Keep backups for", &options)
1172 };
1173
1174 assert_eq!(chosen_text(&field, "10", &p), ("10", p.content));
1175 }
1176
1177 #[test]
1178 fn a_chooser_with_no_ghost_text_is_unchanged() {
1179 // The whole change is opt-in from the description. A field that says
1180 // nothing about its empty state still shows an empty box.
1181 let p = palette(Color32::from_rgb(9, 9, 9));
1182 let options = [Choice::plain("1")];
1183 let field = Field::select("retention", "Keep backups for", &options);
1184 assert_eq!(chosen_text(&field, "", &p), ("", p.content));
1185 }
1186
1187 #[test]
1188 fn a_range_is_slid_and_a_number_is_typed_into() {
1189 // The distinction the kind was added for, at the renderer that has to
1190 // act on it. A well with a figure in it is not a quiet slider.
1191 assert_eq!(control_shape(FieldKind::Range), Control::Slid);
1192 assert_eq!(control_shape(FieldKind::Number), Control::Typed);
1193 }
1194
1195 #[test]
1196 fn a_range_missing_an_end_falls_back_to_a_well() {
1197 // egui's `Slider` demands both ends, so inventing one would be this
1198 // renderer picking bounds the app never stated and the user then
1199 // dragging against them. A typed number takes every answer the slider
1200 // would.
1201 let whole = Field::range("review", "Review above", "0", "1");
1202 assert_eq!(shape_of(&whole), Control::Slid);
1203
1204 let half = Field {
1205 max: Some("1"),
1206 ..Field::new(FieldKind::Range, "review", "Review above")
1207 };
1208 assert_eq!(shape_of(&half), Control::Typed);
1209 assert_eq!(extent(&half), None);
1210
1211 // A bound this host cannot read is the same outcome by a different
1212 // route: the description carries bounds as text because the bound of a
1213 // date is a date.
1214 let dated = Field::range("when", "When", "2026-08-01", "2026-08-31");
1215 assert_eq!(extent(&dated), None);
1216 }
1217
1218 #[test]
1219 fn the_step_decides_how_a_dragged_value_is_written_back() {
1220 // Without it a 0-to-1 threshold writes back whatever float the drag
1221 // landed on, which is the host's granularity and is what the
1222 // description says an absent step means.
1223 assert_eq!(decimals(None), None);
1224 assert_eq!(decimals(Some("1")), Some(0));
1225 assert_eq!(decimals(Some("0.01")), Some(2));
1226 // Trailing zeros are not precision: 0.10 is a one-decimal question.
1227 assert_eq!(decimals(Some("0.10")), Some(1));
1228 }
1229
1230 #[test]
1231 fn an_unavailable_option_is_drawn_muted_rather_than_dropped() {
1232 // The tone rule, at the one place it is a claim rather than a
1233 // preference: this option genuinely will not answer, so muted is the
1234 // truth. The available ones beside it keep the secondary intent.
1235 let p = palette(Color32::from_rgb(9, 9, 9));
1236 let options = [
1237 Choice::new("chromatic", "Chromatic"),
1238 Choice::new("multi", "Multi-sample").unless("Drop a second sample."),
1239 ];
1240 assert!(options[0].available());
1241 assert!(!options[1].available());
1242 assert_eq!(
1243 option_color("chromatic", options[0].value, &p),
1244 p.content,
1245 "the chosen option is the emphasised thing"
1246 );
1247 assert_eq!(
1248 option_color("chromatic", options[1].value, &p),
1249 p.content_secondary,
1250 "and `option_color` never mutes: the unavailable path is what does"
1251 );
1252 }
1253
1254 #[test]
1255 fn only_a_required_field_is_marked() {
1256 let style = FieldStyle::default();
1257 let plain = Field::new(FieldKind::Text, "title", "Title");
1258 assert_eq!(label_text(&plain, &style), "Title");
1259
1260 let required = Field {
1261 required: true,
1262 ..plain
1263 };
1264 assert_eq!(label_text(&required, &style), "Title *");
1265
1266 // The marker is copy and the app owns it, which is why it is a knob.
1267 let house = FieldStyle {
1268 required_marker: "(required)",
1269 ..style
1270 };
1271 assert_eq!(label_text(&required, &house), "Title (required)");
1272 }
1273
1274 #[test]
1275 fn a_select_and_a_checkbox_are_pressed_and_everything_else_is_typed_into() {
1276 // What decides whether the control gets a well. A well is for what the
1277 // user looks into, and only one of these is.
1278 assert_eq!(control_shape(FieldKind::Select), Control::Chosen);
1279 assert_eq!(control_shape(FieldKind::Radio), Control::Listed);
1280 assert_eq!(control_shape(FieldKind::Checkbox), Control::Toggled);
1281 for k in [
1282 FieldKind::Text,
1283 FieldKind::Secret,
1284 FieldKind::Number,
1285 FieldKind::Email,
1286 FieldKind::Url,
1287 FieldKind::Tel,
1288 FieldKind::Textarea,
1289 FieldKind::Rich,
1290 ] {
1291 assert_eq!(control_shape(k), Control::Typed, "{k:?} is typed into");
1292 }
1293 // And the two multi-line ones get a multi-line edit, which is the half
1294 // `control_shape` alone does not say: both are typed into, and only one
1295 // of the two edit shapes can hold a markdown document.
1296 assert!(FieldKind::Rich.multiline());
1297 assert!(FieldKind::Textarea.multiline());
1298 assert!(!FieldKind::Text.multiline());
1299 }
1300
1301 #[test]
1302 fn the_two_option_taking_kinds_are_drawn_differently_on_purpose() {
1303 // The description holds Select and Radio apart, and a renderer that
1304 // collapsed them would silently answer a question the app did not ask:
1305 // audiofiles' storage style is irreversible and its alternatives have
1306 // to be readable without opening anything. Asserting the two shapes
1307 // differ is asserting that distinction survives the trip.
1308 assert!(FieldKind::Select.offers_options());
1309 assert!(FieldKind::Radio.offers_options());
1310 assert_ne!(
1311 control_shape(FieldKind::Select),
1312 control_shape(FieldKind::Radio)
1313 );
1314 }
1315
1316 #[test]
1317 fn an_unchosen_option_is_secondary_and_never_muted() {
1318 let p = palette(Color32::from_rgb(4, 4, 4));
1319 assert_eq!(option_color("wav", "wav", &p), p.content);
1320 assert_eq!(option_color("wav", "aiff", &p), p.content_secondary);
1321 // The whole point of the distinction: muted is what Disabled resolves
1322 // to, so an option wearing it would claim it does not answer a press.
1323 assert_ne!(option_color("wav", "aiff", &p), p.content_muted);
1324 }
1325
1326 #[test]
1327 fn a_hidden_field_draws_nothing_and_answers_nothing() {
1328 // Where the two renderers legitimately part: a webview still emits an
1329 // input because the form submits, and there is no form here.
1330 let f = Field::new(FieldKind::Hidden, "id", "Id");
1331 let p = palette(Color32::from_rgb(9, 9, 9));
1332 egui::__run_test_ui(|ui| {
1333 let drawn = field(ui, &f, Filling::Absent, None, &p, &FieldStyle::default());
1334 assert!(drawn.is_none());
1335 });
1336 }
1337
1338 #[test]
1339 fn a_disabled_field_stops_answering_and_an_unstated_one_does_not() {
1340 let f = Field::new(FieldKind::Text, "title", "Title");
1341 let p = palette(Color32::from_rgb(9, 9, 9));
1342 let style = FieldStyle::default();
1343 egui::__run_test_ui(|ui| {
1344 let mut text = String::from("x");
1345 let disabled = field(
1346 ui,
1347 &f,
1348 Filling::Text(&mut text),
1349 Some(State::Disabled),
1350 &p,
1351 &style,
1352 )
1353 .unwrap();
1354 assert!(!disabled.enabled());
1355
1356 // Stating no state is the ordinary case and answers. Focus used to
1357 // be the counter-example here; it is egui's now and a description
1358 // cannot state it at all.
1359 let mut text = String::from("x");
1360 let plain = field(ui, &f, Filling::Text(&mut text), None, &p, &style).unwrap();
1361 assert!(plain.enabled(), "an unstated field still answers");
1362 });
1363 }
1364
1365 #[test]
1366 fn a_field_described_one_way_and_filled_another_is_drawn_inert() {
1367 // No panic and no write-through. A checkbox handed a string cannot be
1368 // filled, so it is drawn off and left alone.
1369 let f = Field::new(FieldKind::Checkbox, "done", "Done");
1370 let p = palette(Color32::from_rgb(9, 9, 9));
1371 let mut text = String::from("untouched");
1372 egui::__run_test_ui(|ui| {
1373 let drawn = field(
1374 ui,
1375 &f,
1376 Filling::Text(&mut text),
1377 None,
1378 &p,
1379 &FieldStyle::default(),
1380 );
1381 assert!(drawn.is_some());
1382 });
1383 assert_eq!(text, "untouched");
1384 }
1385
1386 #[test]
1387 fn the_disclosure_belongs_to_the_form_and_not_to_the_field() {
1388 let fields = [
1389 Field::new(FieldKind::Text, "title", "Title"),
1390 Field {
1391 extended: true,
1392 ..Field::new(FieldKind::Text, "notes", "Notes")
1393 },
1394 ];
1395 let style = FieldStyle::default();
1396
1397 let mut closed = Vec::new();
1398 egui::__run_test_ui(|ui| {
1399 group(ui, &fields, false, &style, |_, f| closed.push(f.name));
1400 });
1401 assert_eq!(closed, ["title"]);
1402
1403 let mut open = Vec::new();
1404 egui::__run_test_ui(|ui| {
1405 group(ui, &fields, true, &style, |_, f| open.push(f.name));
1406 });
1407 assert_eq!(open, ["title", "notes"]);
1408 }
1409
1410 #[test]
1411 fn the_default_frame_is_square_and_one_point() {
1412 let d = FrameStyle::default();
1413 assert_eq!(d.radius, CornerRadius::ZERO);
1414 assert_eq!(d.margin, Margin::ZERO);
1415 assert!((d.stroke - 1.0).abs() < f32::EPSILON);
1416 }
1417}