Skip to main content

max / makeover-immediate

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