makeover_immediate/lib.rs
1//! The immediate-mode renderer for [`makeover_layout`].
2//!
3//! <!-- wiki: makeover-immediate -->
4//!
5//! Named for the mode, not the library, the way `makeover-tui` is named for
6//! the target and not for ratatui. Immediate mode is the constraint that
7//! actually separates this renderer from the other two, and egui is the
8//! backend it is written against.
9//!
10//! It is the harshest renderer the description has to survive: no
11//! `box-shadow`, no `inset`, no cascade, no retained tree to mutate, and
12//! `Visuals.widgets.*.bg_stroke` is a single stroke with no per-side control.
13//! A two-tone lit edge is not something egui can be configured into producing,
14//! so it gets painted by hand here, once, instead of in every consuming app.
15//!
16//! # What this crate does and does not own
17//!
18//! It owns the *expression*: two mitred polylines for a bevel and a `Frame`
19//! for a filled region. It owns no colours and no sizes, and no longer owns a
20//! substitution: it briefly supplied the page for a well, which was a stand-in
21//! for `surface-well` before makeover derived it, and every consumer reads the
22//! real token now. [`Palette`] is supplied by the caller,
23//! already resolved, and every radius, margin and stroke width arrives in
24//! [`FrameStyle`].
25//!
26//! That split is why the crate has no dependency on `makeover` itself: the app
27//! already resolves a theme, and coupling a renderer to a colour crate's
28//! version would buy nothing.
29//!
30//! # The cascade is the real difference
31//!
32//! A stylesheet can say "a pressed button inverts its bevel" once and let the
33//! cascade carry it. An immediate-mode renderer has nowhere to put that, so
34//! every call site decides. [`makeover_layout::Depth::pressed`] is what keeps
35//! the decision from being re-derived per widget.
36//!
37//! # 0.11.0: the overlay becomes reachable
38//!
39//! 0.10.0 answered what overlaying means in immediate mode with
40//! [`Palette::cast`], and nothing could ask: the description had no
41//! `Depth::Overlay` until `makeover-layout` 0.14.0, so the answer sat beside a
42//! question that could not be posed. [`frame`] now hands the cast shadow to the
43//! `egui::Frame` for any depth whose fill is [`Fill::Overlay`], keyed off the
44//! fill rather than the variant.
45//!
46//! The same release brings `makeover_layout::CellPart`, which 0.11.0 carried
47//! and did not draw. [`table`] draws it, below.
48//!
49//! # 0.12.0: the table
50//!
51//! [`table`] is the vocabulary 0.11.0 took without using. The consumer is
52//! audiofiles, whose file list is the only table in the tree exercising all four
53//! of what the description says about one at once: sortable headings with
54//! carets, fixed and remainder tracks, and buttons inside cells.
55//!
56//! Two things it forces, both named where they land:
57//!
58//! - **`egui_extras`**, this crate's first dependency past egui. egui has no
59//! table, and `Grid` gives no per-column sizing, no sticky header and no
60//! scroll sync, which is why audiofiles reached for `egui_extras` rather than
61//! building on `Grid`. A third answer here would reimplement that crate worse.
62//! - **[`Palette::action`]**, on the footing [`Palette::content`] arrived on: a
63//! link in a cell is the first thing here needing the action intent.
64//!
65//! Narrowing works differently from the terminal's and the module header says
66//! why: a content column cannot be measured before the app's closure has drawn
67//! it, so `egui_extras` sizes it and the declared floor budgets it.
68//!
69//! # 0.13.0: what the adoption found missing
70//!
71//! 0.12.0 shipped [`table`] before audiofiles had taken it, and taking it found
72//! three things the file list already did that the function could not say. All
73//! three are host idiom rather than description, which is why they land here and
74//! not in `makeover-layout`, and all three are answered on a handle the app
75//! never sees: the `egui_extras` row and builder this crate owns. That is
76//! [`table::cell`]'s reasoning again: what the app cannot reach, the renderer
77//! owes it.
78//!
79//! - **A selected row.** [`table::Body::selected`], a predicate asked per row,
80//! because `set_selected` is a method on the row. Without it a file list has
81//! no way to show what is selected, which is most of what a file list does.
82//! - **Scrolling a row into view.** [`table::Body::scroll_to`], because
83//! `scroll_to_row` is a method on the builder. A keyboard cursor that moves
84//! off-screen and stays there is the bug this prevents.
85//! - **Dragging a divider.** [`table::TableStyle::resizable`], which passes the
86//! test `sticky_header` failed in 0.12.0: egui_extras offers two settings here
87//! and a renderer can honestly make either choice.
88//!
89//! A fourth was found and is not a knob. Cells are centred on the row's centre
90//! line, always, because there is no second honest answer and egui's own default
91//! (top-aligned) is the one thing it cannot be.
92//!
93//! [`table::Body`] is also what splits a table's per-frame facts from its
94//! description and from its style. A row count, a selection and a scroll request
95//! are none of them style, and none of them survive the frame.
96//!
97//! # Forms
98//!
99//! 0.5.0 adds the field vocabulary on top of the depth vocabulary:
100//! [`makeover_layout::Field`] rendered to egui widgets, in [`field`], and a set
101//! of them laid down a column in [`group`]. Before it, a description saying
102//! "text field, labelled, required, with this hint" had no way to become a
103//! widget here, and audiofiles' forms stayed hand-rolled.
104//!
105//! `makeover-webview` got there first and its form emitter is the precedent
106//! followed rather than re-derived, including the parts that are bug fixes: a
107//! select handed a value none of its options carries keeps that value visible
108//! instead of silently reading as the first option, which is a save-the-wrong-
109//! thing bug goingson hit for real.
110//!
111//! What differs is forced by the mode and not chosen:
112//!
113//! - **The value arrives as a `&mut`.** [`Filling`] borrows the app's own field
114//! and the widget writes through it. There is no DOM to read back out of,
115//! which is also why the description deliberately does not carry the value.
116//! - **A text control is drawn as a well and a select is not.** The description
117//! holds that a well is for anything the user looks *into*, and a text field
118//! is its own example; a select and a checkbox are pressed rather than looked
119//! into, so they keep egui's own control painting.
120//! - **[`makeover_layout::State::Focus`] is not drawn here.** egui already
121//! paints exactly one focus stroke, and the description's rule is one ring
122//! rather than a ring per primitive, so adding a second would break the rule
123//! it came from. [`makeover_layout::State::Disabled`] *is* drawn, because egui
124//! has no opinion about it until told.
125
126#![forbid(unsafe_code)]
127
128use egui::{
129 Color32, ComboBox, CornerRadius, Margin, Painter, Rect, Response, RichText, Shape, Stroke,
130 TextEdit, Ui,
131};
132use makeover_layout::{Bevel, Choice, Depth, Edge, Field, FieldKind, Fill, State};
133
134/// Columns, narrowing, cell parts and the sort caret, over `egui_extras`.
135pub mod table;
136
137/// The resolved colours this renderer needs, as flat values.
138///
139/// Built by the app from whatever it already uses to resolve a theme, then
140/// held and reused. Deliberately not a trait and not string-keyed: a bevel is
141/// painted per widget per frame, and a map lookup per edge is a cost with
142/// nothing to show for it.
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub struct Palette {
145 /// `surface-page`.
146 pub page: Color32,
147 /// `surface-raised`.
148 pub raised: Color32,
149 /// `surface-overlay`.
150 pub overlay: Color32,
151 /// `surface-well`.
152 ///
153 /// Required, not optional. makeover derives it for every theme from 2.3.0,
154 /// so a resolved palette without a well is not a thing that exists here.
155 /// It was an `Option` while that was untrue, and this renderer substituted
156 /// the page; `makeover-tui` keeps its own `Option` for a different reason,
157 /// since a terminal can have the colour and still be unable to show it.
158 pub well: Color32,
159 /// `surface-sunken`.
160 ///
161 /// A surface set back from the one it sits on, by colour and nothing else.
162 /// Not a well: a well is a hole with an edge, and this has no edge. An
163 /// immediate-mode renderer paints an arbitrary rect, so unlike
164 /// `makeover-tui` it has no excuse for declining this one.
165 ///
166 /// Required rather than optional, on the same footing as `well`: all 31
167 /// themes makeover embeds author it.
168 pub sunken: Color32,
169 /// `bevel-light`.
170 pub bevel_light: Color32,
171 /// `bevel-dark`.
172 pub bevel_dark: Color32,
173 /// `elevation`.
174 ///
175 /// What a surface that floats OVER the page is cast onto it with. The one
176 /// intent here that is about a surface's relationship to the page rather
177 /// than about the surface, which is why it is a translucent near-black on
178 /// every theme rather than something read off the palette's own ramp.
179 ///
180 /// **Only for a surface that overlays.** A menu, a tooltip, a modal. A
181 /// surface *in* the layout takes a bevel, and reaching for this on a panel
182 /// or a card is how a pre-Platinum look survives a conversion under a new
183 /// name.
184 ///
185 /// egui has a real answer for this where a terminal does not: see
186 /// [`Palette::cast`], which is the shadow to hand an
187 /// [`egui::Frame`](egui::Frame).
188 pub elevation: Color32,
189 /// `content`.
190 ///
191 /// Ordinary text. Added 0.5.0 with the field renderer, which is the first
192 /// thing here that draws any: until then this crate painted surfaces and
193 /// edges and let the caller's own egui visuals answer for text.
194 pub content: Color32,
195 /// `content-muted`.
196 ///
197 /// A field's hint, and what
198 /// [`makeover_layout::State::Disabled`](makeover_layout::State::Disabled)
199 /// resolves to. Both readings come from the description rather than from
200 /// here: `State::Disabled` names this intent by token.
201 pub content_muted: Color32,
202 /// `action-primary`.
203 ///
204 /// What a control is drawn in. Added 0.12.0 with the table renderer, for the
205 /// reason `content` was added 0.5.0 with the field renderer: a link in a
206 /// cell is the first thing here that needs the action intent, and a palette
207 /// should carry what is used.
208 ///
209 /// This is the intent [`CellPart`](makeover_layout::CellPart) exists to
210 /// separate. A cell holding a control took the cell's text colour until the
211 /// description could say otherwise, which is the drift `makeover-layout`
212 /// 0.14.0 named and `makeover-webview` 0.25.0 fixed on its own side.
213 pub action: Color32,
214 /// `danger`.
215 ///
216 /// A field's error message. The one [`makeover_layout::Tone`] this renderer
217 /// needs so far, and it is here rather than as a whole resolved tone set
218 /// because notices are not drawn here yet and a palette should carry what
219 /// is used.
220 pub danger: Color32,
221}
222
223impl Palette {
224 /// Resolve a surface intent, or `None` for one this renderer does not know.
225 ///
226 /// A plain lookup. There is still no substitution: the old one existed only
227 /// while `surface-well` was underived, and every consumer reads the real
228 /// token now.
229 ///
230 /// `Option` since 0.3.0, because [`Fill`] became `#[non_exhaustive]` in
231 /// `makeover-layout` 0.4.0 and a total function over an open enum can only
232 /// stay total by inventing a colour for a member it has never heard of.
233 /// That is the substitution this crate spent 0.2.0 removing, so the return
234 /// type moved instead. Every member the description has today is answered
235 /// with `Some`.
236 #[must_use]
237 pub const fn fill(&self, fill: Fill) -> Option<Color32> {
238 match fill {
239 Fill::Page => Some(self.page),
240 Fill::Raised => Some(self.raised),
241 Fill::Overlay => Some(self.overlay),
242 Fill::Well => Some(self.well),
243 Fill::Sunken => Some(self.sunken),
244 _ => None,
245 }
246 }
247
248 /// The cast shadow for a surface that overlays the page.
249 ///
250 /// What "overlaying" means in immediate mode, answered rather than skipped.
251 /// egui already paints shadows for its menus and windows through
252 /// [`egui::Frame::shadow`], so the honest port is to hand that machinery the
253 /// theme's tone instead of egui's own default, not to invent a painter here
254 /// the way [`paint_bevel`] had to.
255 ///
256 /// The geometry matches what `makeover-webview` composes, in points rather
257 /// than pixels: a small downward offset and a wide soft blur. A Platinum-era
258 /// menu sits just off the page rather than hovering above it.
259 ///
260 /// ```no_run
261 /// # let palette: makeover_immediate::Palette = unimplemented!();
262 /// # let ui: &mut egui::Ui = unimplemented!();
263 /// egui::Frame::popup(ui.style())
264 /// .shadow(palette.cast())
265 /// .show(ui, |ui| { ui.label("over the page"); });
266 /// ```
267 #[must_use]
268 pub const fn cast(&self) -> egui::Shadow {
269 egui::Shadow {
270 offset: [0, 2],
271 blur: 24,
272 spread: 0,
273 color: self.elevation,
274 }
275 }
276
277 /// Resolve a bevel edge intent.
278 #[must_use]
279 pub const fn edge(&self, edge: Edge) -> Color32 {
280 match edge {
281 Edge::Light => self.bevel_light,
282 Edge::Dark => self.bevel_dark,
283 }
284 }
285}
286
287/// The geometry a framed region is drawn with.
288///
289/// Every field is a value, which is why they all arrive from the caller:
290/// radius and border width belong to `makeover-geometry`, and margins come
291/// from its relational gaps.
292#[derive(Debug, Clone, Copy, PartialEq)]
293pub struct FrameStyle {
294 /// Corner radius. Square under the Platinum default.
295 pub radius: CornerRadius,
296 /// Inner margin between the frame and its contents.
297 pub margin: Margin,
298 /// Bevel stroke width, in points.
299 pub stroke: f32,
300}
301
302impl Default for FrameStyle {
303 /// A one-point square frame with no inner margin.
304 fn default() -> Self {
305 Self {
306 radius: CornerRadius::ZERO,
307 margin: Margin::ZERO,
308 stroke: 1.0,
309 }
310 }
311}
312
313/// Paint a two-tone edge just inside `rect`.
314///
315/// Fill first, bevel after: this adds two polylines and nothing else, so it
316/// composes over whatever is already there. That is what lets it go over an
317/// [`egui::TextEdit`] after `ui.add`, where the widget's own fill has landed.
318///
319/// Two three-point polylines meeting at opposite corners, rather than four
320/// segments, so egui mitres the corner joins instead of leaving a notch.
321///
322/// The dark polyline is drawn second, so the two corners where the runs meet
323/// take its tone. That is the right answer here rather than a concession.
324/// [`makeover_layout::Bevel`] holds those corners to belong to both edges, and
325/// a renderer with room to divide one should; at the default one-point stroke
326/// the corner is a one-point square, so the division is sub-pixel and
327/// antialiasing resolves it to the same blend the mitre already gives. Splitting
328/// it would add a seam and no information. `makeover-tui` does split, because a
329/// terminal cell is large enough that not splitting costs a visible cell of edge
330/// weight — the same rule, at a resolution where it has something to say.
331pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) {
332 let (top_left, bottom_right) = bevel.edges();
333
334 // Inset by half a stroke so the line lands inside `rect` rather than
335 // straddling its edge, which on a fractional-scale display is the
336 // difference between one crisp pixel and two dim ones.
337 let r = rect.shrink(stroke / 2.0);
338
339 painter.add(Shape::line(
340 vec![r.left_bottom(), r.left_top(), r.right_top()],
341 Stroke::new(stroke, palette.edge(top_left)),
342 ));
343 painter.add(Shape::line(
344 vec![r.right_top(), r.right_bottom(), r.left_bottom()],
345 Stroke::new(stroke, palette.edge(bottom_right)),
346 ));
347}
348
349/// Draw a region at a given [`Depth`]: its fill and its edge, together.
350///
351/// [`Depth::Flat`] gets neither, and inherits whatever it sits on. That is the
352/// difference between level-with and painted-the-same-colour, and it is the
353/// reason `Depth::fill` returns an [`Option`] rather than defaulting to the
354/// page.
355pub fn frame<R>(
356 ui: &mut Ui,
357 depth: Depth,
358 palette: &Palette,
359 style: FrameStyle,
360 add_contents: impl FnOnce(&mut Ui) -> R,
361) -> R {
362 let mut f = egui::Frame::new()
363 .corner_radius(style.radius)
364 .inner_margin(style.margin);
365 // Two ways there is no fill to paint, and they collapse to the same
366 // outcome: the depth names none (Depth::Flat), or it names one this
367 // renderer cannot resolve. Either way the frame goes unfilled and the
368 // bevel below carries the depth on its own, which is the rule this
369 // module already documents for Flat.
370 if let Some(fill) = depth.fill().and_then(|f| palette.fill(f)) {
371 f = f.fill(fill);
372 }
373 // A surface that overlays the page is cast onto it. [`Palette::cast`] has
374 // answered what that means here since 0.10.0 and nothing could reach it: a
375 // description had no way to say Overlay until makeover-layout 0.14.0, so
376 // the answer sat beside the question. Keyed off the fill rather than the
377 // variant, so it stays right for whatever else the description calls an
378 // overlay later.
379 if depth.fill() == Some(Fill::Overlay) {
380 f = f.shadow(palette.cast());
381 }
382 let framed = f.show(ui, add_contents);
383 if let Some(bevel) = depth.bevel() {
384 paint_bevel(
385 ui.painter(),
386 framed.response.rect,
387 bevel,
388 palette,
389 style.stroke,
390 );
391 }
392 framed.inner
393}
394
395/// The geometry a field group is drawn with.
396///
397/// Values again, for the reason [`FrameStyle`] is: every number here belongs to
398/// `makeover-geometry` and arrives already resolved.
399#[derive(Debug, Clone, Copy, PartialEq)]
400pub struct FieldStyle {
401 /// The well a text control sits in.
402 pub frame: FrameStyle,
403 /// Between a field's own parts: its label, its control, its hint and its
404 /// error.
405 pub gap: f32,
406 /// Between one field and the next.
407 pub group_gap: f32,
408 /// What marks a required field, appended to its label.
409 ///
410 /// A knob rather than a constant, because it is the one piece of *copy* in
411 /// this crate and copy is not a renderer's call. A webview does not need it
412 /// at all — it emits the `required` attribute and the browser answers — so
413 /// this renderer is the first place where a compulsory field either shows
414 /// that it is or silently does not.
415 pub required_marker: &'static str,
416}
417
418impl Default for FieldStyle {
419 /// The default frame, no gaps, and an asterisk.
420 fn default() -> Self {
421 Self {
422 frame: FrameStyle::default(),
423 gap: 0.0,
424 group_gap: 0.0,
425 required_marker: "*",
426 }
427 }
428}
429
430/// What the field currently holds, borrowed from wherever the app keeps it.
431///
432/// The immediate-mode counterpart of `makeover_webview::form::Value`, and the
433/// place the two renderers are forced apart: there the value is read back out
434/// of the DOM after the fact, and here the widget writes through this borrow as
435/// it is edited. Same reason the description carries neither.
436///
437/// An enum rather than a bag of options, on the reasoning
438/// `makeover_webview::form::Value` records: a checkbox holding a string is
439/// unsayable here, where a struct would let it be said and then have to cope.
440#[derive(Debug, Default)]
441pub enum Filling<'a> {
442 /// Nothing to edit. The control is drawn and does not answer.
443 #[default]
444 Absent,
445 /// The buffer behind anything that takes typed text, a select included:
446 /// what a select holds is the `value` of one of its [`Choice`]s.
447 ///
448 /// [`Choice`]: makeover_layout::Choice
449 Text(&'a mut String),
450 /// A checkbox, on or off.
451 On(&'a mut bool),
452}
453
454/// The label, marked if the field is compulsory.
455fn label_text(field: &Field<'_>, style: &FieldStyle) -> String {
456 if field.required {
457 format!("{} {}", field.label, style.required_marker)
458 } else {
459 field.label.to_owned()
460 }
461}
462
463/// The four shapes a control comes in here, which is fewer than there are
464/// kinds.
465///
466/// [`FieldKind`] is `#[non_exhaustive]` and grows; this does not, because the
467/// ways egui has of asking for a value do not. Reducing the open set to this
468/// closed one in one total function is what keeps a new kind from needing a new
469/// arm at every match below.
470#[derive(Debug, Clone, Copy, PartialEq, Eq)]
471enum Control {
472 /// Typed into, so it is drawn as a well: the user looks into it.
473 Typed,
474 /// Picked from a control that shows one option at a time. Pressed rather
475 /// than looked into, so egui's own control painting stands.
476 Chosen,
477 /// Picked from options that are all on screen at once.
478 ///
479 /// Apart from [`Chosen`](Self::Chosen) because the description holds them
480 /// apart, and holding them apart is the whole content of
481 /// [`FieldKind::Radio`]: same question, and an answer the user can read
482 /// without opening anything.
483 Listed,
484 /// Held on or off.
485 Toggled,
486}
487
488/// Which shape a kind takes.
489///
490/// The wildcard falls to [`Control::Typed`] on purpose: a kind added to the
491/// description since this renderer was built degrades to a text box, which
492/// accepts any value the others would, rather than to nothing drawn at all.
493///
494/// `FieldKind::File` lands there as of makeover-layout 0.11.0, and it is left
495/// there rather than grown a shape of its own. egui's honest answer is a button
496/// that opens a native picker, which is a fifth control and a file-dialog
497/// dependency; no consumer of this crate asks for a file field yet. Same
498/// position this crate took on `Meter` at 0.10.0: the membership test is that
499/// every renderer *could* answer honestly, not that each one does on the day.
500/// A path in a text box is not nothing, and it is what an app that needs this
501/// tomorrow gets today.
502///
503/// `FieldKind::Date` and `FieldKind::DateTime` land there too, as of
504/// makeover-layout 0.15.0, on the same footing and with one thing owed. A
505/// calendar is a sixth control and bare `egui` has none, so a typed value is
506/// the honest answer here; what the app gets is the format the description
507/// names, `makeover_layout::DATE_FORMAT` and `DATETIME_FORMAT`, which is why
508/// those are constants rather than a sentence. audiofiles is the only consumer
509/// of this crate and asks for neither today. A calendar popup is the upgrade
510/// whenever one does.
511const fn control_shape(kind: FieldKind) -> Control {
512 match kind {
513 FieldKind::Select => Control::Chosen,
514 FieldKind::Radio => Control::Listed,
515 FieldKind::Checkbox => Control::Toggled,
516 _ => Control::Typed,
517 }
518}
519
520/// What a select shows for the value it currently holds.
521///
522/// A value no option carries stays on screen as itself rather than reading as
523/// whichever option happens to be first. goingson saved a backup retention of
524/// 10 against a 1/3/7/14/0 list and the browser silently showed it as 1, so the
525/// next save wrote a value nobody chose; `makeover-webview` grew the fix as a
526/// stray `<option>` and this is the same fix in the shape egui allows.
527fn shown_label<'a>(options: &'a [Choice<'a>], value: &'a str) -> &'a str {
528 options
529 .iter()
530 .find(|opt| opt.value == value)
531 .map_or(value, |opt| opt.label)
532}
533
534/// The control alone, without its label, hint or error.
535fn control(
536 ui: &mut Ui,
537 field: &Field<'_>,
538 filling: Filling<'_>,
539 palette: &Palette,
540 style: &FieldStyle,
541) -> Response {
542 // The mismatch path: described as one thing and filled as another. Nothing
543 // here can fix it, so it is drawn as the empty, inert version of what was
544 // described — visible on screen, in the way an empty select is at the
545 // webview renderer, rather than reported in a log nobody reads.
546 let mut discard = String::new();
547 let mut off = false;
548
549 match control_shape(field.kind) {
550 Control::Typed => {
551 let text = match filling {
552 Filling::Text(text) => text,
553 _ => &mut discard,
554 };
555 // An empty frame and no margin: the well is this crate's, and egui's
556 // own control background and padding would sit underneath it saying
557 // something different about both.
558 let mut edit = if matches!(field.kind, FieldKind::Textarea) {
559 TextEdit::multiline(text)
560 } else {
561 TextEdit::singleline(text)
562 }
563 .frame(egui::Frame::NONE)
564 .margin(Margin::ZERO)
565 .text_color(palette.content)
566 .password(field.kind.confidential());
567 if let Some(ghost) = field.placeholder {
568 edit = edit.hint_text(RichText::new(ghost).color(palette.content_muted));
569 }
570 frame(ui, Depth::Well, palette, style.frame, |ui| ui.add(edit))
571 }
572 Control::Toggled => {
573 let on = match filling {
574 Filling::On(on) => on,
575 _ => &mut off,
576 };
577 ui.checkbox(on, RichText::new(field.label).color(palette.content))
578 }
579 Control::Listed => {
580 let value = match filling {
581 Filling::Text(text) => text,
582 _ => &mut discard,
583 };
584 // No `shown_label` counterpart, and none is needed: a value no
585 // option carries leaves every button unfilled, which is already
586 // the honest report on screen. The select needs the fix because it
587 // has one slot and must put *something* in it.
588 let group = ui.vertical(|ui| {
589 let mut answered: Option<Response> = None;
590 for opt in field.options {
591 let picked = ui.radio_value(
592 value,
593 opt.value.to_owned(),
594 RichText::new(opt.label).color(palette.content),
595 );
596 answered = Some(match answered {
597 Some(prev) => prev.union(picked),
598 None => picked,
599 });
600 }
601 answered
602 });
603 // A group described with no options answers as its own empty area
604 // rather than as no response at all, which keeps the caller's
605 // `.changed()` chain working on a field whose option list has not
606 // loaded yet.
607 group.inner.unwrap_or(group.response)
608 }
609 Control::Chosen => {
610 let value = match filling {
611 Filling::Text(text) => text,
612 _ => &mut discard,
613 };
614 let shown = shown_label(field.options, value);
615 ComboBox::from_id_salt(field.name)
616 .selected_text(RichText::new(shown).color(palette.content))
617 .show_ui(ui, |ui| {
618 for opt in field.options {
619 ui.selectable_value(
620 value,
621 opt.value.to_owned(),
622 RichText::new(opt.label).color(palette.content),
623 );
624 }
625 })
626 .response
627 }
628 }
629}
630
631/// One field, as the column the app drops into its form.
632///
633/// The anatomy is `makeover-webview`'s, so the two renderers put a form
634/// together the same way: label, control, hint, error, top to bottom, with a
635/// checkbox labelling itself instead of taking a label above.
636///
637/// Returns [`None`] for a [`FieldKind::Hidden`] field, which is what
638/// [`FieldKind::visible`] means and is the honest answer here: a webview still
639/// emits an input for it because the form submits, and an immediate-mode
640/// renderer has no form and no submission, so a hidden field is a value the app
641/// already holds and there is nothing to draw or to respond to.
642///
643/// `state` is the description's interaction axis.
644/// [`State::Disabled`] greys the field and stops it answering, through
645/// [`State::suppresses_interaction`] rather than through a second reading of
646/// what disabled means. [`State::Focus`] is deliberately not acted on: egui
647/// paints its own focus stroke and the description asks for one ring, not one
648/// per renderer that happens to have opinions.
649pub fn field(
650 ui: &mut Ui,
651 field: &Field<'_>,
652 filling: Filling<'_>,
653 state: Option<State>,
654 palette: &Palette,
655 style: &FieldStyle,
656) -> Option<Response> {
657 if !field.kind.visible() {
658 return None;
659 }
660 let enabled = !state.is_some_and(State::suppresses_interaction);
661 let text = if enabled {
662 palette.content
663 } else {
664 palette.content_muted
665 };
666
667 let response = ui
668 .vertical(|ui| {
669 ui.spacing_mut().item_spacing.y = style.gap;
670
671 // A checkbox labels itself, on the right of the box.
672 // `FieldKind::labels_itself` is the description saying so, and both
673 // webview apps special-cased it inline before it did.
674 if !field.kind.labels_itself() {
675 ui.label(RichText::new(label_text(field, style)).color(text));
676 }
677
678 let response = ui
679 .add_enabled_ui(enabled, |ui| control(ui, field, filling, palette, style))
680 .inner;
681
682 // Standing help first, then what is wrong now. Both, in that order,
683 // for the reason the webview renderer names both in
684 // `aria-describedby`: an error appearing must not take the hint
685 // away with it.
686 if let Some(hint) = field.hint {
687 ui.label(RichText::new(hint).color(palette.content_muted));
688 }
689 if let Some(error) = field.error {
690 ui.label(RichText::new(error).color(palette.danger));
691 }
692 response
693 })
694 .inner;
695
696 Some(response)
697}
698
699/// A set of fields, laid down a column.
700///
701/// `show_extended` is the disclosure, and it is a parameter rather than state
702/// held here because the disclosure belongs to the *form* and not to any field:
703/// [`Field::extended`] marks which fields are behind one, and the app owns
704/// whether it is open. That is the same division `makeover-webview` draws when
705/// it marks the group `data-extended` and emits no control to toggle it.
706///
707/// `draw` is called once per field that should be visible, in order. Taking a
708/// callback rather than a slice of [`Filling`]s is what keeps the app's own
709/// values borrowed one at a time: a form's fields usually live in different
710/// structs, and a parallel array would have to be built each frame and kept in
711/// step with the description by hand.
712pub fn group<'a>(
713 ui: &mut Ui,
714 fields: &'a [Field<'a>],
715 show_extended: bool,
716 style: &FieldStyle,
717 mut draw: impl FnMut(&mut Ui, &'a Field<'a>),
718) {
719 ui.vertical(|ui| {
720 ui.spacing_mut().item_spacing.y = style.group_gap;
721 for f in fields {
722 if f.extended && !show_extended {
723 continue;
724 }
725 draw(ui, f);
726 }
727 });
728}
729
730#[cfg(test)]
731mod tests {
732 use super::*;
733
734 fn palette(well: Color32) -> Palette {
735 Palette {
736 page: Color32::from_rgb(1, 1, 1),
737 raised: Color32::from_rgb(2, 2, 2),
738 overlay: Color32::from_rgb(3, 3, 3),
739 well,
740 sunken: Color32::from_rgb(4, 4, 4),
741 bevel_light: Color32::WHITE,
742 bevel_dark: Color32::BLACK,
743 elevation: Color32::from_black_alpha(46),
744 content: Color32::from_rgb(5, 5, 5),
745 content_muted: Color32::from_rgb(6, 6, 6),
746 action: Color32::from_rgb(7, 7, 7),
747 danger: Color32::from_rgb(8, 8, 8),
748 }
749 }
750
751 /// The cast is egui's own shadow type carrying the theme's tone, which is
752 /// the whole of what this crate had to decide for it: unlike a bevel, egui
753 /// already knows how to paint one.
754 #[test]
755 fn the_cast_hands_egui_the_themes_tone() {
756 let p = palette(Color32::from_rgb(9, 9, 9));
757 let cast = p.cast();
758 assert_eq!(cast.color, p.elevation);
759 assert!(cast.blur > 0, "a cast shadow is soft");
760 assert_eq!(cast.offset, [0, 2], "it falls downward and only a little");
761 }
762
763 #[test]
764 fn a_well_resolves_to_its_own_token() {
765 // No substitution left. The page-filled well was a stand-in for a
766 // token that did not exist yet; it exists now.
767 let w = Color32::from_rgb(9, 9, 9);
768 let p = palette(w);
769 assert_eq!(p.fill(Fill::Well), Some(w));
770 assert_ne!(p.fill(Fill::Well), Some(p.page));
771 }
772
773 #[test]
774 fn every_intent_is_a_plain_lookup() {
775 let p = palette(Color32::from_rgb(9, 9, 9));
776 assert_eq!(p.fill(Fill::Page), Some(p.page));
777 assert_eq!(p.fill(Fill::Raised), Some(p.raised));
778 assert_eq!(p.fill(Fill::Overlay), Some(p.overlay));
779 }
780
781 /// Sunken is its own colour, not the well's and not the page's. The two
782 /// are authored in opposite directions and an earlier cut of the
783 /// description conflated them.
784 #[test]
785 fn sunken_is_neither_the_well_nor_the_page() {
786 let p = palette(Color32::from_rgb(9, 9, 9));
787 assert_eq!(p.fill(Fill::Sunken), Some(p.sunken));
788 assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Well));
789 assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Page));
790 }
791
792 #[test]
793 fn a_raised_region_never_resolves_to_the_well_fill() {
794 // The cross-app bug, asserted at the renderer boundary this time.
795 let p = palette(Color32::from_rgb(9, 9, 9));
796 let raised = Depth::Raised.fill().and_then(|f| p.fill(f));
797 let well = Depth::Well.fill().and_then(|f| p.fill(f));
798 assert_eq!(raised, Some(p.raised));
799 assert_ne!(raised, well);
800 }
801
802 #[test]
803 fn an_overlay_is_cast_onto_the_page_and_takes_no_edge() {
804 // makeover-layout 0.14.0 is what made this reachable. The answer was
805 // already here at 0.10.0 and the question could not be asked.
806 let p = palette(Color32::from_rgb(9, 9, 9));
807 assert_eq!(
808 Depth::Overlay.fill().and_then(|f| p.fill(f)),
809 Some(p.overlay)
810 );
811 assert_eq!(Depth::Overlay.bevel(), None);
812 // The shadow `frame` reaches for is the theme's tone rather than
813 // egui's default, which is the whole reason `cast` exists.
814 assert_eq!(p.cast().color, p.elevation);
815 }
816
817 #[test]
818 fn the_lit_edge_swaps_when_a_card_is_pressed() {
819 let p = palette(Color32::from_rgb(9, 9, 9));
820 let (tl, _) = Depth::Raised.bevel().unwrap().edges();
821 let (ptl, _) = Depth::Raised.pressed().bevel().unwrap().edges();
822 assert_eq!(p.edge(tl), p.bevel_light);
823 assert_eq!(p.edge(ptl), p.bevel_dark);
824 }
825
826 #[test]
827 fn flat_asks_for_neither_fill_nor_edge() {
828 assert!(Depth::Flat.fill().is_none());
829 assert!(Depth::Flat.bevel().is_none());
830 }
831
832 #[test]
833 fn a_select_keeps_a_value_none_of_its_options_carries() {
834 // The save-the-wrong-thing bug, asserted at the second renderer so it
835 // is not re-found there. goingson's own numbers.
836 let options = [
837 Choice::plain("1"),
838 Choice::plain("3"),
839 Choice::plain("7"),
840 Choice::plain("14"),
841 ];
842 assert_eq!(shown_label(&options, "10"), "10");
843 // And a value that does match reads as its label, not as itself.
844 let spelled = [Choice {
845 value: "7",
846 label: "One week",
847 }];
848 assert_eq!(shown_label(&spelled, "7"), "One week");
849 }
850
851 #[test]
852 fn only_a_required_field_is_marked() {
853 let style = FieldStyle::default();
854 let plain = Field::new(FieldKind::Text, "title", "Title");
855 assert_eq!(label_text(&plain, &style), "Title");
856
857 let required = Field {
858 required: true,
859 ..plain
860 };
861 assert_eq!(label_text(&required, &style), "Title *");
862
863 // The marker is copy and the app owns it, which is why it is a knob.
864 let house = FieldStyle {
865 required_marker: "(required)",
866 ..style
867 };
868 assert_eq!(label_text(&required, &house), "Title (required)");
869 }
870
871 #[test]
872 fn a_select_and_a_checkbox_are_pressed_and_everything_else_is_typed_into() {
873 // What decides whether the control gets a well. A well is for what the
874 // user looks into, and only one of these is.
875 assert_eq!(control_shape(FieldKind::Select), Control::Chosen);
876 assert_eq!(control_shape(FieldKind::Radio), Control::Listed);
877 assert_eq!(control_shape(FieldKind::Checkbox), Control::Toggled);
878 for k in [
879 FieldKind::Text,
880 FieldKind::Secret,
881 FieldKind::Number,
882 FieldKind::Email,
883 FieldKind::Url,
884 FieldKind::Tel,
885 FieldKind::Textarea,
886 ] {
887 assert_eq!(control_shape(k), Control::Typed, "{k:?} is typed into");
888 }
889 }
890
891 #[test]
892 fn the_two_option_taking_kinds_are_drawn_differently_on_purpose() {
893 // The description holds Select and Radio apart, and a renderer that
894 // collapsed them would silently answer a question the app did not ask:
895 // audiofiles' storage style is irreversible and its alternatives have
896 // to be readable without opening anything. Asserting the two shapes
897 // differ is asserting that distinction survives the trip.
898 assert!(FieldKind::Select.offers_options());
899 assert!(FieldKind::Radio.offers_options());
900 assert_ne!(
901 control_shape(FieldKind::Select),
902 control_shape(FieldKind::Radio)
903 );
904 }
905
906 #[test]
907 fn a_hidden_field_draws_nothing_and_answers_nothing() {
908 // Where the two renderers legitimately part: a webview still emits an
909 // input because the form submits, and there is no form here.
910 let f = Field::new(FieldKind::Hidden, "id", "Id");
911 let p = palette(Color32::from_rgb(9, 9, 9));
912 egui::__run_test_ui(|ui| {
913 let drawn = field(ui, &f, Filling::Absent, None, &p, &FieldStyle::default());
914 assert!(drawn.is_none());
915 });
916 }
917
918 #[test]
919 fn a_disabled_field_stops_answering_and_a_focused_one_does_not() {
920 let f = Field::new(FieldKind::Text, "title", "Title");
921 let p = palette(Color32::from_rgb(9, 9, 9));
922 let style = FieldStyle::default();
923 egui::__run_test_ui(|ui| {
924 let mut text = String::from("x");
925 let disabled = field(
926 ui,
927 &f,
928 Filling::Text(&mut text),
929 Some(State::Disabled),
930 &p,
931 &style,
932 )
933 .unwrap();
934 assert!(!disabled.enabled());
935
936 let mut text = String::from("x");
937 let focused = field(
938 ui,
939 &f,
940 Filling::Text(&mut text),
941 Some(State::Focus),
942 &p,
943 &style,
944 )
945 .unwrap();
946 assert!(focused.enabled(), "focus is a thing you can still click");
947 });
948 }
949
950 #[test]
951 fn a_field_described_one_way_and_filled_another_is_drawn_inert() {
952 // No panic and no write-through. A checkbox handed a string cannot be
953 // filled, so it is drawn off and left alone.
954 let f = Field::new(FieldKind::Checkbox, "done", "Done");
955 let p = palette(Color32::from_rgb(9, 9, 9));
956 let mut text = String::from("untouched");
957 egui::__run_test_ui(|ui| {
958 let drawn = field(
959 ui,
960 &f,
961 Filling::Text(&mut text),
962 None,
963 &p,
964 &FieldStyle::default(),
965 );
966 assert!(drawn.is_some());
967 });
968 assert_eq!(text, "untouched");
969 }
970
971 #[test]
972 fn the_disclosure_belongs_to_the_form_and_not_to_the_field() {
973 let fields = [
974 Field::new(FieldKind::Text, "title", "Title"),
975 Field {
976 extended: true,
977 ..Field::new(FieldKind::Text, "notes", "Notes")
978 },
979 ];
980 let style = FieldStyle::default();
981
982 let mut closed = Vec::new();
983 egui::__run_test_ui(|ui| {
984 group(ui, &fields, false, &style, |_, f| closed.push(f.name));
985 });
986 assert_eq!(closed, ["title"]);
987
988 let mut open = Vec::new();
989 egui::__run_test_ui(|ui| {
990 group(ui, &fields, true, &style, |_, f| open.push(f.name));
991 });
992 assert_eq!(open, ["title", "notes"]);
993 }
994
995 #[test]
996 fn the_default_frame_is_square_and_one_point() {
997 let d = FrameStyle::default();
998 assert_eq!(d.radius, CornerRadius::ZERO);
999 assert_eq!(d.margin, Margin::ZERO);
1000 assert!((d.stroke - 1.0).abs() < f32::EPSILON);
1001 }
1002}