Skip to main content

max / makeover-immediate

83.6 KB · 1940 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 ///
710 /// `Field::as_instant` (makeover-layout 0.37.0) is carried and not honoured, on
711 /// the same footing. It asks for the typed wall-clock value to be submitted as
712 /// the moment it names, and this renderer has no submission to convert on: it
713 /// draws the control and the app reads the value back, so the conversion would
714 /// belong wherever that read happens rather than here. What the app gets is the
715 /// local value in `DATETIME_FORMAT`, which is what it got before the member
716 /// existed. No described site on this host asks for it today.
717 const fn control_shape(kind: FieldKind) -> Control {
718 match kind {
719 FieldKind::Select => Control::Chosen,
720 FieldKind::Radio => Control::Listed,
721 FieldKind::Checkbox => Control::Toggled,
722 FieldKind::Range => Control::Slid,
723 FieldKind::Interval => Control::Spanned,
724 _ => Control::Typed,
725 }
726 }
727
728 /// The shape the field actually gets, which is the kind's unless the field is
729 /// missing what that shape needs.
730 ///
731 /// One case, and `makeover-layout` names it: a [`FieldKind::Range`] carries its
732 /// extent in [`Field::min`] and [`Field::max`], and a range missing an end has
733 /// nothing to slide across. egui's `Slider` demands a `RangeInclusive`, so
734 /// inventing one would be this renderer picking bounds the app never stated and
735 /// the user then dragging against them.
736 ///
737 /// It falls back to [`Control::Typed`], which is where every kind this renderer
738 /// cannot draw natively already lands: a number in a well is a true report of
739 /// the value and takes any answer the slider would.
740 fn shape_of(field: &Field<'_>) -> Control {
741 match control_shape(field.kind) {
742 Control::Slid if !field.bounded() => Control::Typed,
743 shape => shape,
744 }
745 }
746
747 /// The unit to draw beside this field's value, if there is one to draw.
748 ///
749 /// Two conditions rather than one: the field has to carry a unit and its kind
750 /// has to be one that means anything by it. `FieldKind::measurable` is the
751 /// description answering the second, so this renderer does not keep its own
752 /// list of which kinds are quantities -- which is the drift that predicate
753 /// exists to stop.
754 fn unit_of<'a>(field: &Field<'a>) -> Option<&'a str> {
755 field.unit.filter(|_| field.kind.measurable())
756 }
757
758 /// The two ends of a range, as egui wants them.
759 ///
760 /// `None` when either end is missing or is not a number this host can read.
761 /// The description carries the bounds as text on purpose — the bound of a date
762 /// is a date — so parsing them is the renderer's job and failing to is a real
763 /// outcome rather than an assertion.
764 fn extent(field: &Field<'_>) -> Option<RangeInclusive<f64>> {
765 let min = field.min?.parse::<f64>().ok()?;
766 let max = field.max?.parse::<f64>().ok()?;
767 Some(min..=max)
768 }
769
770 /// How many decimals to write a dragged value back with.
771 ///
772 /// Read off [`Field::step`], which is the only thing that says what
773 /// granularity the question has: a step of `0.01` is a two-decimal question and
774 /// a step of `1` is a whole-number one. Without a step the host's own
775 /// granularity stands, and egui's is continuous, so the value is written back
776 /// at whatever precision it round-trips at.
777 fn decimals(step: Option<&str>) -> Option<usize> {
778 let step = step?;
779 Some(match step.split_once('.') {
780 Some((_, fraction)) => fraction.trim_end_matches('0').len(),
781 None => 0,
782 })
783 }
784
785 /// What a select shows for the value it currently holds.
786 ///
787 /// A value no option carries stays on screen as itself rather than reading as
788 /// whichever option happens to be first. goingson saved a backup retention of
789 /// 10 against a 1/3/7/14/0 list and the browser silently showed it as 1, so the
790 /// next save wrote a value nobody chose; `makeover-webview` grew the fix as a
791 /// stray `<option>` and this is the same fix in the shape egui allows.
792 ///
793 /// The empty value is the one case that reads as unanswered rather than as an
794 /// answer, and [`chosen_text`] is what puts the field's ghost text there.
795 fn shown_label<'a>(options: &'a [Choice<'a>], value: &'a str) -> &'a str {
796 options
797 .iter()
798 .find(|opt| opt.value == value)
799 .map_or(value, |opt| opt.label)
800 }
801
802 /// What a select's closed control reads, and in which tone.
803 ///
804 /// A chooser with nothing chosen showed an empty box: `shown_label` falls back
805 /// to the value, and the unanswered value is the empty string. So an app with
806 /// an instruction to give — audiofiles' "Select device..." — had nowhere to put
807 /// it but a disabled button elsewhere on the screen, which is the affordance
808 /// this vocabulary keeps moving messages *off*.
809 ///
810 /// [`Field::placeholder`] is already the description's word for "what the field
811 /// reads while it is empty" and was honoured by the typed kinds alone, so
812 /// nothing new is said here; the renderer is what had not caught up. Muted
813 /// because it is not an answer, the same tone the typed kinds' ghost text takes
814 /// three lines up.
815 ///
816 /// A value no option carries but that is *not* empty stays as itself, in
817 /// `content`: that is the goingson retention bug and it is a wrong answer
818 /// rather than an absent one.
819 ///
820 /// Returns the words and the tone rather than a built [`RichText`], because
821 /// what it decides is both of them and only one of them is readable back off a
822 /// `RichText`.
823 ///
824 /// [`Field::placeholder`]: makeover_layout::Field::placeholder
825 fn chosen_text<'a>(field: &'a Field<'a>, value: &'a str, palette: &Palette) -> (&'a str, Color32) {
826 match field.placeholder {
827 Some(ghost) if value.is_empty() => (ghost, palette.content_muted),
828 _ => (shown_label(field.options, value), palette.content),
829 }
830 }
831
832 /// What one option in a choice field is drawn in.
833 ///
834 /// The chosen one is the emphasised thing and takes `content`; the rest take
835 /// [`content_secondary`](Palette::content_secondary), because an option that is
836 /// not chosen is still an option and pressing it chooses it. Muted would be the
837 /// lie: [`State::Disabled`] resolves to it, so a five-option field read as one
838 /// live row and four dead ones. `makeover-tui` draws it the same way
839 /// (`makeover-tui@230bf63`); wiki `three-tone-convention` is the table.
840 fn option_color(value: &str, option: &str, palette: &Palette) -> Color32 {
841 if value == option {
842 palette.content
843 } else {
844 palette.content_secondary
845 }
846 }
847
848 /// Which end of an interval a box is.
849 ///
850 /// Named rather than a bool, because what it selects is not a side but a
851 /// fallback: an empty end reads as the bound it stands for, and which bound
852 /// that is depends on the end.
853 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
854 enum Bound {
855 /// The lower end, falling back to the start of the extent.
856 Low,
857 /// The upper end, falling back to its end.
858 High,
859 }
860
861 /// The facts an interval's two boxes share.
862 ///
863 /// One struct because they are one axis: [`Field::min`], [`Field::max`],
864 /// [`Field::step`] and [`Field::unit`] describe the question rather than either
865 /// end of it, so reading them once is what stops the two boxes drifting apart.
866 struct Axis<'a> {
867 /// The extent both ends are dragged inside, when it is one this host can
868 /// read.
869 extent: Option<RangeInclusive<f64>>,
870 /// The granularity, as the description writes it.
871 step: Option<&'a str>,
872 /// What the axis is measured in.
873 unit: Option<&'a str>,
874 }
875
876 impl Axis<'_> {
877 /// What an empty end reads as: the bound it stands for.
878 ///
879 /// Zero with no extent to fall back on. That is the one number this
880 /// renderer invents, and it invents it where the description declined to
881 /// say anything: an unbounded interval has no edge for the end to sit on,
882 /// and a drag box has to start somewhere.
883 fn edge(&self, which: Bound) -> f64 {
884 self.extent.as_ref().map_or(0.0, |extent| match which {
885 Bound::Low => *extent.start(),
886 Bound::High => *extent.end(),
887 })
888 }
889
890 /// One end of the interval, as a drag box.
891 ///
892 /// # An empty end reads as its bound
893 ///
894 /// Which is what the shipped control did before it was described: an unset
895 /// minimum sits on the low edge and stores no filter. egui's `DragValue`
896 /// holds a number and has no empty state to offer, so the alternative was a
897 /// text box, and that would cost the app a control on the way into being
898 /// described.
899 ///
900 /// With no extent to fall back on, an empty end reads zero. That is the one
901 /// number this renderer invents, and it invents it where the description
902 /// declined to say anything: an unbounded interval has no edge for the end
903 /// to sit on, and a drag box has to start somewhere.
904 ///
905 /// Nothing is written back until the user drags, so a value the app put
906 /// there survives being looked at -- the same guarantee the slider makes.
907 fn end(&self, ui: &mut Ui, value: &mut String, which: Bound) -> Response {
908 let mut number = value.parse::<f64>().unwrap_or(self.edge(which));
909 let mut drag = DragValue::new(&mut number);
910 if let Some(extent) = self.extent.clone() {
911 drag = drag.range(extent);
912 }
913 if let Some(places) = decimals(self.step) {
914 drag = drag.max_decimals(places);
915 }
916 if let Some(step) = self.step.and_then(|s| s.parse::<f64>().ok()) {
917 drag = drag.speed(step);
918 }
919 // Inside the control, beside the readout, which is where `Field::unit`
920 // was decided to belong and where these boxes already put it.
921 if let Some(unit) = self.unit {
922 drag = drag.suffix(format!(" {unit}"));
923 }
924 let response = ui.add(drag);
925 if response.changed() {
926 *value = match decimals(self.step) {
927 Some(places) => format!("{number:.places$}"),
928 None => number.to_string(),
929 };
930 }
931 response
932 }
933 }
934
935 /// The control alone, without its label, hint or error.
936 fn control(
937 ui: &mut Ui,
938 field: &Field<'_>,
939 filling: Filling<'_>,
940 palette: &Palette,
941 style: &FieldStyle,
942 named_by: Option<egui::Id>,
943 ) -> Response {
944 // The mismatch path: described as one thing and filled as another. Nothing
945 // here can fix it, so it is drawn as the empty, inert version of what was
946 // described — visible on screen, in the way an empty select is at the
947 // webview renderer, rather than reported in a log nobody reads.
948 let mut discard = String::new();
949 // The interval's second scratch buffer. Two ends means the mismatch path
950 // needs two places to write nothing to.
951 let mut spare = String::new();
952 let mut off = false;
953
954 match shape_of(field) {
955 Control::Slid => {
956 let value = match filling {
957 Filling::Text(text) => text,
958 _ => &mut discard,
959 };
960 // `shape_of` has already refused an unbounded range, so the extent
961 // is only missing here if a bound is not a number — a date range,
962 // say, which this control cannot draw either.
963 let Some(extent) = extent(field) else {
964 return ui.label(RichText::new(value.as_str()).color(palette.content));
965 };
966
967 // A value the host cannot read starts at the low end rather than at
968 // zero, which may be outside the extent entirely. Nothing is
969 // written back until the user drags, so an unreadable value the app
970 // put there survives being looked at.
971 let mut number = value.parse::<f64>().unwrap_or(*extent.start());
972 // The granularity is the curve's as of makeover-layout 0.32.0. It
973 // is still in the value's own units, so the display precision is
974 // read off it exactly as before.
975 let step = field.curve.step();
976 let mut slider = Slider::new(&mut number, extent.clone()).text("");
977 if let Some(places) = decimals(step) {
978 slider = slider.max_decimals(places);
979 }
980 if let Some(step) = step.and_then(|s| s.parse::<f64>().ok()) {
981 slider = slider.step_by(step);
982 }
983 // egui's own constant-ratio track, which is this host's answer to
984 // `Curve::Logarithmic`. `is_ratio` rather than a match on the
985 // variant, because a ratio across zero is not one: makeover-layout
986 // decides the fallback so that four renderers cannot disagree about
987 // when it applies.
988 if field.curve.is_ratio(*extent.start(), *extent.end()) {
989 slider = slider.logarithmic(true);
990 }
991 // The unit goes inside the control, beside the readout egui already
992 // draws. That placement is the argument `Field::unit` was decided
993 // on: it is where these controls put it before they were described,
994 // and it is the one a label could never reach.
995 if let Some(unit) = unit_of(field) {
996 slider = slider.suffix(format!(" {unit}"));
997 }
998 let response = ui.add(slider);
999 if response.changed() {
1000 *value = match decimals(step) {
1001 Some(places) => format!("{number:.places$}"),
1002 None => number.to_string(),
1003 };
1004 }
1005 response
1006 }
1007 // One question, so one row. Two wells stacked would be two questions on
1008 // screen whatever the description said, which is the reading
1009 // `FieldKind::Interval` exists to prevent.
1010 //
1011 // Dragged rather than typed, because that is what these controls
1012 // already were: audiofiles' six filter axes are `DragValue` pairs with
1013 // a shared extent, a speed and a suffix, and a port that turned them
1014 // into text boxes would be a description costing the app a control.
1015 Control::Spanned => {
1016 let (lower, upper) = match filling {
1017 Filling::Between { lower, upper } => (lower, upper),
1018 _ => (&mut discard, &mut spare),
1019 };
1020 let axis = Axis {
1021 extent: extent(field),
1022 step: field.step,
1023 unit: unit_of(field),
1024 };
1025 ui.horizontal(|ui| {
1026 let low = axis.end(ui, lower, Bound::Low);
1027 // The word rather than a dash. A dash between two numbers is a
1028 // minus sign on a signed axis, and audiofiles filters loudness
1029 // in dBFS.
1030 ui.label(RichText::new("to").color(palette.content_secondary));
1031 let high = axis.end(ui, upper, Bound::High);
1032 // Both ends, by name. A union response carries the first id, so
1033 // labelling the union outside this arm names the lower box and
1034 // leaves the upper one announced as whatever number is in it --
1035 // which is how an interval half-kept the fix that gave every
1036 // other shape its question.
1037 if let Some(id) = named_by {
1038 low.clone().labelled_by(id);
1039 high.clone().labelled_by(id);
1040 }
1041 low | high
1042 })
1043 .inner
1044 }
1045 Control::Typed => {
1046 let text = match filling {
1047 Filling::Text(text) => text,
1048 _ => &mut discard,
1049 };
1050 // An empty frame and no margin: the well is this crate's, and egui's
1051 // own control background and padding would sit underneath it saying
1052 // something different about both.
1053 // Keyed on the description's own `multiline` and not on the
1054 // member: a markdown field is several lines by definition, and a
1055 // single-line edit would be a control the value cannot fit in. egui
1056 // does nothing else with the markdown, which is the honest answer
1057 // rather than a gap -- the source is text, and editing it as text
1058 // loses none of it.
1059 let mut edit = if field.kind.multiline() {
1060 TextEdit::multiline(text)
1061 } else {
1062 TextEdit::singleline(text)
1063 }
1064 .frame(egui::Frame::NONE)
1065 .margin(Margin::ZERO)
1066 .text_color(palette.content)
1067 .password(field.kind.confidential());
1068 if let Some(ghost) = field.placeholder {
1069 edit = edit.hint_text(RichText::new(ghost).color(palette.content_muted));
1070 }
1071 let response = frame(ui, Depth::Well, palette, style.frame, |ui| ui.add(edit));
1072 // A typed number has no readout of its own to sit beside, so the
1073 // unit follows the box. Muted, because it is a fact about the value
1074 // rather than a second thing to read.
1075 match unit_of(field) {
1076 Some(unit) => {
1077 ui.label(RichText::new(unit).color(palette.content_muted));
1078 response
1079 }
1080 None => response,
1081 }
1082 }
1083 Control::Toggled => {
1084 let on = match filling {
1085 Filling::On(on) => on,
1086 _ => &mut off,
1087 };
1088 ui.checkbox(on, RichText::new(field.label).color(palette.content))
1089 }
1090 Control::Listed => {
1091 let value = match filling {
1092 Filling::Text(text) => text,
1093 _ => &mut discard,
1094 };
1095 // No `shown_label` counterpart, and none is needed: a value no
1096 // option carries leaves every button unfilled, which is already
1097 // the honest report on screen. The select needs the fix because it
1098 // has one slot and must put *something* in it.
1099 let group = ui.vertical(|ui| {
1100 let mut answered: Option<Response> = None;
1101 for opt in field.options {
1102 // An option that cannot be picked yet is drawn and does not
1103 // answer, with the precondition beside it rather than
1104 // behind a hover: a greyed row with no reason reads as a
1105 // dead end, which is the state `Choice::unavailable` exists
1106 // to stop being sayable.
1107 let picked = if let Some(reason) = opt.unavailable {
1108 ui.horizontal(|ui| {
1109 let picked = ui
1110 .add_enabled_ui(false, |ui| {
1111 ui.radio_value(
1112 value,
1113 opt.value.to_owned(),
1114 RichText::new(opt.label).color(palette.content_muted),
1115 )
1116 })
1117 .inner;
1118 ui.label(RichText::new(reason).color(palette.content_muted));
1119 picked
1120 })
1121 .inner
1122 } else {
1123 ui.radio_value(
1124 value,
1125 opt.value.to_owned(),
1126 RichText::new(opt.label).color(option_color(value, opt.value, palette)),
1127 )
1128 };
1129 answered = Some(match answered {
1130 Some(prev) => prev.union(picked),
1131 None => picked,
1132 });
1133 }
1134 answered
1135 });
1136 // A group described with no options answers as its own empty area
1137 // rather than as no response at all, which keeps the caller's
1138 // `.changed()` chain working on a field whose option list has not
1139 // loaded yet.
1140 group.inner.unwrap_or(group.response)
1141 }
1142 Control::Chosen => {
1143 let value = match filling {
1144 Filling::Text(text) => text,
1145 _ => &mut discard,
1146 };
1147 let (shown, tone) = chosen_text(field, value, palette);
1148 ComboBox::from_id_salt(field.name)
1149 .selected_text(RichText::new(shown).color(tone))
1150 .show_ui(ui, |ui| {
1151 for opt in field.options {
1152 // Same rule as the radio group: shown, inert, and
1153 // saying why. A closed control hides its list, so the
1154 // reason has to travel with the row it belongs to.
1155 if let Some(reason) = opt.unavailable {
1156 ui.add_enabled_ui(false, |ui| {
1157 ui.selectable_value(
1158 value,
1159 opt.value.to_owned(),
1160 RichText::new(format!("{} {reason}", opt.label))
1161 .color(palette.content_muted),
1162 );
1163 });
1164 continue;
1165 }
1166 ui.selectable_value(
1167 value,
1168 opt.value.to_owned(),
1169 RichText::new(opt.label).color(option_color(value, opt.value, palette)),
1170 );
1171 }
1172 })
1173 .response
1174 }
1175 }
1176 }
1177
1178 /// One field, as the column the app drops into its form.
1179 ///
1180 /// The anatomy is `makeover-webview`'s, so the two renderers put a form
1181 /// together the same way: label, control, hint, error, top to bottom, with a
1182 /// checkbox labelling itself instead of taking a label above.
1183 ///
1184 /// Returns [`None`] for a [`FieldKind::Hidden`] field, which is what
1185 /// [`FieldKind::visible`] means and is the honest answer here: a webview still
1186 /// emits an input for it because the form submits, and an immediate-mode
1187 /// renderer has no form and no submission, so a hidden field is a value the app
1188 /// already holds and there is nothing to draw or to respond to.
1189 ///
1190 /// `state` is the description's interaction axis.
1191 /// [`State::Disabled`] greys the field and stops it answering, through
1192 /// [`State::suppresses_interaction`] rather than through a second reading of
1193 /// what disabled means. Focus is not on that axis and never reaches here: egui
1194 /// owns reach, focus and the ring for this renderer, and one ring means not a
1195 /// second one per renderer that happens to have opinions.
1196 pub fn field(
1197 ui: &mut Ui,
1198 field: &Field<'_>,
1199 filling: Filling<'_>,
1200 state: Option<State>,
1201 palette: &Palette,
1202 style: &FieldStyle,
1203 ) -> Option<Response> {
1204 if !field.kind.visible() {
1205 return None;
1206 }
1207 let enabled = !state.is_some_and(State::suppresses_interaction);
1208 let text = if enabled {
1209 palette.content
1210 } else {
1211 palette.content_muted
1212 };
1213
1214 let response = ui
1215 .vertical(|ui| {
1216 ui.spacing_mut().item_spacing.y = style.gap;
1217
1218 // A checkbox labels itself, on the right of the box.
1219 // `FieldKind::labels_itself` is the description saying so, and both
1220 // webview apps special-cased it inline before it did.
1221 let named_by = (!field.kind.labels_itself())
1222 .then(|| ui.label(RichText::new(label_text(field, style)).color(text)));
1223
1224 let response = ui
1225 .add_enabled_ui(enabled, |ui| {
1226 control(
1227 ui,
1228 field,
1229 filling,
1230 palette,
1231 style,
1232 named_by.as_ref().map(|l| l.id),
1233 )
1234 })
1235 .inner;
1236
1237 // The label, attached rather than merely adjacent.
1238 //
1239 // Drawing it above the control and stopping there is what this did
1240 // until 2026-08-22, and it put an unnamed box in the accessibility
1241 // tree with some text near it: a screen reader announced a text
1242 // field with no question, and a prefilled one announced its own
1243 // contents instead. audiofiles' four name modals were the site that
1244 // measured it, through a harness reading what the panel drew.
1245 //
1246 // Worth stating why it was worth fixing here rather than in each
1247 // app: `Field::label` is a member the description carries so a
1248 // renderer does not have to guess, `makeover-webview` has always
1249 // named it in `aria-describedby`, and the two renderers disagreeing
1250 // about a fact the description states is the one thing this layer
1251 // exists to prevent. A checkbox is unaffected -- egui names one from
1252 // its own text, which is what `labels_itself` already says.
1253 let response = match named_by {
1254 Some(label) => response.labelled_by(label.id),
1255 None => response,
1256 };
1257
1258 // Standing help, then what the answer costs, then what is wrong
1259 // now. All three, in that order, for the reason the webview
1260 // renderer names all three in `aria-describedby`: an error
1261 // appearing must not take the hint away with it. This host has the
1262 // room, so unlike makeover-tui it never has to choose -- the
1263 // precedence rule on `Field::note` is for the renderer that does.
1264 if let Some(hint) = field.hint {
1265 ui.label(RichText::new(hint).color(palette.content_muted));
1266 }
1267 // The note carries its own tone, and `Palette::tone` is what
1268 // resolves it, so a Neutral note is ordinary content rather than
1269 // a colour this renderer picked.
1270 if let Some((tone, note)) = field.note {
1271 ui.label(RichText::new(note).color(palette.tone(tone)));
1272 }
1273 if let Some(error) = field.error {
1274 ui.label(RichText::new(error).color(palette.danger));
1275 }
1276 response
1277 })
1278 .inner;
1279
1280 Some(response)
1281 }
1282
1283 /// A set of fields, laid down a column.
1284 ///
1285 /// `show_extended` is the disclosure, and it is a parameter rather than state
1286 /// held here because the disclosure belongs to the *form* and not to any field:
1287 /// [`Field::extended`] marks which fields are behind one, and the app owns
1288 /// whether it is open. That is the same division `makeover-webview` draws when
1289 /// it marks the group `data-extended` and emits no control to toggle it.
1290 ///
1291 /// `draw` is called once per field that should be visible, in order. Taking a
1292 /// callback rather than a slice of [`Filling`]s is what keeps the app's own
1293 /// values borrowed one at a time: a form's fields usually live in different
1294 /// structs, and a parallel array would have to be built each frame and kept in
1295 /// step with the description by hand.
1296 pub fn group<'a>(
1297 ui: &mut Ui,
1298 fields: &'a [Field<'a>],
1299 show_extended: bool,
1300 style: &FieldStyle,
1301 mut draw: impl FnMut(&mut Ui, &'a Field<'a>),
1302 ) {
1303 ui.vertical(|ui| {
1304 ui.spacing_mut().item_spacing.y = style.group_gap;
1305 for f in fields {
1306 if f.extended && !show_extended {
1307 continue;
1308 }
1309 draw(ui, f);
1310 }
1311 });
1312 }
1313
1314 #[cfg(test)]
1315 mod tests {
1316 use super::*;
1317
1318 fn palette(well: Color32) -> Palette {
1319 Palette {
1320 page: Color32::from_rgb(1, 1, 1),
1321 raised: Color32::from_rgb(2, 2, 2),
1322 overlay: Color32::from_rgb(3, 3, 3),
1323 well,
1324 sunken: Color32::from_rgb(4, 4, 4),
1325 bevel_light: Color32::WHITE,
1326 bevel_dark: Color32::BLACK,
1327 elevation: Color32::from_black_alpha(46),
1328 content: Color32::from_rgb(5, 5, 5),
1329 content_secondary: Color32::from_rgb(55, 55, 55),
1330 content_muted: Color32::from_rgb(6, 6, 6),
1331 action: Color32::from_rgb(7, 7, 7),
1332 danger: Color32::from_rgb(8, 8, 8),
1333 success: Color32::from_rgb(9, 9, 9),
1334 warning: Color32::from_rgb(10, 10, 10),
1335 info: Color32::from_rgb(11, 11, 11),
1336 }
1337 }
1338
1339 /// The cast is egui's own shadow type carrying the theme's tone, which is
1340 /// the whole of what this crate had to decide for it: unlike a bevel, egui
1341 /// already knows how to paint one.
1342 #[test]
1343 fn a_unit_is_drawn_only_where_the_kind_is_a_quantity() {
1344 // egui-drawing has no harness here, so what is tested is the decision
1345 // that precedes it: which fields have a unit to draw at all. The kind
1346 // half comes from the description rather than from a `matches!` in this
1347 // crate, which is the drift `FieldKind::measurable` exists to stop.
1348 let ranged = makeover_layout::Field {
1349 unit: Some("s"),
1350 ..makeover_layout::Field::range("attack", "Attack", "0", "5")
1351 };
1352 assert_eq!(unit_of(&ranged), Some("s"));
1353
1354 let typed = makeover_layout::Field {
1355 unit: Some("ms"),
1356 ..makeover_layout::Field::new(makeover_layout::FieldKind::Number, "fade", "Fade")
1357 };
1358 assert_eq!(unit_of(&typed), Some("ms"));
1359
1360 let worded = makeover_layout::Field {
1361 unit: Some("s"),
1362 ..makeover_layout::Field::new(makeover_layout::FieldKind::Text, "name", "Name")
1363 };
1364 assert_eq!(unit_of(&worded), None);
1365
1366 let bare = makeover_layout::Field::range("attack", "Attack", "0", "5");
1367 assert_eq!(unit_of(&bare), None);
1368 }
1369
1370 #[test]
1371 fn the_cast_hands_egui_the_themes_tone() {
1372 let p = palette(Color32::from_rgb(9, 9, 9));
1373 let cast = p.cast();
1374 assert_eq!(cast.color, p.elevation);
1375 assert!(cast.blur > 0, "a cast shadow is soft");
1376 assert_eq!(cast.offset, [0, 2], "it falls downward and only a little");
1377 }
1378
1379 #[test]
1380 fn a_well_resolves_to_its_own_token() {
1381 // No substitution left. The page-filled well was a stand-in for a
1382 // token that did not exist yet; it exists now.
1383 let w = Color32::from_rgb(9, 9, 9);
1384 let p = palette(w);
1385 assert_eq!(p.fill(Fill::Well), Some(w));
1386 assert_ne!(p.fill(Fill::Well), Some(p.page));
1387 }
1388
1389 #[test]
1390 fn every_intent_is_a_plain_lookup() {
1391 let p = palette(Color32::from_rgb(9, 9, 9));
1392 assert_eq!(p.fill(Fill::Page), Some(p.page));
1393 assert_eq!(p.fill(Fill::Raised), Some(p.raised));
1394 assert_eq!(p.fill(Fill::Overlay), Some(p.overlay));
1395 }
1396
1397 /// Sunken is its own colour, not the well's and not the page's. The two
1398 /// are authored in opposite directions and an earlier cut of the
1399 /// description conflated them.
1400 #[test]
1401 fn sunken_is_neither_the_well_nor_the_page() {
1402 let p = palette(Color32::from_rgb(9, 9, 9));
1403 assert_eq!(p.fill(Fill::Sunken), Some(p.sunken));
1404 assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Well));
1405 assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Page));
1406 }
1407
1408 #[test]
1409 fn a_raised_region_never_resolves_to_the_well_fill() {
1410 // The cross-app bug, asserted at the renderer boundary this time.
1411 let p = palette(Color32::from_rgb(9, 9, 9));
1412 let raised = Depth::Raised.fill().and_then(|f| p.fill(f));
1413 let well = Depth::Well.fill().and_then(|f| p.fill(f));
1414 assert_eq!(raised, Some(p.raised));
1415 assert_ne!(raised, well);
1416 }
1417
1418 #[test]
1419 fn an_overlay_is_cast_onto_the_page_and_takes_no_edge() {
1420 // makeover-layout 0.14.0 is what made this reachable. The answer was
1421 // already here at 0.10.0 and the question could not be asked.
1422 let p = palette(Color32::from_rgb(9, 9, 9));
1423 assert_eq!(
1424 Depth::Overlay.fill().and_then(|f| p.fill(f)),
1425 Some(p.overlay)
1426 );
1427 assert_eq!(Depth::Overlay.bevel(), None);
1428 // The shadow `frame` reaches for is the theme's tone rather than
1429 // egui's default, which is the whole reason `cast` exists.
1430 assert_eq!(p.cast().color, p.elevation);
1431 }
1432
1433 #[test]
1434 fn the_lit_edge_swaps_when_a_card_is_pressed() {
1435 let p = palette(Color32::from_rgb(9, 9, 9));
1436 let (tl, _) = Depth::Raised.bevel().unwrap().edges();
1437 let (ptl, _) = Depth::Raised.pressed().bevel().unwrap().edges();
1438 assert_eq!(p.edge(tl), p.bevel_light);
1439 assert_eq!(p.edge(ptl), p.bevel_dark);
1440 }
1441
1442 #[test]
1443 fn flat_asks_for_neither_fill_nor_edge() {
1444 assert!(Depth::Flat.fill().is_none());
1445 assert!(Depth::Flat.bevel().is_none());
1446 }
1447
1448 #[test]
1449 fn a_select_keeps_a_value_none_of_its_options_carries() {
1450 // The save-the-wrong-thing bug, asserted at the second renderer so it
1451 // is not re-found there. goingson's own numbers.
1452 let options = [
1453 Choice::plain("1"),
1454 Choice::plain("3"),
1455 Choice::plain("7"),
1456 Choice::plain("14"),
1457 ];
1458 assert_eq!(shown_label(&options, "10"), "10");
1459 // And a value that does match reads as its label, not as itself.
1460 let spelled = [Choice::new("7", "One week")];
1461 assert_eq!(shown_label(&spelled, "7"), "One week");
1462 }
1463
1464 #[test]
1465 fn an_unanswered_chooser_reads_its_ghost_text_and_reads_it_muted() {
1466 let p = palette(Color32::from_rgb(9, 9, 9));
1467 let options = [Choice::new("sp404", "SP-404")];
1468 let field = Field {
1469 placeholder: Some("Select device..."),
1470 ..Field::select("device", "Conform for device", &options)
1471 };
1472
1473 assert_eq!(
1474 chosen_text(&field, "", &p),
1475 ("Select device...", p.content_muted),
1476 "ghost text is not an answer, so it takes the tone the typed kinds' ghost text does"
1477 );
1478
1479 // Answered, and it is the label that reads rather than the value.
1480 assert_eq!(chosen_text(&field, "sp404", &p), ("SP-404", p.content));
1481 }
1482
1483 #[test]
1484 fn a_wrong_answer_is_not_an_absent_one() {
1485 // The retention-10 bug and the ghost text meet here: a value no option
1486 // carries still reads as itself, because the field IS answered and the
1487 // answer is wrong. Only the empty value is unanswered.
1488 let p = palette(Color32::from_rgb(9, 9, 9));
1489 let options = [Choice::plain("1"), Choice::plain("7")];
1490 let field = Field {
1491 placeholder: Some("Pick one"),
1492 ..Field::select("retention", "Keep backups for", &options)
1493 };
1494
1495 assert_eq!(chosen_text(&field, "10", &p), ("10", p.content));
1496 }
1497
1498 #[test]
1499 fn a_chooser_with_no_ghost_text_is_unchanged() {
1500 // The whole change is opt-in from the description. A field that says
1501 // nothing about its empty state still shows an empty box.
1502 let p = palette(Color32::from_rgb(9, 9, 9));
1503 let options = [Choice::plain("1")];
1504 let field = Field::select("retention", "Keep backups for", &options);
1505 assert_eq!(chosen_text(&field, "", &p), ("", p.content));
1506 }
1507
1508 #[test]
1509 fn a_range_is_slid_and_a_number_is_typed_into() {
1510 // The distinction the kind was added for, at the renderer that has to
1511 // act on it. A well with a figure in it is not a quiet slider.
1512 assert_eq!(control_shape(FieldKind::Range), Control::Slid);
1513 assert_eq!(control_shape(FieldKind::Number), Control::Typed);
1514 }
1515
1516 #[test]
1517 fn a_range_missing_an_end_falls_back_to_a_well() {
1518 // egui's `Slider` demands both ends, so inventing one would be this
1519 // renderer picking bounds the app never stated and the user then
1520 // dragging against them. A typed number takes every answer the slider
1521 // would.
1522 let whole = Field::range("review", "Review above", "0", "1");
1523 assert_eq!(shape_of(&whole), Control::Slid);
1524
1525 let half = Field {
1526 max: Some("1"),
1527 ..Field::new(FieldKind::Range, "review", "Review above")
1528 };
1529 assert_eq!(shape_of(&half), Control::Typed);
1530 assert_eq!(extent(&half), None);
1531
1532 // A bound this host cannot read is the same outcome by a different
1533 // route: the description carries bounds as text because the bound of a
1534 // date is a date.
1535 let dated = Field::range("when", "When", "2026-08-01", "2026-08-31");
1536 assert_eq!(extent(&dated), None);
1537 }
1538
1539 #[test]
1540 fn an_interval_is_its_own_shape_and_not_two_numbers() {
1541 // The distinction the kind was added for, at the renderer that has to
1542 // arrange it: two wells stacked are two questions on screen, whatever
1543 // the description says.
1544 assert_eq!(control_shape(FieldKind::Interval), Control::Spanned);
1545 assert_eq!(shape_of(&Field::interval("a", "b", "A")), Control::Spanned);
1546
1547 // Unlike a range, it owes no extent: its bounds are a rule on each end
1548 // rather than the control, so a missing one is an open end.
1549 let axis = Field {
1550 min: Some("0"),
1551 max: Some("300"),
1552 ..Field::interval("bpm_min", "bpm_max", "BPM")
1553 };
1554 assert_eq!(shape_of(&axis), Control::Spanned);
1555 }
1556
1557 #[test]
1558 fn an_empty_end_reads_as_the_bound_it_stands_for() {
1559 // Which is what the shipped control did before it was described: an
1560 // unset minimum sits on the low edge and stores no filter. `DragValue`
1561 // has no empty state, and a text box instead would cost the app a
1562 // control on the way into being described.
1563 let axis = Axis {
1564 extent: Some(0.0..=300.0),
1565 step: Some("1"),
1566 unit: Some("BPM"),
1567 };
1568 assert!((axis.edge(Bound::Low) - 0.0).abs() < f64::EPSILON);
1569 assert!((axis.edge(Bound::High) - 300.0).abs() < f64::EPSILON);
1570
1571 // With no extent there is no edge to sit on, and a drag box has to
1572 // start somewhere. The one number this renderer invents, invented where
1573 // the description declined to say anything.
1574 let open = Axis {
1575 extent: None,
1576 step: None,
1577 unit: None,
1578 };
1579 assert!((open.edge(Bound::Low) - 0.0).abs() < f64::EPSILON);
1580 assert!((open.edge(Bound::High) - 0.0).abs() < f64::EPSILON);
1581 }
1582
1583 #[test]
1584 fn the_step_decides_how_a_dragged_value_is_written_back() {
1585 // Without it a 0-to-1 threshold writes back whatever float the drag
1586 // landed on, which is the host's granularity and is what the
1587 // description says an absent step means.
1588 assert_eq!(decimals(None), None);
1589 assert_eq!(decimals(Some("1")), Some(0));
1590 assert_eq!(decimals(Some("0.01")), Some(2));
1591 // Trailing zeros are not precision: 0.10 is a one-decimal question.
1592 assert_eq!(decimals(Some("0.10")), Some(1));
1593 }
1594
1595 #[test]
1596 fn an_unavailable_option_is_drawn_muted_rather_than_dropped() {
1597 // The tone rule, at the one place it is a claim rather than a
1598 // preference: this option genuinely will not answer, so muted is the
1599 // truth. The available ones beside it keep the secondary intent.
1600 let p = palette(Color32::from_rgb(9, 9, 9));
1601 let options = [
1602 Choice::new("chromatic", "Chromatic"),
1603 Choice::new("multi", "Multi-sample").unless("Drop a second sample."),
1604 ];
1605 assert!(options[0].available());
1606 assert!(!options[1].available());
1607 assert_eq!(
1608 option_color("chromatic", options[0].value, &p),
1609 p.content,
1610 "the chosen option is the emphasised thing"
1611 );
1612 assert_eq!(
1613 option_color("chromatic", options[1].value, &p),
1614 p.content_secondary,
1615 "and `option_color` never mutes: the unavailable path is what does"
1616 );
1617 }
1618
1619 #[test]
1620 fn only_a_required_field_is_marked() {
1621 let style = FieldStyle::default();
1622 let plain = Field::new(FieldKind::Text, "title", "Title");
1623 assert_eq!(label_text(&plain, &style), "Title");
1624
1625 let required = Field {
1626 required: true,
1627 ..plain
1628 };
1629 assert_eq!(label_text(&required, &style), "Title *");
1630
1631 // The marker is copy and the app owns it, which is why it is a knob.
1632 let house = FieldStyle {
1633 required_marker: "(required)",
1634 ..style
1635 };
1636 assert_eq!(label_text(&required, &house), "Title (required)");
1637 }
1638
1639 #[test]
1640 fn a_select_and_a_checkbox_are_pressed_and_everything_else_is_typed_into() {
1641 // What decides whether the control gets a well. A well is for what the
1642 // user looks into, and only one of these is.
1643 assert_eq!(control_shape(FieldKind::Select), Control::Chosen);
1644 assert_eq!(control_shape(FieldKind::Radio), Control::Listed);
1645 assert_eq!(control_shape(FieldKind::Checkbox), Control::Toggled);
1646 for k in [
1647 FieldKind::Text,
1648 FieldKind::Secret,
1649 FieldKind::Number,
1650 FieldKind::Email,
1651 FieldKind::Url,
1652 FieldKind::Tel,
1653 FieldKind::Textarea,
1654 FieldKind::Rich,
1655 ] {
1656 assert_eq!(control_shape(k), Control::Typed, "{k:?} is typed into");
1657 }
1658 // And the two multi-line ones get a multi-line edit, which is the half
1659 // `control_shape` alone does not say: both are typed into, and only one
1660 // of the two edit shapes can hold a markdown document.
1661 assert!(FieldKind::Rich.multiline());
1662 assert!(FieldKind::Textarea.multiline());
1663 assert!(!FieldKind::Text.multiline());
1664 }
1665
1666 #[test]
1667 fn the_two_option_taking_kinds_are_drawn_differently_on_purpose() {
1668 // The description holds Select and Radio apart, and a renderer that
1669 // collapsed them would silently answer a question the app did not ask:
1670 // audiofiles' storage style is irreversible and its alternatives have
1671 // to be readable without opening anything. Asserting the two shapes
1672 // differ is asserting that distinction survives the trip.
1673 assert!(FieldKind::Select.offers_options());
1674 assert!(FieldKind::Radio.offers_options());
1675 assert_ne!(
1676 control_shape(FieldKind::Select),
1677 control_shape(FieldKind::Radio)
1678 );
1679 }
1680
1681 #[test]
1682 fn an_unchosen_option_is_secondary_and_never_muted() {
1683 let p = palette(Color32::from_rgb(4, 4, 4));
1684 assert_eq!(option_color("wav", "wav", &p), p.content);
1685 assert_eq!(option_color("wav", "aiff", &p), p.content_secondary);
1686 // The whole point of the distinction: muted is what Disabled resolves
1687 // to, so an option wearing it would claim it does not answer a press.
1688 assert_ne!(option_color("wav", "aiff", &p), p.content_muted);
1689 }
1690
1691 /// What the accessibility tree says a screen drew, as `(role, name)` pairs.
1692 ///
1693 /// egui builds this from the same `WidgetInfo` every widget already reports,
1694 /// so it is what a screen reader would be handed rather than a second
1695 /// opinion about it. A name that arrives through `labelled_by` is resolved
1696 /// the way a client resolves it: the relation names another node, and that
1697 /// node's text is the control's accessible name.
1698 fn announced(draw: impl FnMut(&mut egui::Ui)) -> Vec<(egui::accesskit::Role, String)> {
1699 let ctx = egui::Context::default();
1700 ctx.enable_accesskit();
1701 let mut draw = draw;
1702 let input = || egui::RawInput {
1703 screen_rect: Some(egui::Rect::from_min_size(
1704 egui::Pos2::ZERO,
1705 egui::vec2(800.0, 600.0),
1706 )),
1707 ..Default::default()
1708 };
1709 // Two passes: egui lays out against the previous frame, so the first
1710 // sees widgets at the wrong rect.
1711 let _ = ctx.run_ui(input(), &mut draw);
1712 let out = ctx.run_ui(input(), &mut draw);
1713
1714 let update = out
1715 .platform_output
1716 .accesskit_update
1717 .expect("accesskit is on, so a tree was built");
1718 let by_id: std::collections::HashMap<_, _> = update.nodes.iter().cloned().collect();
1719 update
1720 .nodes
1721 .iter()
1722 .map(|(_, node)| {
1723 let named = node.label().map(str::to_owned).or_else(|| {
1724 node.labelled_by()
1725 .iter()
1726 .find_map(|id| by_id.get(id))
1727 .and_then(|by| by.label().or_else(|| by.value()).map(str::to_owned))
1728 });
1729 (node.role(), named.unwrap_or_default())
1730 })
1731 .collect()
1732 }
1733
1734 #[test]
1735 fn a_fields_label_names_its_control_rather_than_sitting_beside_it() {
1736 let f = Field::new(FieldKind::Text, "name", "Vault name");
1737 let p = palette(Color32::from_rgb(9, 9, 9));
1738 let drawn = announced(|ui| {
1739 let mut text = String::new();
1740 field(
1741 ui,
1742 &f,
1743 Filling::Text(&mut text),
1744 None,
1745 &p,
1746 &FieldStyle::default(),
1747 );
1748 });
1749
1750 let box_ = drawn
1751 .iter()
1752 .find(|(role, _)| *role == egui::accesskit::Role::TextInput)
1753 .expect("a text field draws a text input");
1754 assert_eq!(
1755 box_.1, "Vault name",
1756 "the box is announced by the question rather than unnamed: {drawn:?}"
1757 );
1758 }
1759
1760 #[test]
1761 fn a_prefilled_box_is_still_announced_by_its_question() {
1762 // The sharper half. With nothing attached, a box carrying a value is
1763 // announced as that value, so a rename field read out the name it was
1764 // seeded with and never said what was being asked.
1765 let f = Field::new(FieldKind::Text, "name", "New name");
1766 let p = palette(Color32::from_rgb(9, 9, 9));
1767 let drawn = announced(|ui| {
1768 let mut text = String::from("Drums");
1769 field(
1770 ui,
1771 &f,
1772 Filling::Text(&mut text),
1773 None,
1774 &p,
1775 &FieldStyle::default(),
1776 );
1777 });
1778
1779 let box_ = drawn
1780 .iter()
1781 .find(|(role, _)| *role == egui::accesskit::Role::TextInput)
1782 .expect("a text field draws a text input");
1783 assert_eq!(box_.1, "New name", "{drawn:?}");
1784 }
1785
1786 #[test]
1787 fn both_ends_of_an_interval_are_named_by_the_one_question() {
1788 // A union response carries the first id, so labelling the pair outside
1789 // the arm named the lower box and left the upper one announced as
1790 // whatever number was in it.
1791 let f = Field::new(FieldKind::Interval, "bpm", "BPM Range");
1792 let p = palette(Color32::from_rgb(9, 9, 9));
1793 let drawn = announced(|ui| {
1794 let mut lower = String::from("90");
1795 let mut upper = String::from("300");
1796 field(
1797 ui,
1798 &f,
1799 Filling::Between {
1800 lower: &mut lower,
1801 upper: &mut upper,
1802 },
1803 None,
1804 &p,
1805 &FieldStyle::default(),
1806 );
1807 });
1808
1809 // A `SpinButton`: an interval's ends are drag values, not text boxes.
1810 let ends: Vec<_> = drawn
1811 .iter()
1812 .filter(|(role, _)| *role == egui::accesskit::Role::SpinButton)
1813 .collect();
1814 assert_eq!(ends.len(), 2, "an interval draws two boxes: {drawn:?}");
1815 for end in ends {
1816 assert_eq!(end.1, "BPM Range", "{drawn:?}");
1817 }
1818 }
1819
1820 #[test]
1821 fn a_checkbox_keeps_naming_itself() {
1822 // `FieldKind::labels_itself` routes past the label, and egui names a
1823 // checkbox from its own text, so there is nothing to attach and
1824 // attaching one would say the name twice.
1825 let f = Field::new(FieldKind::Checkbox, "loop", "Loop playback");
1826 let p = palette(Color32::from_rgb(9, 9, 9));
1827 let drawn = announced(|ui| {
1828 let mut ticked = false;
1829 field(
1830 ui,
1831 &f,
1832 Filling::On(&mut ticked),
1833 None,
1834 &p,
1835 &FieldStyle::default(),
1836 );
1837 });
1838
1839 assert!(
1840 drawn
1841 .iter()
1842 .any(|(role, name)| *role == egui::accesskit::Role::CheckBox
1843 && name == "Loop playback"),
1844 "{drawn:?}"
1845 );
1846 }
1847
1848 #[test]
1849 fn a_hidden_field_draws_nothing_and_answers_nothing() {
1850 // Where the two renderers legitimately part: a webview still emits an
1851 // input because the form submits, and there is no form here.
1852 let f = Field::new(FieldKind::Hidden, "id", "Id");
1853 let p = palette(Color32::from_rgb(9, 9, 9));
1854 egui::__run_test_ui(|ui| {
1855 let drawn = field(ui, &f, Filling::Absent, None, &p, &FieldStyle::default());
1856 assert!(drawn.is_none());
1857 });
1858 }
1859
1860 #[test]
1861 fn a_disabled_field_stops_answering_and_an_unstated_one_does_not() {
1862 let f = Field::new(FieldKind::Text, "title", "Title");
1863 let p = palette(Color32::from_rgb(9, 9, 9));
1864 let style = FieldStyle::default();
1865 egui::__run_test_ui(|ui| {
1866 let mut text = String::from("x");
1867 let disabled = field(
1868 ui,
1869 &f,
1870 Filling::Text(&mut text),
1871 Some(State::Disabled),
1872 &p,
1873 &style,
1874 )
1875 .unwrap();
1876 assert!(!disabled.enabled());
1877
1878 // Stating no state is the ordinary case and answers. Focus used to
1879 // be the counter-example here; it is egui's now and a description
1880 // cannot state it at all.
1881 let mut text = String::from("x");
1882 let plain = field(ui, &f, Filling::Text(&mut text), None, &p, &style).unwrap();
1883 assert!(plain.enabled(), "an unstated field still answers");
1884 });
1885 }
1886
1887 #[test]
1888 fn a_field_described_one_way_and_filled_another_is_drawn_inert() {
1889 // No panic and no write-through. A checkbox handed a string cannot be
1890 // filled, so it is drawn off and left alone.
1891 let f = Field::new(FieldKind::Checkbox, "done", "Done");
1892 let p = palette(Color32::from_rgb(9, 9, 9));
1893 let mut text = String::from("untouched");
1894 egui::__run_test_ui(|ui| {
1895 let drawn = field(
1896 ui,
1897 &f,
1898 Filling::Text(&mut text),
1899 None,
1900 &p,
1901 &FieldStyle::default(),
1902 );
1903 assert!(drawn.is_some());
1904 });
1905 assert_eq!(text, "untouched");
1906 }
1907
1908 #[test]
1909 fn the_disclosure_belongs_to_the_form_and_not_to_the_field() {
1910 let fields = [
1911 Field::new(FieldKind::Text, "title", "Title"),
1912 Field {
1913 extended: true,
1914 ..Field::new(FieldKind::Text, "notes", "Notes")
1915 },
1916 ];
1917 let style = FieldStyle::default();
1918
1919 let mut closed = Vec::new();
1920 egui::__run_test_ui(|ui| {
1921 group(ui, &fields, false, &style, |_, f| closed.push(f.name));
1922 });
1923 assert_eq!(closed, ["title"]);
1924
1925 let mut open = Vec::new();
1926 egui::__run_test_ui(|ui| {
1927 group(ui, &fields, true, &style, |_, f| open.push(f.name));
1928 });
1929 assert_eq!(open, ["title", "notes"]);
1930 }
1931
1932 #[test]
1933 fn the_default_frame_is_square_and_one_point() {
1934 let d = FrameStyle::default();
1935 assert_eq!(d.radius, CornerRadius::ZERO);
1936 assert_eq!(d.margin, Margin::ZERO);
1937 assert!((d.stroke - 1.0).abs() < f32::EPSILON);
1938 }
1939 }
1940