Skip to main content

max / makeover-immediate

93.1 KB · 2138 lines History Blame Raw
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.33.0: an interval is a sixth control shape
158 //!
159 //! `makeover-layout` 0.34.0's [`FieldKind::Interval`], drawn as `Control::Spanned`:
160 //! two drag boxes on one row with the word `to` between them.
161 //!
162 //! - **Dragged rather than typed**, because that is what these controls already
163 //! were. audiofiles' six filter axes are `DragValue` pairs sharing an extent,
164 //! a speed and a suffix, and describing them into two text boxes would be a
165 //! port that cost the app a control.
166 //! - **One row, not two wells stacked.** Two wells are two questions on screen
167 //! whatever the description says, and the arrangement is the whole content of
168 //! the kind.
169 //! - **An empty end reads as the bound it stands for.** An unset minimum sits
170 //! on the low edge and stores no filter, which is what the shipped control
171 //! did; egui's `DragValue` has no empty state, and a text box in its place
172 //! would be the regression above. With no extent to fall back on it reads
173 //! zero -- the one number this renderer invents, invented where the
174 //! description declined to say anything.
175 //! - **The word rather than a dash**, which on a signed axis is a minus sign.
176 //! audiofiles filters loudness in dBFS.
177 //!
178 //! `Axis` holds the four facts both boxes share, because they are one axis:
179 //! reading `min`, `max`, `step` and `unit` once is what stops the two ends
180 //! drifting apart.
181 //!
182 //! # 0.32.0: a number draws its unit
183 //!
184 //! `makeover-layout` 0.33.0's [`Field::unit`], and this host is the one the
185 //! member was argued from: egui's `Slider` already draws a suffix beside its
186 //! readout, which is where these controls put the unit before they were
187 //! described and is somewhere a label cannot reach.
188 //!
189 //! So a slider takes it as a suffix, inside the control. A typed number has no
190 //! readout of its own and takes it as a muted label after the box. Every other
191 //! kind ignores it, and the description says which those are --
192 //! `FieldKind::measurable`, rather than a `matches!` kept here.
193 //!
194 //! # 0.31.0: the slider's track is a curve
195 //!
196 //! `makeover-layout` 0.32.0 says what a slider is: a fraction and a function
197 //! taking numbers to numbers, with `min` and `max` being `f(0)` and `f(1)`
198 //! rather than the control's extent. This host has the easiest job of the
199 //! three, because egui already has the control -- `Slider::logarithmic` is a
200 //! constant-ratio track, so the mapping is a builder call rather than an
201 //! arithmetic of its own.
202 //!
203 //! Two things worth knowing. The granularity moved onto the curve, so a range
204 //! reads `Field::curve.step()` and every other kind still reads `Field::step`;
205 //! the step is in the value's own units under either curve, so the display
206 //! precision is derived exactly as before. And the fallback for a ratio curve
207 //! across zero is asked of `Curve::is_ratio` rather than matched on the
208 //! variant, so this renderer and a terminal cannot disagree about when a
209 //! logarithmic request is honoured.
210 //!
211 //! # 0.28.0: the slider, the unanswered chooser, and the option that is not
212 //! offered yet
213 //!
214 //! Three things `makeover-layout` 0.28.0 lets a description say, all three
215 //! found by audiofiles' forms port hitting a wall it could not describe its way
216 //! past.
217 //!
218 //! - **[`FieldKind::Range`] is a fifth control shape**, `Control::Slid`, and
219 //! the first one added since 0.5.0. egui has `Slider` and this crate had no
220 //! way to be asked for one, so four sliders in the only consuming app stayed
221 //! hand-rolled against a vocabulary that could not name them. A range missing
222 //! an end falls back to a well rather than to invented bounds, which is what
223 //! `makeover_layout::Field::bounded` is for.
224 //! - **`Field::placeholder` finally reads on a chooser.** It was sayable and
225 //! this renderer ignored it, so a select with nothing chosen showed an empty
226 //! box. Nothing new is described; the renderer caught up.
227 //! - **`Choice::unavailable` is drawn rather than dropped.** The option stays
228 //! in the list, inert, with its precondition beside it instead of behind a
229 //! hover — a greyed row with no reason reads as a dead end, which is the
230 //! whole finding.
231 //! - **`Choice::detail` (makeover-layout 0.39.0) is drawn under the option in a
232 //! radio group and inside the row in a combo.** A closed chooser hides its
233 //! list, so everything an option carries has to travel with its row; a group
234 //! has a line to spare and putting a sentence beside the control instead
235 //! would push every option's radio out of line with its neighbours.
236 //!
237 //! The value still arrives as a `&mut String` and a slider is a number, so the
238 //! parse and the write-back are this renderer's, and the write happens only on
239 //! a real drag: a value the app put there that this host cannot read survives
240 //! being looked at.
241
242 #![forbid(unsafe_code)]
243
244 use egui::{
245 Color32, ComboBox, CornerRadius, DragValue, Margin, Painter, Rect, Response, RichText, Shape,
246 Slider, Stroke, TextEdit, Ui,
247 };
248 use makeover_layout::{
249 Bevel, Choice, Depth, Edge, Field, FieldKind, Fill, State, ThemeVariant, Tone,
250 };
251 use std::ops::RangeInclusive;
252
253 /// Columns, narrowing, cell parts and the sort caret, over `egui_extras`.
254 pub mod table;
255 pub mod widget;
256
257 /// The resolved colours this renderer needs, as flat values.
258 ///
259 /// Built by the app from whatever it already uses to resolve a theme, then
260 /// held and reused. Deliberately not a trait and not string-keyed: a bevel is
261 /// painted per widget per frame, and a map lookup per edge is a cost with
262 /// nothing to show for it.
263 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
264 pub struct Palette {
265 /// `surface-page`.
266 pub page: Color32,
267 /// `surface-raised`.
268 pub raised: Color32,
269 /// `surface-overlay`.
270 pub overlay: Color32,
271 /// `surface-well`.
272 ///
273 /// Required, not optional. makeover derives it for every theme from 2.3.0,
274 /// so a resolved palette without a well is not a thing that exists here.
275 /// It was an `Option` while that was untrue, and this renderer substituted
276 /// the page; `makeover-tui` keeps its own `Option` for a different reason,
277 /// since a terminal can have the colour and still be unable to show it.
278 pub well: Color32,
279 /// `surface-sunken`.
280 ///
281 /// A surface set back from the one it sits on, by colour and nothing else.
282 /// Not a well: a well is a hole with an edge, and this has no edge. An
283 /// immediate-mode renderer paints an arbitrary rect, so unlike
284 /// `makeover-tui` it has no excuse for declining this one.
285 ///
286 /// Required rather than optional, on the same footing as `well`: all 31
287 /// themes makeover embeds author it.
288 pub sunken: Color32,
289 /// `bevel-light`.
290 pub bevel_light: Color32,
291 /// `bevel-dark`.
292 pub bevel_dark: Color32,
293 /// `elevation`.
294 ///
295 /// What a surface that floats OVER the page is cast onto it with. The one
296 /// intent here that is about a surface's relationship to the page rather
297 /// than about the surface, which is why it is a translucent near-black on
298 /// every theme rather than something read off the palette's own ramp.
299 ///
300 /// **Only for a surface that overlays.** A menu, a tooltip, a modal. A
301 /// surface *in* the layout takes a bevel, and reaching for this on a panel
302 /// or a card is how a pre-Platinum look survives a conversion under a new
303 /// name.
304 ///
305 /// egui has a real answer for this where a terminal does not: see
306 /// [`Palette::cast`], which is the shadow to hand an
307 /// [`egui::Frame`](egui::Frame).
308 pub elevation: Color32,
309 /// `content`.
310 ///
311 /// Ordinary text. Added 0.5.0 with the field renderer, which is the first
312 /// thing here that draws any: until then this crate painted surfaces and
313 /// edges and let the caller's own egui visuals answer for text.
314 pub content: Color32,
315 /// `content-secondary`.
316 ///
317 /// Inactive but usable: it still answers a press. The middle tone of the
318 /// three (wiki `three-tone-convention`), and the one an unchosen option in
319 /// a choice field takes. Added 0.26.0 for that widget, which drew every
320 /// option at full `content` and so said nothing about which one was
321 /// chosen beyond the dot egui paints.
322 ///
323 /// Not [`content_muted`](Self::content_muted), which carries a claim:
324 /// `State::Disabled` resolves to it, so a live control wearing it tells the
325 /// user it will not answer. `makeover-tui` draws the same widget the same
326 /// way from `makeover-tui@230bf63`.
327 ///
328 /// A step of `content` toward the page, derived at load by `makeover`
329 /// rather than authored, so it is read off the resolved theme here like
330 /// any other token and never re-derived.
331 pub content_secondary: Color32,
332 /// `content-muted`.
333 ///
334 /// A field's hint, and what
335 /// [`makeover_layout::State::Disabled`](makeover_layout::State::Disabled)
336 /// resolves to. Both readings come from the description rather than from
337 /// here: `State::Disabled` names this intent by token.
338 pub content_muted: Color32,
339 /// `action-primary`.
340 ///
341 /// What a control is drawn in. Added 0.12.0 with the table renderer, for the
342 /// reason `content` was added 0.5.0 with the field renderer: a link in a
343 /// cell is the first thing here that needs the action intent, and a palette
344 /// should carry what is used.
345 ///
346 /// This is the intent [`CellPart`](makeover_layout::CellPart) exists to
347 /// separate. A cell holding a control took the cell's text colour until the
348 /// description could say otherwise, which is the drift `makeover-layout`
349 /// 0.14.0 named and `makeover-webview` 0.25.0 fixed on its own side.
350 pub action: Color32,
351 /// `danger`.
352 ///
353 /// A field's error message, a destructive control, a bar that has run over.
354 pub danger: Color32,
355 /// `success`.
356 ///
357 /// Added 0.18.0 with [`widget`], which is the first thing here that draws a
358 /// [`Tone`]. The three status intents arrive together and not one at a
359 /// time: [`Tone`] is five members wide and a resolver missing one has to
360 /// invent a colour for it, which is the substitution this crate spent
361 /// 0.2.0 removing from [`Palette::fill`].
362 pub success: Color32,
363 /// `warning`.
364 pub warning: Color32,
365 /// `info`.
366 pub info: Color32,
367 }
368
369 impl Palette {
370 /// Resolve a surface intent, or `None` for one this renderer does not know.
371 ///
372 /// A plain lookup. There is still no substitution: the old one existed only
373 /// while `surface-well` was underived, and every consumer reads the real
374 /// token now.
375 ///
376 /// `Option` since 0.3.0, because [`Fill`] became `#[non_exhaustive]` in
377 /// `makeover-layout` 0.4.0 and a total function over an open enum can only
378 /// stay total by inventing a colour for a member it has never heard of.
379 /// That is the substitution this crate spent 0.2.0 removing, so the return
380 /// type moved instead. Every member the description has today is answered
381 /// with `Some`.
382 #[must_use]
383 pub const fn fill(&self, fill: Fill) -> Option<Color32> {
384 match fill {
385 Fill::Page => Some(self.page),
386 Fill::Raised => Some(self.raised),
387 Fill::Overlay => Some(self.overlay),
388 Fill::Well => Some(self.well),
389 Fill::Sunken => Some(self.sunken),
390 _ => None,
391 }
392 }
393
394 /// The colour a [`Tone`] reads as.
395 ///
396 /// Total, unlike [`fill`](Self::fill), and the difference is not an
397 /// inconsistency. `Fill` is `#[non_exhaustive]` and `Tone` is not: the
398 /// description layer settled tone at five members and grows surfaces, so a
399 /// total function here cannot be made to invent a colour by an upstream
400 /// release the way a total `fill` could.
401 ///
402 /// [`Tone::Neutral`] is [`content`](Self::content) rather than a colour of
403 /// its own, which is what "an ordinary fact" means: a neutral badge is text
404 /// in a box, not a fifth status.
405 #[must_use]
406 pub const fn tone(&self, tone: Tone) -> Color32 {
407 match tone {
408 Tone::Neutral => self.content,
409 Tone::Info => self.info,
410 Tone::Success => self.success,
411 Tone::Warning => self.warning,
412 Tone::Danger => self.danger,
413 }
414 }
415
416 /// The cast shadow for a surface that overlays the page.
417 ///
418 /// What "overlaying" means in immediate mode, answered rather than skipped.
419 /// egui already paints shadows for its menus and windows through
420 /// [`egui::Frame::shadow`], so the honest port is to hand that machinery the
421 /// theme's tone instead of egui's own default, not to invent a painter here
422 /// the way [`paint_bevel`] had to.
423 ///
424 /// The geometry matches what `makeover-webview` composes, in points rather
425 /// than pixels: a small downward offset and a wide soft blur. A Platinum-era
426 /// menu sits just off the page rather than hovering above it.
427 ///
428 /// ```no_run
429 /// # let palette: makeover_immediate::Palette = unimplemented!();
430 /// # let ui: &mut egui::Ui = unimplemented!();
431 /// egui::Frame::popup(ui.style())
432 /// .shadow(palette.cast())
433 /// .show(ui, |ui| { ui.label("over the page"); });
434 /// ```
435 #[must_use]
436 pub const fn cast(&self) -> egui::Shadow {
437 egui::Shadow {
438 offset: [0, 2],
439 blur: 24,
440 spread: 0,
441 color: self.elevation,
442 }
443 }
444
445 /// Resolve a bevel edge intent.
446 #[must_use]
447 pub const fn edge(&self, edge: Edge) -> Color32 {
448 match edge {
449 Edge::Light => self.bevel_light,
450 Edge::Dark => self.bevel_dark,
451 }
452 }
453 }
454
455 /// The geometry a framed region is drawn with.
456 ///
457 /// Every field is a value, which is why they all arrive from the caller:
458 /// radius and border width belong to `makeover-geometry`, and margins come
459 /// from its relational gaps.
460 #[derive(Debug, Clone, Copy, PartialEq)]
461 pub struct FrameStyle {
462 /// Corner radius. Square under the Platinum default.
463 pub radius: CornerRadius,
464 /// Inner margin between the frame and its contents.
465 pub margin: Margin,
466 /// Bevel stroke width, in points.
467 pub stroke: f32,
468 }
469
470 impl Default for FrameStyle {
471 /// A one-point square frame with no inner margin.
472 fn default() -> Self {
473 Self {
474 radius: CornerRadius::ZERO,
475 margin: Margin::ZERO,
476 stroke: 1.0,
477 }
478 }
479 }
480
481 /// Paint a two-tone edge just inside `rect`.
482 ///
483 /// Fill first, bevel after: this adds two polylines and nothing else, so it
484 /// composes over whatever is already there. That is what lets it go over an
485 /// [`egui::TextEdit`] after `ui.add`, where the widget's own fill has landed.
486 ///
487 /// Two three-point polylines meeting at opposite corners, rather than four
488 /// segments, so egui mitres the corner joins instead of leaving a notch.
489 ///
490 /// The dark polyline is drawn second, so the two corners where the runs meet
491 /// take its tone. That is the right answer here rather than a concession.
492 /// [`makeover_layout::Bevel`] holds those corners to belong to both edges, and
493 /// a renderer with room to divide one should; at the default one-point stroke
494 /// the corner is a one-point square, so the division is sub-pixel and
495 /// antialiasing resolves it to the same blend the mitre already gives. Splitting
496 /// it would add a seam and no information. `makeover-tui` does split, because a
497 /// terminal cell is large enough that not splitting costs a visible cell of edge
498 /// weight — the same rule, at a resolution where it has something to say.
499 pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) {
500 let (top_left, bottom_right) = bevel.edges();
501
502 // Inset by half a stroke so the line lands inside `rect` rather than
503 // straddling its edge, which on a fractional-scale display is the
504 // difference between one crisp pixel and two dim ones.
505 let r = rect.shrink(stroke / 2.0);
506
507 painter.add(Shape::line(
508 vec![r.left_bottom(), r.left_top(), r.right_top()],
509 Stroke::new(stroke, palette.edge(top_left)),
510 ));
511 painter.add(Shape::line(
512 vec![r.right_top(), r.right_bottom(), r.left_bottom()],
513 Stroke::new(stroke, palette.edge(bottom_right)),
514 ));
515 }
516
517 /// Draw a region at a given [`Depth`]: its fill and its edge, together.
518 ///
519 /// [`Depth::Flat`] gets neither, and inherits whatever it sits on. That is the
520 /// difference between level-with and painted-the-same-colour, and it is the
521 /// reason `Depth::fill` returns an [`Option`] rather than defaulting to the
522 /// page.
523 pub fn frame<R>(
524 ui: &mut Ui,
525 depth: Depth,
526 palette: &Palette,
527 style: FrameStyle,
528 add_contents: impl FnOnce(&mut Ui) -> R,
529 ) -> R {
530 let mut f = egui::Frame::new()
531 .corner_radius(style.radius)
532 .inner_margin(style.margin);
533 // Two ways there is no fill to paint, and they collapse to the same
534 // outcome: the depth names none (Depth::Flat), or it names one this
535 // renderer cannot resolve. Either way the frame goes unfilled and the
536 // bevel below carries the depth on its own, which is the rule this
537 // module already documents for Flat.
538 if let Some(fill) = depth.fill().and_then(|f| palette.fill(f)) {
539 f = f.fill(fill);
540 }
541 // A surface that overlays the page is cast onto it. [`Palette::cast`] has
542 // answered what that means here since 0.10.0 and nothing could reach it: a
543 // description had no way to say Overlay until makeover-layout 0.14.0, so
544 // the answer sat beside the question. Keyed off the fill rather than the
545 // variant, so it stays right for whatever else the description calls an
546 // overlay later.
547 if depth.fill() == Some(Fill::Overlay) {
548 f = f.shadow(palette.cast());
549 }
550 let framed = f.show(ui, add_contents);
551 if let Some(bevel) = depth.bevel() {
552 paint_bevel(
553 ui.painter(),
554 framed.response.rect,
555 bevel,
556 palette,
557 style.stroke,
558 );
559 }
560 framed.inner
561 }
562
563 /// The geometry a field group is drawn with.
564 ///
565 /// Values again, for the reason [`FrameStyle`] is: every number here belongs to
566 /// `makeover-geometry` and arrives already resolved.
567 #[derive(Debug, Clone, Copy, PartialEq)]
568 pub struct FieldStyle {
569 /// The well a text control sits in.
570 pub frame: FrameStyle,
571 /// Between a field's own parts: its label, its control, its hint and its
572 /// error.
573 pub gap: f32,
574 /// Between one field and the next.
575 pub group_gap: f32,
576 /// What marks a required field, appended to its label.
577 ///
578 /// A knob rather than a constant, because it is the one piece of *copy* in
579 /// this crate and copy is not a renderer's call. A webview does not need it
580 /// at all — it emits the `required` attribute and the browser answers — so
581 /// this renderer is the first place where a compulsory field either shows
582 /// that it is or silently does not.
583 pub required_marker: &'static str,
584 }
585
586 impl Default for FieldStyle {
587 /// The default frame, no gaps, and an asterisk.
588 fn default() -> Self {
589 Self {
590 frame: FrameStyle::default(),
591 gap: 0.0,
592 group_gap: 0.0,
593 required_marker: "*",
594 }
595 }
596 }
597
598 /// What the field currently holds, borrowed from wherever the app keeps it.
599 ///
600 /// The immediate-mode counterpart of `makeover_webview::form::Value`, and the
601 /// place the two renderers are forced apart: there the value is read back out
602 /// of the DOM after the fact, and here the widget writes through this borrow as
603 /// it is edited. Same reason the description carries neither.
604 ///
605 /// An enum rather than a bag of options, on the reasoning
606 /// `makeover_webview::form::Value` records: a checkbox holding a string is
607 /// unsayable here, where a struct would let it be said and then have to cope.
608 #[derive(Debug, Default)]
609 pub enum Filling<'a> {
610 /// Nothing to edit. The control is drawn and does not answer.
611 #[default]
612 Absent,
613 /// The buffer behind anything that takes typed text, a select included:
614 /// what a select holds is the `value` of one of its [`Choice`]s.
615 ///
616 /// [`Choice`]: makeover_layout::Choice
617 Text(&'a mut String),
618 /// A checkbox, on or off.
619 On(&'a mut bool),
620 /// The two buffers behind a [`FieldKind::Interval`], lower first.
621 ///
622 /// Two buffers rather than one string with a separator, which is
623 /// [`makeover_layout::Field::upper_name`]'s reason one level down: an
624 /// interval is submitted under two names, so it is edited as two values,
625 /// and a delimiter this crate owned could appear inside either of them.
626 ///
627 /// Either end may be empty while the other stands. An open end is an
628 /// answer -- "over 120 BPM" -- rather than a half-filled box.
629 ///
630 /// Added 0.33.0 with makeover-layout 0.34.0.
631 Between {
632 /// The lower end's buffer.
633 lower: &'a mut String,
634 /// The upper end's buffer.
635 upper: &'a mut String,
636 },
637 }
638
639 /// The label, marked if the field is compulsory.
640 fn label_text(field: &Field<'_>, style: &FieldStyle) -> String {
641 if field.required {
642 format!("{} {}", field.label, style.required_marker)
643 } else {
644 field.label.to_owned()
645 }
646 }
647
648 /// The four shapes a control comes in here, which is fewer than there are
649 /// kinds.
650 ///
651 /// [`FieldKind`] is `#[non_exhaustive]` and grows; this does not, because the
652 /// ways egui has of asking for a value do not. Reducing the open set to this
653 /// closed one in one total function is what keeps a new kind from needing a new
654 /// arm at every match below.
655 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
656 enum Control {
657 /// Typed into, so it is drawn as a well: the user looks into it.
658 Typed,
659 /// Picked from a control that shows one option at a time. Pressed rather
660 /// than looked into, so egui's own control painting stands.
661 Chosen,
662 /// Picked from options that are all on screen at once.
663 ///
664 /// Apart from [`Chosen`](Self::Chosen) because the description holds them
665 /// apart, and holding them apart is the whole content of
666 /// [`FieldKind::Radio`]: same question, and an answer the user can read
667 /// without opening anything.
668 Listed,
669 /// Held on or off.
670 Toggled,
671 /// Dragged across an extent that is on screen the whole time.
672 ///
673 /// Apart from [`Typed`](Self::Typed) for the reason
674 /// [`FieldKind::Range`] is apart from `Number`: the two ends are what the
675 /// question means, so a well with a figure in it is not a quieter version
676 /// of this control, it is a different one.
677 Slid,
678 /// Picked from a list of themes that arrives grouped and marked.
679 ///
680 /// Apart from [`Chosen`](Self::Chosen) rather than folded into it, and the
681 /// distinction is the same one [`Listed`](Self::Listed) draws: it is not a
682 /// different question, it is a different amount of structure on screen. A
683 /// theme picker's rows carry a group heading and a contrast mark, and both
684 /// come from members [`Field::options`] does not have, so a shared arm
685 /// would be a `matches!` on the kind inside the loop rather than one arm
686 /// less.
687 ///
688 /// Added with makeover-layout 0.38.0's [`FieldKind::Theme`].
689 Themed,
690 /// Two values dragged across one axis, drawn as one question.
691 ///
692 /// Apart from [`Typed`](Self::Typed) for the reason
693 /// [`FieldKind::Interval`] is apart from `Number`: two wells one under the
694 /// other are two questions on screen, whatever the description says, and
695 /// the arrangement is the whole content of the kind.
696 Spanned,
697 }
698
699 /// Which shape a kind takes.
700 ///
701 /// The wildcard falls to [`Control::Typed`] on purpose: a kind added to the
702 /// description since this renderer was built degrades to a text box, which
703 /// accepts any value the others would, rather than to nothing drawn at all.
704 ///
705 /// `FieldKind::File` lands there as of makeover-layout 0.11.0, and it is left
706 /// there rather than grown a shape of its own. egui's honest answer is a button
707 /// that opens a native picker, which is a fifth control and a file-dialog
708 /// dependency; no consumer of this crate asks for a file field yet. Same
709 /// position this crate took on `Meter` at 0.10.0: the membership test is that
710 /// every renderer *could* answer honestly, not that each one does on the day.
711 /// A path in a text box is not nothing, and it is what an app that needs this
712 /// tomorrow gets today.
713 ///
714 /// makeover-layout 0.31.0 added `Field::accept` and `Field::multiple`, and this
715 /// position is what they land on: both are the picker's arguments, and this
716 /// renderer has no picker to give them to. They are not lost — the description
717 /// still carries them, and the day the native dialog arrives here it is opened
718 /// with them rather than with a filter written twice.
719 ///
720 /// `FieldKind::Date` and `FieldKind::DateTime` land there too, as of
721 /// makeover-layout 0.15.0, on the same footing and with one thing owed. A
722 /// calendar is a sixth control and bare `egui` has none, so a typed value is
723 /// the honest answer here; what the app gets is the format the description
724 /// names, `makeover_layout::DATE_FORMAT` and `DATETIME_FORMAT`, which is why
725 /// those are constants rather than a sentence. audiofiles is the only consumer
726 /// of this crate and asks for neither today. A calendar popup is the upgrade
727 /// whenever one does.
728 ///
729 /// `Field::as_instant` (makeover-layout 0.37.0) is carried and not honoured, on
730 /// the same footing. It asks for the typed wall-clock value to be submitted as
731 /// the moment it names, and this renderer has no submission to convert on: it
732 /// draws the control and the app reads the value back, so the conversion would
733 /// belong wherever that read happens rather than here. What the app gets is the
734 /// local value in `DATETIME_FORMAT`, which is what it got before the member
735 /// existed. No described site on this host asks for it today.
736 /// One row of a closed chooser, as the single string it has room for.
737 ///
738 /// A combo hides its list, so everything an option carries has to travel with
739 /// the row it belongs to: there is no second line to put a detail on and no
740 /// space beside the row to put a reason in. That is the same constraint a
741 /// `<select>`'s option has in the webview, and it takes the same answer.
742 ///
743 /// The order is what the option *is* before why it cannot be picked, which is
744 /// the order the two read in and the order the radio group draws them in.
745 fn combo_row(opt: &Choice<'_>) -> String {
746 let mut text = opt.label.to_owned();
747 for extra in [opt.detail, opt.unavailable].into_iter().flatten() {
748 text.push_str(" ");
749 text.push_str(extra);
750 }
751 text
752 }
753
754 /// How far an option's second line is inset, in points.
755 ///
756 /// makeover-layout 0.39.0. The width of egui's radio button plus the gap after
757 /// it, so the line starts under the label rather than under the control. A
758 /// magnitude, which is `makeover-geometry`'s subject and not this crate's --
759 /// but this one is measured off a widget egui draws and sizes, so there is
760 /// nothing for a spacing scale to say about it.
761 const OPTION_DETAIL_INDENT: f32 = 22.0;
762
763 const fn control_shape(kind: FieldKind) -> Control {
764 match kind {
765 FieldKind::Select => Control::Chosen,
766 FieldKind::Radio => Control::Listed,
767 FieldKind::Checkbox => Control::Toggled,
768 FieldKind::Range => Control::Slid,
769 FieldKind::Interval => Control::Spanned,
770 FieldKind::Theme => Control::Themed,
771 _ => Control::Typed,
772 }
773 }
774
775 /// The shape the field actually gets, which is the kind's unless the field is
776 /// missing what that shape needs.
777 ///
778 /// One case, and `makeover-layout` names it: a [`FieldKind::Range`] carries its
779 /// extent in [`Field::min`] and [`Field::max`], and a range missing an end has
780 /// nothing to slide across. egui's `Slider` demands a `RangeInclusive`, so
781 /// inventing one would be this renderer picking bounds the app never stated and
782 /// the user then dragging against them.
783 ///
784 /// It falls back to [`Control::Typed`], which is where every kind this renderer
785 /// cannot draw natively already lands: a number in a well is a true report of
786 /// the value and takes any answer the slider would.
787 fn shape_of(field: &Field<'_>) -> Control {
788 match control_shape(field.kind) {
789 Control::Slid if !field.bounded() => Control::Typed,
790 shape => shape,
791 }
792 }
793
794 /// The unit to draw beside this field's value, if there is one to draw.
795 ///
796 /// Two conditions rather than one: the field has to carry a unit and its kind
797 /// has to be one that means anything by it. `FieldKind::measurable` is the
798 /// description answering the second, so this renderer does not keep its own
799 /// list of which kinds are quantities -- which is the drift that predicate
800 /// exists to stop.
801 fn unit_of<'a>(field: &Field<'a>) -> Option<&'a str> {
802 field.unit.filter(|_| field.kind.measurable())
803 }
804
805 /// The two ends of a range, as egui wants them.
806 ///
807 /// `None` when either end is missing or is not a number this host can read.
808 /// The description carries the bounds as text on purpose — the bound of a date
809 /// is a date — so parsing them is the renderer's job and failing to is a real
810 /// outcome rather than an assertion.
811 fn extent(field: &Field<'_>) -> Option<RangeInclusive<f64>> {
812 let min = field.min?.parse::<f64>().ok()?;
813 let max = field.max?.parse::<f64>().ok()?;
814 Some(min..=max)
815 }
816
817 /// How many decimals to write a dragged value back with.
818 ///
819 /// Read off [`Field::step`], which is the only thing that says what
820 /// granularity the question has: a step of `0.01` is a two-decimal question and
821 /// a step of `1` is a whole-number one. Without a step the host's own
822 /// granularity stands, and egui's is continuous, so the value is written back
823 /// at whatever precision it round-trips at.
824 fn decimals(step: Option<&str>) -> Option<usize> {
825 let step = step?;
826 Some(match step.split_once('.') {
827 Some((_, fraction)) => fraction.trim_end_matches('0').len(),
828 None => 0,
829 })
830 }
831
832 /// What a select shows for the value it currently holds.
833 ///
834 /// A value no option carries stays on screen as itself rather than reading as
835 /// whichever option happens to be first. goingson saved a backup retention of
836 /// 10 against a 1/3/7/14/0 list and the browser silently showed it as 1, so the
837 /// next save wrote a value nobody chose; `makeover-webview` grew the fix as a
838 /// stray `<option>` and this is the same fix in the shape egui allows.
839 ///
840 /// The empty value is the one case that reads as unanswered rather than as an
841 /// answer, and [`chosen_text`] is what puts the field's ghost text there.
842 fn shown_label<'a>(options: &'a [Choice<'a>], value: &'a str) -> &'a str {
843 options
844 .iter()
845 .find(|opt| opt.value == value)
846 .map_or(value, |opt| opt.label)
847 }
848
849 /// What a select's closed control reads, and in which tone.
850 ///
851 /// A chooser with nothing chosen showed an empty box: `shown_label` falls back
852 /// to the value, and the unanswered value is the empty string. So an app with
853 /// an instruction to give — audiofiles' "Select device..." — had nowhere to put
854 /// it but a disabled button elsewhere on the screen, which is the affordance
855 /// this vocabulary keeps moving messages *off*.
856 ///
857 /// [`Field::placeholder`] is already the description's word for "what the field
858 /// reads while it is empty" and was honoured by the typed kinds alone, so
859 /// nothing new is said here; the renderer is what had not caught up. Muted
860 /// because it is not an answer, the same tone the typed kinds' ghost text takes
861 /// three lines up.
862 ///
863 /// A value no option carries but that is *not* empty stays as itself, in
864 /// `content`: that is the goingson retention bug and it is a wrong answer
865 /// rather than an absent one.
866 ///
867 /// Returns the words and the tone rather than a built [`RichText`], because
868 /// what it decides is both of them and only one of them is readable back off a
869 /// `RichText`.
870 ///
871 /// [`Field::placeholder`]: makeover_layout::Field::placeholder
872 fn chosen_text<'a>(field: &'a Field<'a>, value: &'a str, palette: &Palette) -> (&'a str, Color32) {
873 match field.placeholder {
874 Some(ghost) if value.is_empty() => (ghost, palette.content_muted),
875 _ => (shown_label(field.options, value), palette.content),
876 }
877 }
878
879 /// What one option in a choice field is drawn in.
880 ///
881 /// The chosen one is the emphasised thing and takes `content`; the rest take
882 /// [`content_secondary`](Palette::content_secondary), because an option that is
883 /// not chosen is still an option and pressing it chooses it. Muted would be the
884 /// lie: [`State::Disabled`] resolves to it, so a five-option field read as one
885 /// live row and four dead ones. `makeover-tui` draws it the same way
886 /// (`makeover-tui@230bf63`); wiki `three-tone-convention` is the table.
887 fn option_color(value: &str, option: &str, palette: &Palette) -> Color32 {
888 if value == option {
889 palette.content
890 } else {
891 palette.content_secondary
892 }
893 }
894
895 /// Which end of an interval a box is.
896 ///
897 /// Named rather than a bool, because what it selects is not a side but a
898 /// fallback: an empty end reads as the bound it stands for, and which bound
899 /// that is depends on the end.
900 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
901 enum Bound {
902 /// The lower end, falling back to the start of the extent.
903 Low,
904 /// The upper end, falling back to its end.
905 High,
906 }
907
908 /// The facts an interval's two boxes share.
909 ///
910 /// One struct because they are one axis: [`Field::min`], [`Field::max`],
911 /// [`Field::step`] and [`Field::unit`] describe the question rather than either
912 /// end of it, so reading them once is what stops the two boxes drifting apart.
913 struct Axis<'a> {
914 /// The extent both ends are dragged inside, when it is one this host can
915 /// read.
916 extent: Option<RangeInclusive<f64>>,
917 /// The granularity, as the description writes it.
918 step: Option<&'a str>,
919 /// What the axis is measured in.
920 unit: Option<&'a str>,
921 }
922
923 impl Axis<'_> {
924 /// What an empty end reads as: the bound it stands for.
925 ///
926 /// Zero with no extent to fall back on. That is the one number this
927 /// renderer invents, and it invents it where the description declined to
928 /// say anything: an unbounded interval has no edge for the end to sit on,
929 /// and a drag box has to start somewhere.
930 fn edge(&self, which: Bound) -> f64 {
931 self.extent.as_ref().map_or(0.0, |extent| match which {
932 Bound::Low => *extent.start(),
933 Bound::High => *extent.end(),
934 })
935 }
936
937 /// One end of the interval, as a drag box.
938 ///
939 /// # An empty end reads as its bound
940 ///
941 /// Which is what the shipped control did before it was described: an unset
942 /// minimum sits on the low edge and stores no filter. egui's `DragValue`
943 /// holds a number and has no empty state to offer, so the alternative was a
944 /// text box, and that would cost the app a control on the way into being
945 /// described.
946 ///
947 /// With no extent to fall back on, an empty end reads zero. That is the one
948 /// number this renderer invents, and it invents it where the description
949 /// declined to say anything: an unbounded interval has no edge for the end
950 /// to sit on, and a drag box has to start somewhere.
951 ///
952 /// Nothing is written back until the user drags, so a value the app put
953 /// there survives being looked at -- the same guarantee the slider makes.
954 fn end(&self, ui: &mut Ui, value: &mut String, which: Bound) -> Response {
955 let mut number = value.parse::<f64>().unwrap_or(self.edge(which));
956 let mut drag = DragValue::new(&mut number);
957 if let Some(extent) = self.extent.clone() {
958 drag = drag.range(extent);
959 }
960 if let Some(places) = decimals(self.step) {
961 drag = drag.max_decimals(places);
962 }
963 if let Some(step) = self.step.and_then(|s| s.parse::<f64>().ok()) {
964 drag = drag.speed(step);
965 }
966 // Inside the control, beside the readout, which is where `Field::unit`
967 // was decided to belong and where these boxes already put it.
968 if let Some(unit) = self.unit {
969 drag = drag.suffix(format!(" {unit}"));
970 }
971 let response = ui.add(drag);
972 if response.changed() {
973 *value = match decimals(self.step) {
974 Some(places) => format!("{number:.places$}"),
975 None => number.to_string(),
976 };
977 }
978 response
979 }
980 }
981
982 /// The control alone, without its label, hint or error.
983 fn control(
984 ui: &mut Ui,
985 field: &Field<'_>,
986 filling: Filling<'_>,
987 palette: &Palette,
988 style: &FieldStyle,
989 named_by: Option<egui::Id>,
990 ) -> Response {
991 // The mismatch path: described as one thing and filled as another. Nothing
992 // here can fix it, so it is drawn as the empty, inert version of what was
993 // described — visible on screen, in the way an empty select is at the
994 // webview renderer, rather than reported in a log nobody reads.
995 let mut discard = String::new();
996 // The interval's second scratch buffer. Two ends means the mismatch path
997 // needs two places to write nothing to.
998 let mut spare = String::new();
999 let mut off = false;
1000
1001 match shape_of(field) {
1002 Control::Slid => {
1003 let value = match filling {
1004 Filling::Text(text) => text,
1005 _ => &mut discard,
1006 };
1007 // `shape_of` has already refused an unbounded range, so the extent
1008 // is only missing here if a bound is not a number — a date range,
1009 // say, which this control cannot draw either.
1010 let Some(extent) = extent(field) else {
1011 return ui.label(RichText::new(value.as_str()).color(palette.content));
1012 };
1013
1014 // A value the host cannot read starts at the low end rather than at
1015 // zero, which may be outside the extent entirely. Nothing is
1016 // written back until the user drags, so an unreadable value the app
1017 // put there survives being looked at.
1018 let mut number = value.parse::<f64>().unwrap_or(*extent.start());
1019 // The granularity is the curve's as of makeover-layout 0.32.0. It
1020 // is still in the value's own units, so the display precision is
1021 // read off it exactly as before.
1022 let step = field.curve.step();
1023 let mut slider = Slider::new(&mut number, extent.clone()).text("");
1024 if let Some(places) = decimals(step) {
1025 slider = slider.max_decimals(places);
1026 }
1027 if let Some(step) = step.and_then(|s| s.parse::<f64>().ok()) {
1028 slider = slider.step_by(step);
1029 }
1030 // egui's own constant-ratio track, which is this host's answer to
1031 // `Curve::Logarithmic`. `is_ratio` rather than a match on the
1032 // variant, because a ratio across zero is not one: makeover-layout
1033 // decides the fallback so that four renderers cannot disagree about
1034 // when it applies.
1035 if field.curve.is_ratio(*extent.start(), *extent.end()) {
1036 slider = slider.logarithmic(true);
1037 }
1038 // The unit goes inside the control, beside the readout egui already
1039 // draws. That placement is the argument `Field::unit` was decided
1040 // on: it is where these controls put it before they were described,
1041 // and it is the one a label could never reach.
1042 if let Some(unit) = unit_of(field) {
1043 slider = slider.suffix(format!(" {unit}"));
1044 }
1045 let response = ui.add(slider);
1046 if response.changed() {
1047 *value = match decimals(step) {
1048 Some(places) => format!("{number:.places$}"),
1049 None => number.to_string(),
1050 };
1051 }
1052 response
1053 }
1054 // One question, so one row. Two wells stacked would be two questions on
1055 // screen whatever the description said, which is the reading
1056 // `FieldKind::Interval` exists to prevent.
1057 //
1058 // Dragged rather than typed, because that is what these controls
1059 // already were: audiofiles' six filter axes are `DragValue` pairs with
1060 // a shared extent, a speed and a suffix, and a port that turned them
1061 // into text boxes would be a description costing the app a control.
1062 Control::Spanned => {
1063 let (lower, upper) = match filling {
1064 Filling::Between { lower, upper } => (lower, upper),
1065 _ => (&mut discard, &mut spare),
1066 };
1067 let axis = Axis {
1068 extent: extent(field),
1069 step: field.step,
1070 unit: unit_of(field),
1071 };
1072 ui.horizontal(|ui| {
1073 let low = axis.end(ui, lower, Bound::Low);
1074 // The word rather than a dash. A dash between two numbers is a
1075 // minus sign on a signed axis, and audiofiles filters loudness
1076 // in dBFS.
1077 ui.label(RichText::new("to").color(palette.content_secondary));
1078 let high = axis.end(ui, upper, Bound::High);
1079 // Both ends, by name. A union response carries the first id, so
1080 // labelling the union outside this arm names the lower box and
1081 // leaves the upper one announced as whatever number is in it --
1082 // which is how an interval half-kept the fix that gave every
1083 // other shape its question.
1084 if let Some(id) = named_by {
1085 low.clone().labelled_by(id);
1086 high.clone().labelled_by(id);
1087 }
1088 low | high
1089 })
1090 .inner
1091 }
1092 Control::Typed => {
1093 let text = match filling {
1094 Filling::Text(text) => text,
1095 _ => &mut discard,
1096 };
1097 // An empty frame and no margin: the well is this crate's, and egui's
1098 // own control background and padding would sit underneath it saying
1099 // something different about both.
1100 // Keyed on the description's own `multiline` and not on the
1101 // member: a markdown field is several lines by definition, and a
1102 // single-line edit would be a control the value cannot fit in. egui
1103 // does nothing else with the markdown, which is the honest answer
1104 // rather than a gap -- the source is text, and editing it as text
1105 // loses none of it.
1106 let mut edit = if field.kind.multiline() {
1107 TextEdit::multiline(text)
1108 } else {
1109 TextEdit::singleline(text)
1110 }
1111 .frame(egui::Frame::NONE)
1112 .margin(Margin::ZERO)
1113 .text_color(palette.content)
1114 .password(field.kind.confidential());
1115 if let Some(ghost) = field.placeholder {
1116 edit = edit.hint_text(RichText::new(ghost).color(palette.content_muted));
1117 }
1118 let response = frame(ui, Depth::Well, palette, style.frame, |ui| ui.add(edit));
1119 // A typed number has no readout of its own to sit beside, so the
1120 // unit follows the box. Muted, because it is a fact about the value
1121 // rather than a second thing to read.
1122 match unit_of(field) {
1123 Some(unit) => {
1124 ui.label(RichText::new(unit).color(palette.content_muted));
1125 response
1126 }
1127 None => response,
1128 }
1129 }
1130 Control::Toggled => {
1131 let on = match filling {
1132 Filling::On(on) => on,
1133 _ => &mut off,
1134 };
1135 ui.checkbox(on, RichText::new(field.label).color(palette.content))
1136 }
1137 Control::Listed => {
1138 let value = match filling {
1139 Filling::Text(text) => text,
1140 _ => &mut discard,
1141 };
1142 // No `shown_label` counterpart, and none is needed: a value no
1143 // option carries leaves every button unfilled, which is already
1144 // the honest report on screen. The select needs the fix because it
1145 // has one slot and must put *something* in it.
1146 let group = ui.vertical(|ui| {
1147 let mut answered: Option<Response> = None;
1148 for opt in field.options {
1149 // An option that cannot be picked yet is drawn and does not
1150 // answer, with the precondition beside it rather than
1151 // behind a hover: a greyed row with no reason reads as a
1152 // dead end, which is the state `Choice::unavailable` exists
1153 // to stop being sayable.
1154 let picked = if let Some(reason) = opt.unavailable {
1155 ui.horizontal(|ui| {
1156 let picked = ui
1157 .add_enabled_ui(false, |ui| {
1158 ui.radio_value(
1159 value,
1160 opt.value.to_owned(),
1161 RichText::new(opt.label).color(palette.content_muted),
1162 )
1163 })
1164 .inner;
1165 ui.label(RichText::new(reason).color(palette.content_muted));
1166 picked
1167 })
1168 .inner
1169 } else {
1170 ui.radio_value(
1171 value,
1172 opt.value.to_owned(),
1173 RichText::new(opt.label).color(option_color(value, opt.value, palette)),
1174 )
1175 };
1176 // What picking it means, under the option rather than
1177 // beside it. makeover-layout 0.39.0, and the placement is
1178 // the difference from the reason above: a precondition is
1179 // short enough to sit on the line, and a sentence saying
1180 // what a tier is would push every option's control out of
1181 // line with its neighbours.
1182 //
1183 // Indented past the radio, so it reads as belonging to the
1184 // option above rather than as a label of its own. Muted,
1185 // the same reading `.form-option-detail` takes in the
1186 // webview: the line orients the label, it does not compete
1187 // with it.
1188 if let Some(detail) = opt.detail {
1189 ui.horizontal(|ui| {
1190 ui.add_space(OPTION_DETAIL_INDENT);
1191 ui.label(RichText::new(detail).color(palette.content_muted));
1192 });
1193 }
1194 answered = Some(match answered {
1195 Some(prev) => prev.union(picked),
1196 None => picked,
1197 });
1198 }
1199 answered
1200 });
1201 // A group described with no options answers as its own empty area
1202 // rather than as no response at all, which keeps the caller's
1203 // `.changed()` chain working on a field whose option list has not
1204 // loaded yet.
1205 group.inner.unwrap_or(group.response)
1206 }
1207 Control::Chosen => {
1208 let value = match filling {
1209 Filling::Text(text) => text,
1210 _ => &mut discard,
1211 };
1212 let (shown, tone) = chosen_text(field, value, palette);
1213 ComboBox::from_id_salt(field.name)
1214 .selected_text(RichText::new(shown).color(tone))
1215 .show_ui(ui, |ui| {
1216 for opt in field.options {
1217 // Same rule as the radio group: shown, inert, and
1218 // saying why. A closed control hides its list, so the
1219 // reason has to travel with the row it belongs to.
1220 // A closed control hides its list, so everything an
1221 // option carries has to travel with the row it belongs
1222 // to. That is why both extra strings run into the text
1223 // here and neither does in the group above: a combo
1224 // row is a row, the way a `<select>`'s option is.
1225 let text = combo_row(opt);
1226 if opt.unavailable.is_some() {
1227 ui.add_enabled_ui(false, |ui| {
1228 ui.selectable_value(
1229 value,
1230 opt.value.to_owned(),
1231 RichText::new(text).color(palette.content_muted),
1232 );
1233 });
1234 continue;
1235 }
1236 ui.selectable_value(
1237 value,
1238 opt.value.to_owned(),
1239 RichText::new(text).color(option_color(value, opt.value, palette)),
1240 );
1241 }
1242 })
1243 .response
1244 }
1245 // The grouping comes out of the order rather than out of a group list:
1246 // `Field::themes` arrives sorted by variant, so the run of one variant
1247 // is the group and a heading opens whenever the variant changes. Same
1248 // walk as `makeover-webview`'s `<optgroup>` emission, which is what
1249 // keeps two renderers from disagreeing about where a group starts.
1250 Control::Themed => {
1251 let value = match filling {
1252 Filling::Text(text) => text,
1253 _ => &mut discard,
1254 };
1255 let shown = themed_text(field, value);
1256 ComboBox::from_id_salt(field.name)
1257 .selected_text(RichText::new(shown).color(palette.content))
1258 .show_ui(ui, |ui| {
1259 if let Some(follow) = field.follows {
1260 // First and outside every heading. It names no theme
1261 // and sits in no variant, so a heading over it would be
1262 // inventing a fourth variant for one row.
1263 ui.selectable_value(
1264 value,
1265 follow.value.to_owned(),
1266 RichText::new(follow.label).color(option_color(
1267 value,
1268 follow.value,
1269 palette,
1270 )),
1271 );
1272 }
1273 let mut open: Option<ThemeVariant> = None;
1274 for theme in field.themes {
1275 if open != Some(theme.variant) {
1276 // A heading rather than a `selectable_value`: it is
1277 // not pickable, and egui has no inert row that
1278 // still reads as a row. `content_muted` is the tone
1279 // for something that is not an answer, which is the
1280 // ghost text's tone eight lines up.
1281 if open.is_some() {
1282 ui.separator();
1283 }
1284 ui.label(
1285 RichText::new(theme.variant.heading()).color(palette.content_muted),
1286 );
1287 open = Some(theme.variant);
1288 }
1289 ui.selectable_value(
1290 value,
1291 theme.id.to_owned(),
1292 RichText::new(format!("{} {}", theme.name, theme.contrast.badge()))
1293 .color(option_color(value, theme.id, palette)),
1294 );
1295 }
1296 })
1297 .response
1298 }
1299 }
1300 }
1301
1302 /// What a theme picker's closed control reads.
1303 ///
1304 /// [`chosen_text`]'s counterpart, and it is separate for the reason
1305 /// [`Control::Themed`] is: the label lives on a [`makeover_layout::ThemeChoice`]
1306 /// rather than on a [`Choice`], and the follow row is a third place to look.
1307 ///
1308 /// No placeholder arm. A theme picker is never unanswered in the way a select
1309 /// is — an app that resolved a theme to paint this control with has one — and
1310 /// falling back to the raw value is the honest report on a stored id whose
1311 /// theme has since been deleted.
1312 fn themed_text<'a>(field: &'a Field<'a>, value: &'a str) -> &'a str {
1313 if let Some(follow) = field.follows
1314 && follow.value == value
1315 {
1316 return follow.label;
1317 }
1318 field
1319 .themes
1320 .iter()
1321 .find(|theme| theme.id == value)
1322 .map_or(value, |theme| theme.name)
1323 }
1324
1325 /// One field, as the column the app drops into its form.
1326 ///
1327 /// The anatomy is `makeover-webview`'s, so the two renderers put a form
1328 /// together the same way: label, control, hint, error, top to bottom, with a
1329 /// checkbox labelling itself instead of taking a label above.
1330 ///
1331 /// Returns [`None`] for a [`FieldKind::Hidden`] field, which is what
1332 /// [`FieldKind::visible`] means and is the honest answer here: a webview still
1333 /// emits an input for it because the form submits, and an immediate-mode
1334 /// renderer has no form and no submission, so a hidden field is a value the app
1335 /// already holds and there is nothing to draw or to respond to.
1336 ///
1337 /// `state` is the description's interaction axis.
1338 /// [`State::Disabled`] greys the field and stops it answering, through
1339 /// [`State::suppresses_interaction`] rather than through a second reading of
1340 /// what disabled means. Focus is not on that axis and never reaches here: egui
1341 /// owns reach, focus and the ring for this renderer, and one ring means not a
1342 /// second one per renderer that happens to have opinions.
1343 pub fn field(
1344 ui: &mut Ui,
1345 field: &Field<'_>,
1346 filling: Filling<'_>,
1347 state: Option<State>,
1348 palette: &Palette,
1349 style: &FieldStyle,
1350 ) -> Option<Response> {
1351 if !field.kind.visible() {
1352 return None;
1353 }
1354 let enabled = !state.is_some_and(State::suppresses_interaction);
1355 let text = if enabled {
1356 palette.content
1357 } else {
1358 palette.content_muted
1359 };
1360
1361 let response = ui
1362 .vertical(|ui| {
1363 ui.spacing_mut().item_spacing.y = style.gap;
1364
1365 // A checkbox labels itself, on the right of the box.
1366 // `FieldKind::labels_itself` is the description saying so, and both
1367 // webview apps special-cased it inline before it did.
1368 let named_by = (!field.kind.labels_itself())
1369 .then(|| ui.label(RichText::new(label_text(field, style)).color(text)));
1370
1371 let response = ui
1372 .add_enabled_ui(enabled, |ui| {
1373 control(
1374 ui,
1375 field,
1376 filling,
1377 palette,
1378 style,
1379 named_by.as_ref().map(|l| l.id),
1380 )
1381 })
1382 .inner;
1383
1384 // The label, attached rather than merely adjacent.
1385 //
1386 // Drawing it above the control and stopping there is what this did
1387 // until 2026-08-22, and it put an unnamed box in the accessibility
1388 // tree with some text near it: a screen reader announced a text
1389 // field with no question, and a prefilled one announced its own
1390 // contents instead. audiofiles' four name modals were the site that
1391 // measured it, through a harness reading what the panel drew.
1392 //
1393 // Worth stating why it was worth fixing here rather than in each
1394 // app: `Field::label` is a member the description carries so a
1395 // renderer does not have to guess, `makeover-webview` has always
1396 // named it in `aria-describedby`, and the two renderers disagreeing
1397 // about a fact the description states is the one thing this layer
1398 // exists to prevent. A checkbox is unaffected -- egui names one from
1399 // its own text, which is what `labels_itself` already says.
1400 let response = match named_by {
1401 Some(label) => response.labelled_by(label.id),
1402 None => response,
1403 };
1404
1405 // Standing help, then what the answer costs, then what is wrong
1406 // now. All three, in that order, for the reason the webview
1407 // renderer names all three in `aria-describedby`: an error
1408 // appearing must not take the hint away with it. This host has the
1409 // room, so unlike makeover-tui it never has to choose -- the
1410 // precedence rule on `Field::note` is for the renderer that does.
1411 if let Some(hint) = field.hint {
1412 ui.label(RichText::new(hint).color(palette.content_muted));
1413 }
1414 // The note carries its own tone, and `Palette::tone` is what
1415 // resolves it, so a Neutral note is ordinary content rather than
1416 // a colour this renderer picked.
1417 if let Some((tone, note)) = field.note {
1418 ui.label(RichText::new(note).color(palette.tone(tone)));
1419 }
1420 if let Some(error) = field.error {
1421 ui.label(RichText::new(error).color(palette.danger));
1422 }
1423 response
1424 })
1425 .inner;
1426
1427 Some(response)
1428 }
1429
1430 /// A set of fields, laid down a column.
1431 ///
1432 /// `show_extended` is the disclosure, and it is a parameter rather than state
1433 /// held here because the disclosure belongs to the *form* and not to any field:
1434 /// [`Field::extended`] marks which fields are behind one, and the app owns
1435 /// whether it is open. That is the same division `makeover-webview` draws when
1436 /// it marks the group `data-extended` and emits no control to toggle it.
1437 ///
1438 /// `draw` is called once per field that should be visible, in order. Taking a
1439 /// callback rather than a slice of [`Filling`]s is what keeps the app's own
1440 /// values borrowed one at a time: a form's fields usually live in different
1441 /// structs, and a parallel array would have to be built each frame and kept in
1442 /// step with the description by hand.
1443 pub fn group<'a>(
1444 ui: &mut Ui,
1445 fields: &'a [Field<'a>],
1446 show_extended: bool,
1447 style: &FieldStyle,
1448 mut draw: impl FnMut(&mut Ui, &'a Field<'a>),
1449 ) {
1450 ui.vertical(|ui| {
1451 ui.spacing_mut().item_spacing.y = style.group_gap;
1452 for f in fields {
1453 if f.extended && !show_extended {
1454 continue;
1455 }
1456 draw(ui, f);
1457 }
1458 });
1459 }
1460
1461 #[cfg(test)]
1462 mod tests {
1463 use super::*;
1464
1465 fn palette(well: Color32) -> Palette {
1466 Palette {
1467 page: Color32::from_rgb(1, 1, 1),
1468 raised: Color32::from_rgb(2, 2, 2),
1469 overlay: Color32::from_rgb(3, 3, 3),
1470 well,
1471 sunken: Color32::from_rgb(4, 4, 4),
1472 bevel_light: Color32::WHITE,
1473 bevel_dark: Color32::BLACK,
1474 elevation: Color32::from_black_alpha(46),
1475 content: Color32::from_rgb(5, 5, 5),
1476 content_secondary: Color32::from_rgb(55, 55, 55),
1477 content_muted: Color32::from_rgb(6, 6, 6),
1478 action: Color32::from_rgb(7, 7, 7),
1479 danger: Color32::from_rgb(8, 8, 8),
1480 success: Color32::from_rgb(9, 9, 9),
1481 warning: Color32::from_rgb(10, 10, 10),
1482 info: Color32::from_rgb(11, 11, 11),
1483 }
1484 }
1485
1486 /// The cast is egui's own shadow type carrying the theme's tone, which is
1487 /// the whole of what this crate had to decide for it: unlike a bevel, egui
1488 /// already knows how to paint one.
1489 #[test]
1490 fn a_unit_is_drawn_only_where_the_kind_is_a_quantity() {
1491 // egui-drawing has no harness here, so what is tested is the decision
1492 // that precedes it: which fields have a unit to draw at all. The kind
1493 // half comes from the description rather than from a `matches!` in this
1494 // crate, which is the drift `FieldKind::measurable` exists to stop.
1495 let ranged = makeover_layout::Field {
1496 unit: Some("s"),
1497 ..makeover_layout::Field::range("attack", "Attack", "0", "5")
1498 };
1499 assert_eq!(unit_of(&ranged), Some("s"));
1500
1501 let typed = makeover_layout::Field {
1502 unit: Some("ms"),
1503 ..makeover_layout::Field::new(makeover_layout::FieldKind::Number, "fade", "Fade")
1504 };
1505 assert_eq!(unit_of(&typed), Some("ms"));
1506
1507 let worded = makeover_layout::Field {
1508 unit: Some("s"),
1509 ..makeover_layout::Field::new(makeover_layout::FieldKind::Text, "name", "Name")
1510 };
1511 assert_eq!(unit_of(&worded), None);
1512
1513 let bare = makeover_layout::Field::range("attack", "Attack", "0", "5");
1514 assert_eq!(unit_of(&bare), None);
1515 }
1516
1517 #[test]
1518 fn the_cast_hands_egui_the_themes_tone() {
1519 let p = palette(Color32::from_rgb(9, 9, 9));
1520 let cast = p.cast();
1521 assert_eq!(cast.color, p.elevation);
1522 assert!(cast.blur > 0, "a cast shadow is soft");
1523 assert_eq!(cast.offset, [0, 2], "it falls downward and only a little");
1524 }
1525
1526 #[test]
1527 fn a_well_resolves_to_its_own_token() {
1528 // No substitution left. The page-filled well was a stand-in for a
1529 // token that did not exist yet; it exists now.
1530 let w = Color32::from_rgb(9, 9, 9);
1531 let p = palette(w);
1532 assert_eq!(p.fill(Fill::Well), Some(w));
1533 assert_ne!(p.fill(Fill::Well), Some(p.page));
1534 }
1535
1536 #[test]
1537 fn every_intent_is_a_plain_lookup() {
1538 let p = palette(Color32::from_rgb(9, 9, 9));
1539 assert_eq!(p.fill(Fill::Page), Some(p.page));
1540 assert_eq!(p.fill(Fill::Raised), Some(p.raised));
1541 assert_eq!(p.fill(Fill::Overlay), Some(p.overlay));
1542 }
1543
1544 /// Sunken is its own colour, not the well's and not the page's. The two
1545 /// are authored in opposite directions and an earlier cut of the
1546 /// description conflated them.
1547 #[test]
1548 fn sunken_is_neither_the_well_nor_the_page() {
1549 let p = palette(Color32::from_rgb(9, 9, 9));
1550 assert_eq!(p.fill(Fill::Sunken), Some(p.sunken));
1551 assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Well));
1552 assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Page));
1553 }
1554
1555 #[test]
1556 fn a_raised_region_never_resolves_to_the_well_fill() {
1557 // The cross-app bug, asserted at the renderer boundary this time.
1558 let p = palette(Color32::from_rgb(9, 9, 9));
1559 let raised = Depth::Raised.fill().and_then(|f| p.fill(f));
1560 let well = Depth::Well.fill().and_then(|f| p.fill(f));
1561 assert_eq!(raised, Some(p.raised));
1562 assert_ne!(raised, well);
1563 }
1564
1565 #[test]
1566 fn an_overlay_is_cast_onto_the_page_and_takes_no_edge() {
1567 // makeover-layout 0.14.0 is what made this reachable. The answer was
1568 // already here at 0.10.0 and the question could not be asked.
1569 let p = palette(Color32::from_rgb(9, 9, 9));
1570 assert_eq!(
1571 Depth::Overlay.fill().and_then(|f| p.fill(f)),
1572 Some(p.overlay)
1573 );
1574 assert_eq!(Depth::Overlay.bevel(), None);
1575 // The shadow `frame` reaches for is the theme's tone rather than
1576 // egui's default, which is the whole reason `cast` exists.
1577 assert_eq!(p.cast().color, p.elevation);
1578 }
1579
1580 #[test]
1581 fn the_lit_edge_swaps_when_a_card_is_pressed() {
1582 let p = palette(Color32::from_rgb(9, 9, 9));
1583 let (tl, _) = Depth::Raised.bevel().unwrap().edges();
1584 let (ptl, _) = Depth::Raised.pressed().bevel().unwrap().edges();
1585 assert_eq!(p.edge(tl), p.bevel_light);
1586 assert_eq!(p.edge(ptl), p.bevel_dark);
1587 }
1588
1589 #[test]
1590 fn flat_asks_for_neither_fill_nor_edge() {
1591 assert!(Depth::Flat.fill().is_none());
1592 assert!(Depth::Flat.bevel().is_none());
1593 }
1594
1595 #[test]
1596 fn a_select_keeps_a_value_none_of_its_options_carries() {
1597 // The save-the-wrong-thing bug, asserted at the second renderer so it
1598 // is not re-found there. goingson's own numbers.
1599 let options = [
1600 Choice::plain("1"),
1601 Choice::plain("3"),
1602 Choice::plain("7"),
1603 Choice::plain("14"),
1604 ];
1605 assert_eq!(shown_label(&options, "10"), "10");
1606 // And a value that does match reads as its label, not as itself.
1607 let spelled = [Choice::new("7", "One week")];
1608 assert_eq!(shown_label(&spelled, "7"), "One week");
1609 }
1610
1611 #[test]
1612 fn an_unanswered_chooser_reads_its_ghost_text_and_reads_it_muted() {
1613 let p = palette(Color32::from_rgb(9, 9, 9));
1614 let options = [Choice::new("sp404", "SP-404")];
1615 let field = Field {
1616 placeholder: Some("Select device..."),
1617 ..Field::select("device", "Conform for device", &options)
1618 };
1619
1620 assert_eq!(
1621 chosen_text(&field, "", &p),
1622 ("Select device...", p.content_muted),
1623 "ghost text is not an answer, so it takes the tone the typed kinds' ghost text does"
1624 );
1625
1626 // Answered, and it is the label that reads rather than the value.
1627 assert_eq!(chosen_text(&field, "sp404", &p), ("SP-404", p.content));
1628 }
1629
1630 #[test]
1631 fn a_wrong_answer_is_not_an_absent_one() {
1632 // The retention-10 bug and the ghost text meet here: a value no option
1633 // carries still reads as itself, because the field IS answered and the
1634 // answer is wrong. Only the empty value is unanswered.
1635 let p = palette(Color32::from_rgb(9, 9, 9));
1636 let options = [Choice::plain("1"), Choice::plain("7")];
1637 let field = Field {
1638 placeholder: Some("Pick one"),
1639 ..Field::select("retention", "Keep backups for", &options)
1640 };
1641
1642 assert_eq!(chosen_text(&field, "10", &p), ("10", p.content));
1643 }
1644
1645 #[test]
1646 fn a_chooser_with_no_ghost_text_is_unchanged() {
1647 // The whole change is opt-in from the description. A field that says
1648 // nothing about its empty state still shows an empty box.
1649 let p = palette(Color32::from_rgb(9, 9, 9));
1650 let options = [Choice::plain("1")];
1651 let field = Field::select("retention", "Keep backups for", &options);
1652 assert_eq!(chosen_text(&field, "", &p), ("", p.content));
1653 }
1654
1655 #[test]
1656 fn a_range_is_slid_and_a_number_is_typed_into() {
1657 // The distinction the kind was added for, at the renderer that has to
1658 // act on it. A well with a figure in it is not a quiet slider.
1659 assert_eq!(control_shape(FieldKind::Range), Control::Slid);
1660 assert_eq!(control_shape(FieldKind::Number), Control::Typed);
1661 }
1662
1663 #[test]
1664 fn a_range_missing_an_end_falls_back_to_a_well() {
1665 // egui's `Slider` demands both ends, so inventing one would be this
1666 // renderer picking bounds the app never stated and the user then
1667 // dragging against them. A typed number takes every answer the slider
1668 // would.
1669 let whole = Field::range("review", "Review above", "0", "1");
1670 assert_eq!(shape_of(&whole), Control::Slid);
1671
1672 let half = Field {
1673 max: Some("1"),
1674 ..Field::new(FieldKind::Range, "review", "Review above")
1675 };
1676 assert_eq!(shape_of(&half), Control::Typed);
1677 assert_eq!(extent(&half), None);
1678
1679 // A bound this host cannot read is the same outcome by a different
1680 // route: the description carries bounds as text because the bound of a
1681 // date is a date.
1682 let dated = Field::range("when", "When", "2026-08-01", "2026-08-31");
1683 assert_eq!(extent(&dated), None);
1684 }
1685
1686 #[test]
1687 fn an_interval_is_its_own_shape_and_not_two_numbers() {
1688 // The distinction the kind was added for, at the renderer that has to
1689 // arrange it: two wells stacked are two questions on screen, whatever
1690 // the description says.
1691 assert_eq!(control_shape(FieldKind::Interval), Control::Spanned);
1692 assert_eq!(shape_of(&Field::interval("a", "b", "A")), Control::Spanned);
1693
1694 // Unlike a range, it owes no extent: its bounds are a rule on each end
1695 // rather than the control, so a missing one is an open end.
1696 let axis = Field {
1697 min: Some("0"),
1698 max: Some("300"),
1699 ..Field::interval("bpm_min", "bpm_max", "BPM")
1700 };
1701 assert_eq!(shape_of(&axis), Control::Spanned);
1702 }
1703
1704 #[test]
1705 fn an_empty_end_reads_as_the_bound_it_stands_for() {
1706 // Which is what the shipped control did before it was described: an
1707 // unset minimum sits on the low edge and stores no filter. `DragValue`
1708 // has no empty state, and a text box instead would cost the app a
1709 // control on the way into being described.
1710 let axis = Axis {
1711 extent: Some(0.0..=300.0),
1712 step: Some("1"),
1713 unit: Some("BPM"),
1714 };
1715 assert!((axis.edge(Bound::Low) - 0.0).abs() < f64::EPSILON);
1716 assert!((axis.edge(Bound::High) - 300.0).abs() < f64::EPSILON);
1717
1718 // With no extent there is no edge to sit on, and a drag box has to
1719 // start somewhere. The one number this renderer invents, invented where
1720 // the description declined to say anything.
1721 let open = Axis {
1722 extent: None,
1723 step: None,
1724 unit: None,
1725 };
1726 assert!((open.edge(Bound::Low) - 0.0).abs() < f64::EPSILON);
1727 assert!((open.edge(Bound::High) - 0.0).abs() < f64::EPSILON);
1728 }
1729
1730 #[test]
1731 fn the_step_decides_how_a_dragged_value_is_written_back() {
1732 // Without it a 0-to-1 threshold writes back whatever float the drag
1733 // landed on, which is the host's granularity and is what the
1734 // description says an absent step means.
1735 assert_eq!(decimals(None), None);
1736 assert_eq!(decimals(Some("1")), Some(0));
1737 assert_eq!(decimals(Some("0.01")), Some(2));
1738 // Trailing zeros are not precision: 0.10 is a one-decimal question.
1739 assert_eq!(decimals(Some("0.10")), Some(1));
1740 }
1741
1742 #[test]
1743 fn an_unavailable_option_is_drawn_muted_rather_than_dropped() {
1744 // The tone rule, at the one place it is a claim rather than a
1745 // preference: this option genuinely will not answer, so muted is the
1746 // truth. The available ones beside it keep the secondary intent.
1747 let p = palette(Color32::from_rgb(9, 9, 9));
1748 let options = [
1749 Choice::new("chromatic", "Chromatic"),
1750 Choice::new("multi", "Multi-sample").unless("Drop a second sample."),
1751 ];
1752 assert!(options[0].available());
1753 assert!(!options[1].available());
1754 assert_eq!(
1755 option_color("chromatic", options[0].value, &p),
1756 p.content,
1757 "the chosen option is the emphasised thing"
1758 );
1759 assert_eq!(
1760 option_color("chromatic", options[1].value, &p),
1761 p.content_secondary,
1762 "and `option_color` never mutes: the unavailable path is what does"
1763 );
1764 }
1765
1766 #[test]
1767 fn a_closed_chooser_carries_both_of_an_options_extra_lines_in_its_row() {
1768 // makeover-layout 0.39.0. The radio group has room for a second line
1769 // and this control does not, so the two draw the same description
1770 // differently and neither is a preference.
1771 let plain = Choice::new("24", "Small Files");
1772 assert_eq!(combo_row(&plain), "Small Files");
1773
1774 let detailed = plain.detailing("$24/mo. Fits audio, plugins, binaries.");
1775 assert_eq!(
1776 combo_row(&detailed),
1777 "Small Files $24/mo. Fits audio, plugins, binaries."
1778 );
1779
1780 // What it is, then why it cannot be picked. An option carrying both has
1781 // said two things, and the order is the one the group draws.
1782 let both = detailed.unless("Sold out.");
1783 assert_eq!(
1784 combo_row(&both),
1785 "Small Files $24/mo. Fits audio, plugins, binaries. Sold out."
1786 );
1787 assert_eq!(
1788 combo_row(&plain.unless("Sold out.")),
1789 "Small Files Sold out.",
1790 "the reason still reads the way it did before the detail existed"
1791 );
1792 }
1793
1794 #[test]
1795 fn only_a_required_field_is_marked() {
1796 let style = FieldStyle::default();
1797 let plain = Field::new(FieldKind::Text, "title", "Title");
1798 assert_eq!(label_text(&plain, &style), "Title");
1799
1800 let required = Field {
1801 required: true,
1802 ..plain
1803 };
1804 assert_eq!(label_text(&required, &style), "Title *");
1805
1806 // The marker is copy and the app owns it, which is why it is a knob.
1807 let house = FieldStyle {
1808 required_marker: "(required)",
1809 ..style
1810 };
1811 assert_eq!(label_text(&required, &house), "Title (required)");
1812 }
1813
1814 #[test]
1815 fn a_select_and_a_checkbox_are_pressed_and_everything_else_is_typed_into() {
1816 // What decides whether the control gets a well. A well is for what the
1817 // user looks into, and only one of these is.
1818 assert_eq!(control_shape(FieldKind::Select), Control::Chosen);
1819 // Not the wildcard. A theme picker falling to `Control::Typed` would
1820 // draw a text box over a resolved list, which is worse than the select
1821 // every app had before the member existed.
1822 assert_eq!(control_shape(FieldKind::Theme), Control::Themed);
1823 assert_eq!(control_shape(FieldKind::Radio), Control::Listed);
1824 assert_eq!(control_shape(FieldKind::Checkbox), Control::Toggled);
1825 for k in [
1826 FieldKind::Text,
1827 FieldKind::Secret,
1828 FieldKind::Number,
1829 FieldKind::Email,
1830 FieldKind::Url,
1831 FieldKind::Tel,
1832 FieldKind::Textarea,
1833 FieldKind::Rich,
1834 ] {
1835 assert_eq!(control_shape(k), Control::Typed, "{k:?} is typed into");
1836 }
1837 // And the two multi-line ones get a multi-line edit, which is the half
1838 // `control_shape` alone does not say: both are typed into, and only one
1839 // of the two edit shapes can hold a markdown document.
1840 assert!(FieldKind::Rich.multiline());
1841 assert!(FieldKind::Textarea.multiline());
1842 assert!(!FieldKind::Text.multiline());
1843 }
1844
1845 #[test]
1846 fn the_two_option_taking_kinds_are_drawn_differently_on_purpose() {
1847 // The description holds Select and Radio apart, and a renderer that
1848 // collapsed them would silently answer a question the app did not ask:
1849 // audiofiles' storage style is irreversible and its alternatives have
1850 // to be readable without opening anything. Asserting the two shapes
1851 // differ is asserting that distinction survives the trip.
1852 assert!(FieldKind::Select.offers_options());
1853 assert!(FieldKind::Radio.offers_options());
1854 assert_ne!(
1855 control_shape(FieldKind::Select),
1856 control_shape(FieldKind::Radio)
1857 );
1858 }
1859
1860 #[test]
1861 fn an_unchosen_option_is_secondary_and_never_muted() {
1862 let p = palette(Color32::from_rgb(4, 4, 4));
1863 assert_eq!(option_color("wav", "wav", &p), p.content);
1864 assert_eq!(option_color("wav", "aiff", &p), p.content_secondary);
1865 // The whole point of the distinction: muted is what Disabled resolves
1866 // to, so an option wearing it would claim it does not answer a press.
1867 assert_ne!(option_color("wav", "aiff", &p), p.content_muted);
1868 }
1869
1870 /// What the accessibility tree says a screen drew, as `(role, name)` pairs.
1871 ///
1872 /// egui builds this from the same `WidgetInfo` every widget already reports,
1873 /// so it is what a screen reader would be handed rather than a second
1874 /// opinion about it. A name that arrives through `labelled_by` is resolved
1875 /// the way a client resolves it: the relation names another node, and that
1876 /// node's text is the control's accessible name.
1877 fn announced(draw: impl FnMut(&mut egui::Ui)) -> Vec<(egui::accesskit::Role, String)> {
1878 let ctx = egui::Context::default();
1879 ctx.enable_accesskit();
1880 let mut draw = draw;
1881 let input = || egui::RawInput {
1882 screen_rect: Some(egui::Rect::from_min_size(
1883 egui::Pos2::ZERO,
1884 egui::vec2(800.0, 600.0),
1885 )),
1886 ..Default::default()
1887 };
1888 // Two passes: egui lays out against the previous frame, so the first
1889 // sees widgets at the wrong rect.
1890 let _ = ctx.run_ui(input(), &mut draw);
1891 let out = ctx.run_ui(input(), &mut draw);
1892
1893 let update = out
1894 .platform_output
1895 .accesskit_update
1896 .expect("accesskit is on, so a tree was built");
1897 let by_id: std::collections::HashMap<_, _> = update.nodes.iter().cloned().collect();
1898 update
1899 .nodes
1900 .iter()
1901 .map(|(_, node)| {
1902 let named = node.label().map(str::to_owned).or_else(|| {
1903 node.labelled_by()
1904 .iter()
1905 .find_map(|id| by_id.get(id))
1906 .and_then(|by| by.label().or_else(|| by.value()).map(str::to_owned))
1907 });
1908 (node.role(), named.unwrap_or_default())
1909 })
1910 .collect()
1911 }
1912
1913 #[test]
1914 fn a_fields_label_names_its_control_rather_than_sitting_beside_it() {
1915 let f = Field::new(FieldKind::Text, "name", "Vault name");
1916 let p = palette(Color32::from_rgb(9, 9, 9));
1917 let drawn = announced(|ui| {
1918 let mut text = String::new();
1919 field(
1920 ui,
1921 &f,
1922 Filling::Text(&mut text),
1923 None,
1924 &p,
1925 &FieldStyle::default(),
1926 );
1927 });
1928
1929 let box_ = drawn
1930 .iter()
1931 .find(|(role, _)| *role == egui::accesskit::Role::TextInput)
1932 .expect("a text field draws a text input");
1933 assert_eq!(
1934 box_.1, "Vault name",
1935 "the box is announced by the question rather than unnamed: {drawn:?}"
1936 );
1937 }
1938
1939 #[test]
1940 fn a_prefilled_box_is_still_announced_by_its_question() {
1941 // The sharper half. With nothing attached, a box carrying a value is
1942 // announced as that value, so a rename field read out the name it was
1943 // seeded with and never said what was being asked.
1944 let f = Field::new(FieldKind::Text, "name", "New name");
1945 let p = palette(Color32::from_rgb(9, 9, 9));
1946 let drawn = announced(|ui| {
1947 let mut text = String::from("Drums");
1948 field(
1949 ui,
1950 &f,
1951 Filling::Text(&mut text),
1952 None,
1953 &p,
1954 &FieldStyle::default(),
1955 );
1956 });
1957
1958 let box_ = drawn
1959 .iter()
1960 .find(|(role, _)| *role == egui::accesskit::Role::TextInput)
1961 .expect("a text field draws a text input");
1962 assert_eq!(box_.1, "New name", "{drawn:?}");
1963 }
1964
1965 #[test]
1966 fn both_ends_of_an_interval_are_named_by_the_one_question() {
1967 // A union response carries the first id, so labelling the pair outside
1968 // the arm named the lower box and left the upper one announced as
1969 // whatever number was in it.
1970 let f = Field::new(FieldKind::Interval, "bpm", "BPM Range");
1971 let p = palette(Color32::from_rgb(9, 9, 9));
1972 let drawn = announced(|ui| {
1973 let mut lower = String::from("90");
1974 let mut upper = String::from("300");
1975 field(
1976 ui,
1977 &f,
1978 Filling::Between {
1979 lower: &mut lower,
1980 upper: &mut upper,
1981 },
1982 None,
1983 &p,
1984 &FieldStyle::default(),
1985 );
1986 });
1987
1988 // A `SpinButton`: an interval's ends are drag values, not text boxes.
1989 let ends: Vec<_> = drawn
1990 .iter()
1991 .filter(|(role, _)| *role == egui::accesskit::Role::SpinButton)
1992 .collect();
1993 assert_eq!(ends.len(), 2, "an interval draws two boxes: {drawn:?}");
1994 for end in ends {
1995 assert_eq!(end.1, "BPM Range", "{drawn:?}");
1996 }
1997 }
1998
1999 #[test]
2000 fn a_checkbox_keeps_naming_itself() {
2001 // `FieldKind::labels_itself` routes past the label, and egui names a
2002 // checkbox from its own text, so there is nothing to attach and
2003 // attaching one would say the name twice.
2004 let f = Field::new(FieldKind::Checkbox, "loop", "Loop playback");
2005 let p = palette(Color32::from_rgb(9, 9, 9));
2006 let drawn = announced(|ui| {
2007 let mut ticked = false;
2008 field(
2009 ui,
2010 &f,
2011 Filling::On(&mut ticked),
2012 None,
2013 &p,
2014 &FieldStyle::default(),
2015 );
2016 });
2017
2018 assert!(
2019 drawn
2020 .iter()
2021 .any(|(role, name)| *role == egui::accesskit::Role::CheckBox
2022 && name == "Loop playback"),
2023 "{drawn:?}"
2024 );
2025 }
2026
2027 #[test]
2028 fn a_hidden_field_draws_nothing_and_answers_nothing() {
2029 // Where the two renderers legitimately part: a webview still emits an
2030 // input because the form submits, and there is no form here.
2031 let f = Field::new(FieldKind::Hidden, "id", "Id");
2032 let p = palette(Color32::from_rgb(9, 9, 9));
2033 egui::__run_test_ui(|ui| {
2034 let drawn = field(ui, &f, Filling::Absent, None, &p, &FieldStyle::default());
2035 assert!(drawn.is_none());
2036 });
2037 }
2038
2039 #[test]
2040 fn a_disabled_field_stops_answering_and_an_unstated_one_does_not() {
2041 let f = Field::new(FieldKind::Text, "title", "Title");
2042 let p = palette(Color32::from_rgb(9, 9, 9));
2043 let style = FieldStyle::default();
2044 egui::__run_test_ui(|ui| {
2045 let mut text = String::from("x");
2046 let disabled = field(
2047 ui,
2048 &f,
2049 Filling::Text(&mut text),
2050 Some(State::Disabled),
2051 &p,
2052 &style,
2053 )
2054 .unwrap();
2055 assert!(!disabled.enabled());
2056
2057 // Stating no state is the ordinary case and answers. Focus used to
2058 // be the counter-example here; it is egui's now and a description
2059 // cannot state it at all.
2060 let mut text = String::from("x");
2061 let plain = field(ui, &f, Filling::Text(&mut text), None, &p, &style).unwrap();
2062 assert!(plain.enabled(), "an unstated field still answers");
2063 });
2064 }
2065
2066 #[test]
2067 fn a_field_described_one_way_and_filled_another_is_drawn_inert() {
2068 // No panic and no write-through. A checkbox handed a string cannot be
2069 // filled, so it is drawn off and left alone.
2070 let f = Field::new(FieldKind::Checkbox, "done", "Done");
2071 let p = palette(Color32::from_rgb(9, 9, 9));
2072 let mut text = String::from("untouched");
2073 egui::__run_test_ui(|ui| {
2074 let drawn = field(
2075 ui,
2076 &f,
2077 Filling::Text(&mut text),
2078 None,
2079 &p,
2080 &FieldStyle::default(),
2081 );
2082 assert!(drawn.is_some());
2083 });
2084 assert_eq!(text, "untouched");
2085 }
2086
2087 #[test]
2088 fn the_disclosure_belongs_to_the_form_and_not_to_the_field() {
2089 let fields = [
2090 Field::new(FieldKind::Text, "title", "Title"),
2091 Field {
2092 extended: true,
2093 ..Field::new(FieldKind::Text, "notes", "Notes")
2094 },
2095 ];
2096 let style = FieldStyle::default();
2097
2098 let mut closed = Vec::new();
2099 egui::__run_test_ui(|ui| {
2100 group(ui, &fields, false, &style, |_, f| closed.push(f.name));
2101 });
2102 assert_eq!(closed, ["title"]);
2103
2104 let mut open = Vec::new();
2105 egui::__run_test_ui(|ui| {
2106 group(ui, &fields, true, &style, |_, f| open.push(f.name));
2107 });
2108 assert_eq!(open, ["title", "notes"]);
2109 }
2110
2111 #[test]
2112 fn the_default_frame_is_square_and_one_point() {
2113 let d = FrameStyle::default();
2114 assert_eq!(d.radius, CornerRadius::ZERO);
2115 assert_eq!(d.margin, Margin::ZERO);
2116 assert!((d.stroke - 1.0).abs() < f32::EPSILON);
2117 }
2118
2119 #[test]
2120 fn a_theme_picker_reads_its_chosen_theme_by_name() {
2121 const THEMES: &[makeover_layout::ThemeChoice<'_>] = &[makeover_layout::ThemeChoice::new(
2122 "carbonfox",
2123 "Carbonfox",
2124 ThemeVariant::Dark,
2125 makeover_layout::Contrast::High,
2126 )];
2127 let field = Field::theme("theme", "Theme", THEMES)
2128 .following(Choice::new("system", "Follow System"));
2129
2130 assert_eq!(themed_text(&field, "carbonfox"), "Carbonfox");
2131 assert_eq!(themed_text(&field, "system"), "Follow System");
2132 // A stored id whose theme has been deleted reads as itself rather than
2133 // as an empty box, which is the honest report on the config as it
2134 // stands.
2135 assert_eq!(themed_text(&field, "gone"), "gone");
2136 }
2137 }
2138