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