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//! # Forms
38//!
39//! 0.5.0 adds the field vocabulary on top of the depth vocabulary:
40//! [`makeover_layout::Field`] rendered to egui widgets, in [`field`], and a set
41//! of them laid down a column in [`group`]. Before it, a description saying
42//! "text field, labelled, required, with this hint" had no way to become a
43//! widget here, and audiofiles' forms stayed hand-rolled.
44//!
45//! `makeover-webview` got there first and its form emitter is the precedent
46//! followed rather than re-derived, including the parts that are bug fixes: a
47//! select handed a value none of its options carries keeps that value visible
48//! instead of silently reading as the first option, which is a save-the-wrong-
49//! thing bug goingson hit for real.
50//!
51//! What differs is forced by the mode and not chosen:
52//!
53//! - **The value arrives as a `&mut`.** [`Filling`] borrows the app's own field
54//! and the widget writes through it. There is no DOM to read back out of,
55//! which is also why the description deliberately does not carry the value.
56//! - **A text control is drawn as a well and a select is not.** The description
57//! holds that a well is for anything the user looks *into*, and a text field
58//! is its own example; a select and a checkbox are pressed rather than looked
59//! into, so they keep egui's own control painting.
60//! - **[`makeover_layout::State::Focus`] is not drawn here.** egui already
61//! paints exactly one focus stroke, and the description's rule is one ring
62//! rather than a ring per primitive, so adding a second would break the rule
63//! it came from. [`makeover_layout::State::Disabled`] *is* drawn, because egui
64//! has no opinion about it until told.
65
66#![forbid(unsafe_code)]
67
68use egui::{
69 Color32, ComboBox, CornerRadius, Margin, Painter, Rect, Response, RichText, Shape, Stroke,
70 TextEdit, Ui,
71};
72use makeover_layout::{Bevel, Choice, Depth, Edge, Field, FieldKind, Fill, State};
73
74/// The resolved colours this renderer needs, as flat values.
75///
76/// Built by the app from whatever it already uses to resolve a theme, then
77/// held and reused. Deliberately not a trait and not string-keyed: a bevel is
78/// painted per widget per frame, and a map lookup per edge is a cost with
79/// nothing to show for it.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub struct Palette {
82 /// `surface-page`.
83 pub page: Color32,
84 /// `surface-raised`.
85 pub raised: Color32,
86 /// `surface-overlay`.
87 pub overlay: Color32,
88 /// `surface-well`.
89 ///
90 /// Required, not optional. makeover derives it for every theme from 2.3.0,
91 /// so a resolved palette without a well is not a thing that exists here.
92 /// It was an `Option` while that was untrue, and this renderer substituted
93 /// the page; `makeover-tui` keeps its own `Option` for a different reason,
94 /// since a terminal can have the colour and still be unable to show it.
95 pub well: Color32,
96 /// `surface-sunken`.
97 ///
98 /// A surface set back from the one it sits on, by colour and nothing else.
99 /// Not a well: a well is a hole with an edge, and this has no edge. An
100 /// immediate-mode renderer paints an arbitrary rect, so unlike
101 /// `makeover-tui` it has no excuse for declining this one.
102 ///
103 /// Required rather than optional, on the same footing as `well`: all 31
104 /// themes makeover embeds author it.
105 pub sunken: Color32,
106 /// `bevel-light`.
107 pub bevel_light: Color32,
108 /// `bevel-dark`.
109 pub bevel_dark: Color32,
110 /// `content`.
111 ///
112 /// Ordinary text. Added 0.5.0 with the field renderer, which is the first
113 /// thing here that draws any: until then this crate painted surfaces and
114 /// edges and let the caller's own egui visuals answer for text.
115 pub content: Color32,
116 /// `content-muted`.
117 ///
118 /// A field's hint, and what
119 /// [`makeover_layout::State::Disabled`](makeover_layout::State::Disabled)
120 /// resolves to. Both readings come from the description rather than from
121 /// here: `State::Disabled` names this intent by token.
122 pub content_muted: Color32,
123 /// `danger`.
124 ///
125 /// A field's error message. The one [`makeover_layout::Tone`] this renderer
126 /// needs so far, and it is here rather than as a whole resolved tone set
127 /// because notices are not drawn here yet and a palette should carry what
128 /// is used.
129 pub danger: Color32,
130}
131
132impl Palette {
133 /// Resolve a surface intent, or `None` for one this renderer does not know.
134 ///
135 /// A plain lookup. There is still no substitution: the old one existed only
136 /// while `surface-well` was underived, and every consumer reads the real
137 /// token now.
138 ///
139 /// `Option` since 0.3.0, because [`Fill`] became `#[non_exhaustive]` in
140 /// `makeover-layout` 0.4.0 and a total function over an open enum can only
141 /// stay total by inventing a colour for a member it has never heard of.
142 /// That is the substitution this crate spent 0.2.0 removing, so the return
143 /// type moved instead. Every member the description has today is answered
144 /// with `Some`.
145 #[must_use]
146 pub const fn fill(&self, fill: Fill) -> Option<Color32> {
147 match fill {
148 Fill::Page => Some(self.page),
149 Fill::Raised => Some(self.raised),
150 Fill::Overlay => Some(self.overlay),
151 Fill::Well => Some(self.well),
152 Fill::Sunken => Some(self.sunken),
153 _ => None,
154 }
155 }
156
157 /// Resolve a bevel edge intent.
158 #[must_use]
159 pub const fn edge(&self, edge: Edge) -> Color32 {
160 match edge {
161 Edge::Light => self.bevel_light,
162 Edge::Dark => self.bevel_dark,
163 }
164 }
165}
166
167/// The geometry a framed region is drawn with.
168///
169/// Every field is a value, which is why they all arrive from the caller:
170/// radius and border width belong to `makeover-geometry`, and margins come
171/// from its relational gaps.
172#[derive(Debug, Clone, Copy, PartialEq)]
173pub struct FrameStyle {
174 /// Corner radius. Square under the Platinum default.
175 pub radius: CornerRadius,
176 /// Inner margin between the frame and its contents.
177 pub margin: Margin,
178 /// Bevel stroke width, in points.
179 pub stroke: f32,
180}
181
182impl Default for FrameStyle {
183 /// A one-point square frame with no inner margin.
184 fn default() -> Self {
185 Self {
186 radius: CornerRadius::ZERO,
187 margin: Margin::ZERO,
188 stroke: 1.0,
189 }
190 }
191}
192
193/// Paint a two-tone edge just inside `rect`.
194///
195/// Fill first, bevel after: this adds two polylines and nothing else, so it
196/// composes over whatever is already there. That is what lets it go over an
197/// [`egui::TextEdit`] after `ui.add`, where the widget's own fill has landed.
198///
199/// Two three-point polylines meeting at opposite corners, rather than four
200/// segments, so egui mitres the corner joins instead of leaving a notch.
201///
202/// The dark polyline is drawn second, so the two corners where the runs meet
203/// take its tone. That is the right answer here rather than a concession.
204/// [`makeover_layout::Bevel`] holds those corners to belong to both edges, and
205/// a renderer with room to divide one should; at the default one-point stroke
206/// the corner is a one-point square, so the division is sub-pixel and
207/// antialiasing resolves it to the same blend the mitre already gives. Splitting
208/// it would add a seam and no information. `makeover-tui` does split, because a
209/// terminal cell is large enough that not splitting costs a visible cell of edge
210/// weight — the same rule, at a resolution where it has something to say.
211pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) {
212 let (top_left, bottom_right) = bevel.edges();
213
214 // Inset by half a stroke so the line lands inside `rect` rather than
215 // straddling its edge, which on a fractional-scale display is the
216 // difference between one crisp pixel and two dim ones.
217 let r = rect.shrink(stroke / 2.0);
218
219 painter.add(Shape::line(
220 vec![r.left_bottom(), r.left_top(), r.right_top()],
221 Stroke::new(stroke, palette.edge(top_left)),
222 ));
223 painter.add(Shape::line(
224 vec![r.right_top(), r.right_bottom(), r.left_bottom()],
225 Stroke::new(stroke, palette.edge(bottom_right)),
226 ));
227}
228
229/// Draw a region at a given [`Depth`]: its fill and its edge, together.
230///
231/// [`Depth::Flat`] gets neither, and inherits whatever it sits on. That is the
232/// difference between level-with and painted-the-same-colour, and it is the
233/// reason `Depth::fill` returns an [`Option`] rather than defaulting to the
234/// page.
235pub fn frame<R>(
236 ui: &mut Ui,
237 depth: Depth,
238 palette: &Palette,
239 style: FrameStyle,
240 add_contents: impl FnOnce(&mut Ui) -> R,
241) -> R {
242 let mut f = egui::Frame::new()
243 .corner_radius(style.radius)
244 .inner_margin(style.margin);
245 // Two ways there is no fill to paint, and they collapse to the same
246 // outcome: the depth names none (Depth::Flat), or it names one this
247 // renderer cannot resolve. Either way the frame goes unfilled and the
248 // bevel below carries the depth on its own, which is the rule this
249 // module already documents for Flat.
250 if let Some(fill) = depth.fill().and_then(|f| palette.fill(f)) {
251 f = f.fill(fill);
252 }
253 let framed = f.show(ui, add_contents);
254 if let Some(bevel) = depth.bevel() {
255 paint_bevel(
256 ui.painter(),
257 framed.response.rect,
258 bevel,
259 palette,
260 style.stroke,
261 );
262 }
263 framed.inner
264}
265
266/// The geometry a field group is drawn with.
267///
268/// Values again, for the reason [`FrameStyle`] is: every number here belongs to
269/// `makeover-geometry` and arrives already resolved.
270#[derive(Debug, Clone, Copy, PartialEq)]
271pub struct FieldStyle {
272 /// The well a text control sits in.
273 pub frame: FrameStyle,
274 /// Between a field's own parts: its label, its control, its hint and its
275 /// error.
276 pub gap: f32,
277 /// Between one field and the next.
278 pub group_gap: f32,
279 /// What marks a required field, appended to its label.
280 ///
281 /// A knob rather than a constant, because it is the one piece of *copy* in
282 /// this crate and copy is not a renderer's call. A webview does not need it
283 /// at all — it emits the `required` attribute and the browser answers — so
284 /// this renderer is the first place where a compulsory field either shows
285 /// that it is or silently does not.
286 pub required_marker: &'static str,
287}
288
289impl Default for FieldStyle {
290 /// The default frame, no gaps, and an asterisk.
291 fn default() -> Self {
292 Self {
293 frame: FrameStyle::default(),
294 gap: 0.0,
295 group_gap: 0.0,
296 required_marker: "*",
297 }
298 }
299}
300
301/// What the field currently holds, borrowed from wherever the app keeps it.
302///
303/// The immediate-mode counterpart of `makeover_webview::form::Value`, and the
304/// place the two renderers are forced apart: there the value is read back out
305/// of the DOM after the fact, and here the widget writes through this borrow as
306/// it is edited. Same reason the description carries neither.
307///
308/// An enum rather than a bag of options, on the reasoning
309/// `makeover_webview::form::Value` records: a checkbox holding a string is
310/// unsayable here, where a struct would let it be said and then have to cope.
311#[derive(Debug, Default)]
312pub enum Filling<'a> {
313 /// Nothing to edit. The control is drawn and does not answer.
314 #[default]
315 Absent,
316 /// The buffer behind anything that takes typed text, a select included:
317 /// what a select holds is the `value` of one of its [`Choice`]s.
318 ///
319 /// [`Choice`]: makeover_layout::Choice
320 Text(&'a mut String),
321 /// A checkbox, on or off.
322 On(&'a mut bool),
323}
324
325/// The label, marked if the field is compulsory.
326fn label_text(field: &Field<'_>, style: &FieldStyle) -> String {
327 if field.required {
328 format!("{} {}", field.label, style.required_marker)
329 } else {
330 field.label.to_owned()
331 }
332}
333
334/// The four shapes a control comes in here, which is fewer than there are
335/// kinds.
336///
337/// [`FieldKind`] is `#[non_exhaustive]` and grows; this does not, because the
338/// ways egui has of asking for a value do not. Reducing the open set to this
339/// closed one in one total function is what keeps a new kind from needing a new
340/// arm at every match below.
341#[derive(Debug, Clone, Copy, PartialEq, Eq)]
342enum Control {
343 /// Typed into, so it is drawn as a well: the user looks into it.
344 Typed,
345 /// Picked from a control that shows one option at a time. Pressed rather
346 /// than looked into, so egui's own control painting stands.
347 Chosen,
348 /// Picked from options that are all on screen at once.
349 ///
350 /// Apart from [`Chosen`](Self::Chosen) because the description holds them
351 /// apart, and holding them apart is the whole content of
352 /// [`FieldKind::Radio`]: same question, and an answer the user can read
353 /// without opening anything.
354 Listed,
355 /// Held on or off.
356 Toggled,
357}
358
359/// Which shape a kind takes.
360///
361/// The wildcard falls to [`Control::Typed`] on purpose: a kind added to the
362/// description since this renderer was built degrades to a text box, which
363/// accepts any value the others would, rather than to nothing drawn at all.
364///
365/// `FieldKind::File` lands there as of makeover-layout 0.11.0, and it is left
366/// there rather than grown a shape of its own. egui's honest answer is a button
367/// that opens a native picker, which is a fifth control and a file-dialog
368/// dependency; no consumer of this crate asks for a file field yet. Same
369/// position this crate took on `Meter` at 0.10.0: the membership test is that
370/// every renderer *could* answer honestly, not that each one does on the day.
371/// A path in a text box is not nothing, and it is what an app that needs this
372/// tomorrow gets today.
373const fn control_shape(kind: FieldKind) -> Control {
374 match kind {
375 FieldKind::Select => Control::Chosen,
376 FieldKind::Radio => Control::Listed,
377 FieldKind::Checkbox => Control::Toggled,
378 _ => Control::Typed,
379 }
380}
381
382/// What a select shows for the value it currently holds.
383///
384/// A value no option carries stays on screen as itself rather than reading as
385/// whichever option happens to be first. goingson saved a backup retention of
386/// 10 against a 1/3/7/14/0 list and the browser silently showed it as 1, so the
387/// next save wrote a value nobody chose; `makeover-webview` grew the fix as a
388/// stray `<option>` and this is the same fix in the shape egui allows.
389fn shown_label<'a>(options: &'a [Choice<'a>], value: &'a str) -> &'a str {
390 options
391 .iter()
392 .find(|opt| opt.value == value)
393 .map_or(value, |opt| opt.label)
394}
395
396/// The control alone, without its label, hint or error.
397fn control(
398 ui: &mut Ui,
399 field: &Field<'_>,
400 filling: Filling<'_>,
401 palette: &Palette,
402 style: &FieldStyle,
403) -> Response {
404 // The mismatch path: described as one thing and filled as another. Nothing
405 // here can fix it, so it is drawn as the empty, inert version of what was
406 // described — visible on screen, in the way an empty select is at the
407 // webview renderer, rather than reported in a log nobody reads.
408 let mut discard = String::new();
409 let mut off = false;
410
411 match control_shape(field.kind) {
412 Control::Typed => {
413 let text = match filling {
414 Filling::Text(text) => text,
415 _ => &mut discard,
416 };
417 // An empty frame and no margin: the well is this crate's, and egui's
418 // own control background and padding would sit underneath it saying
419 // something different about both.
420 let mut edit = if matches!(field.kind, FieldKind::Textarea) {
421 TextEdit::multiline(text)
422 } else {
423 TextEdit::singleline(text)
424 }
425 .frame(egui::Frame::NONE)
426 .margin(Margin::ZERO)
427 .text_color(palette.content)
428 .password(field.kind.confidential());
429 if let Some(ghost) = field.placeholder {
430 edit = edit.hint_text(RichText::new(ghost).color(palette.content_muted));
431 }
432 frame(ui, Depth::Well, palette, style.frame, |ui| ui.add(edit))
433 }
434 Control::Toggled => {
435 let on = match filling {
436 Filling::On(on) => on,
437 _ => &mut off,
438 };
439 ui.checkbox(on, RichText::new(field.label).color(palette.content))
440 }
441 Control::Listed => {
442 let value = match filling {
443 Filling::Text(text) => text,
444 _ => &mut discard,
445 };
446 // No `shown_label` counterpart, and none is needed: a value no
447 // option carries leaves every button unfilled, which is already
448 // the honest report on screen. The select needs the fix because it
449 // has one slot and must put *something* in it.
450 let group = ui.vertical(|ui| {
451 let mut answered: Option<Response> = None;
452 for opt in field.options {
453 let picked = ui.radio_value(
454 value,
455 opt.value.to_owned(),
456 RichText::new(opt.label).color(palette.content),
457 );
458 answered = Some(match answered {
459 Some(prev) => prev.union(picked),
460 None => picked,
461 });
462 }
463 answered
464 });
465 // A group described with no options answers as its own empty area
466 // rather than as no response at all, which keeps the caller's
467 // `.changed()` chain working on a field whose option list has not
468 // loaded yet.
469 group.inner.unwrap_or(group.response)
470 }
471 Control::Chosen => {
472 let value = match filling {
473 Filling::Text(text) => text,
474 _ => &mut discard,
475 };
476 let shown = shown_label(field.options, value);
477 ComboBox::from_id_salt(field.name)
478 .selected_text(RichText::new(shown).color(palette.content))
479 .show_ui(ui, |ui| {
480 for opt in field.options {
481 ui.selectable_value(
482 value,
483 opt.value.to_owned(),
484 RichText::new(opt.label).color(palette.content),
485 );
486 }
487 })
488 .response
489 }
490 }
491}
492
493/// One field, as the column the app drops into its form.
494///
495/// The anatomy is `makeover-webview`'s, so the two renderers put a form
496/// together the same way: label, control, hint, error, top to bottom, with a
497/// checkbox labelling itself instead of taking a label above.
498///
499/// Returns [`None`] for a [`FieldKind::Hidden`] field, which is what
500/// [`FieldKind::visible`] means and is the honest answer here: a webview still
501/// emits an input for it because the form submits, and an immediate-mode
502/// renderer has no form and no submission, so a hidden field is a value the app
503/// already holds and there is nothing to draw or to respond to.
504///
505/// `state` is the description's interaction axis.
506/// [`State::Disabled`] greys the field and stops it answering, through
507/// [`State::suppresses_interaction`] rather than through a second reading of
508/// what disabled means. [`State::Focus`] is deliberately not acted on: egui
509/// paints its own focus stroke and the description asks for one ring, not one
510/// per renderer that happens to have opinions.
511pub fn field(
512 ui: &mut Ui,
513 field: &Field<'_>,
514 filling: Filling<'_>,
515 state: Option<State>,
516 palette: &Palette,
517 style: &FieldStyle,
518) -> Option<Response> {
519 if !field.kind.visible() {
520 return None;
521 }
522 let enabled = !state.is_some_and(State::suppresses_interaction);
523 let text = if enabled {
524 palette.content
525 } else {
526 palette.content_muted
527 };
528
529 let response = ui
530 .vertical(|ui| {
531 ui.spacing_mut().item_spacing.y = style.gap;
532
533 // A checkbox labels itself, on the right of the box.
534 // `FieldKind::labels_itself` is the description saying so, and both
535 // webview apps special-cased it inline before it did.
536 if !field.kind.labels_itself() {
537 ui.label(RichText::new(label_text(field, style)).color(text));
538 }
539
540 let response = ui
541 .add_enabled_ui(enabled, |ui| control(ui, field, filling, palette, style))
542 .inner;
543
544 // Standing help first, then what is wrong now. Both, in that order,
545 // for the reason the webview renderer names both in
546 // `aria-describedby`: an error appearing must not take the hint
547 // away with it.
548 if let Some(hint) = field.hint {
549 ui.label(RichText::new(hint).color(palette.content_muted));
550 }
551 if let Some(error) = field.error {
552 ui.label(RichText::new(error).color(palette.danger));
553 }
554 response
555 })
556 .inner;
557
558 Some(response)
559}
560
561/// A set of fields, laid down a column.
562///
563/// `show_extended` is the disclosure, and it is a parameter rather than state
564/// held here because the disclosure belongs to the *form* and not to any field:
565/// [`Field::extended`] marks which fields are behind one, and the app owns
566/// whether it is open. That is the same division `makeover-webview` draws when
567/// it marks the group `data-extended` and emits no control to toggle it.
568///
569/// `draw` is called once per field that should be visible, in order. Taking a
570/// callback rather than a slice of [`Filling`]s is what keeps the app's own
571/// values borrowed one at a time: a form's fields usually live in different
572/// structs, and a parallel array would have to be built each frame and kept in
573/// step with the description by hand.
574pub fn group<'a>(
575 ui: &mut Ui,
576 fields: &'a [Field<'a>],
577 show_extended: bool,
578 style: &FieldStyle,
579 mut draw: impl FnMut(&mut Ui, &'a Field<'a>),
580) {
581 ui.vertical(|ui| {
582 ui.spacing_mut().item_spacing.y = style.group_gap;
583 for f in fields {
584 if f.extended && !show_extended {
585 continue;
586 }
587 draw(ui, f);
588 }
589 });
590}
591
592#[cfg(test)]
593mod tests {
594 use super::*;
595
596 fn palette(well: Color32) -> Palette {
597 Palette {
598 page: Color32::from_rgb(1, 1, 1),
599 raised: Color32::from_rgb(2, 2, 2),
600 overlay: Color32::from_rgb(3, 3, 3),
601 well,
602 sunken: Color32::from_rgb(4, 4, 4),
603 bevel_light: Color32::WHITE,
604 bevel_dark: Color32::BLACK,
605 content: Color32::from_rgb(5, 5, 5),
606 content_muted: Color32::from_rgb(6, 6, 6),
607 danger: Color32::from_rgb(7, 7, 7),
608 }
609 }
610
611 #[test]
612 fn a_well_resolves_to_its_own_token() {
613 // No substitution left. The page-filled well was a stand-in for a
614 // token that did not exist yet; it exists now.
615 let w = Color32::from_rgb(9, 9, 9);
616 let p = palette(w);
617 assert_eq!(p.fill(Fill::Well), Some(w));
618 assert_ne!(p.fill(Fill::Well), Some(p.page));
619 }
620
621 #[test]
622 fn every_intent_is_a_plain_lookup() {
623 let p = palette(Color32::from_rgb(9, 9, 9));
624 assert_eq!(p.fill(Fill::Page), Some(p.page));
625 assert_eq!(p.fill(Fill::Raised), Some(p.raised));
626 assert_eq!(p.fill(Fill::Overlay), Some(p.overlay));
627 }
628
629 /// Sunken is its own colour, not the well's and not the page's. The two
630 /// are authored in opposite directions and an earlier cut of the
631 /// description conflated them.
632 #[test]
633 fn sunken_is_neither_the_well_nor_the_page() {
634 let p = palette(Color32::from_rgb(9, 9, 9));
635 assert_eq!(p.fill(Fill::Sunken), Some(p.sunken));
636 assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Well));
637 assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Page));
638 }
639
640 #[test]
641 fn a_raised_region_never_resolves_to_the_well_fill() {
642 // The cross-app bug, asserted at the renderer boundary this time.
643 let p = palette(Color32::from_rgb(9, 9, 9));
644 let raised = Depth::Raised.fill().and_then(|f| p.fill(f));
645 let well = Depth::Well.fill().and_then(|f| p.fill(f));
646 assert_eq!(raised, Some(p.raised));
647 assert_ne!(raised, well);
648 }
649
650 #[test]
651 fn the_lit_edge_swaps_when_a_card_is_pressed() {
652 let p = palette(Color32::from_rgb(9, 9, 9));
653 let (tl, _) = Depth::Raised.bevel().unwrap().edges();
654 let (ptl, _) = Depth::Raised.pressed().bevel().unwrap().edges();
655 assert_eq!(p.edge(tl), p.bevel_light);
656 assert_eq!(p.edge(ptl), p.bevel_dark);
657 }
658
659 #[test]
660 fn flat_asks_for_neither_fill_nor_edge() {
661 assert!(Depth::Flat.fill().is_none());
662 assert!(Depth::Flat.bevel().is_none());
663 }
664
665 #[test]
666 fn a_select_keeps_a_value_none_of_its_options_carries() {
667 // The save-the-wrong-thing bug, asserted at the second renderer so it
668 // is not re-found there. goingson's own numbers.
669 let options = [
670 Choice::plain("1"),
671 Choice::plain("3"),
672 Choice::plain("7"),
673 Choice::plain("14"),
674 ];
675 assert_eq!(shown_label(&options, "10"), "10");
676 // And a value that does match reads as its label, not as itself.
677 let spelled = [Choice {
678 value: "7",
679 label: "One week",
680 }];
681 assert_eq!(shown_label(&spelled, "7"), "One week");
682 }
683
684 #[test]
685 fn only_a_required_field_is_marked() {
686 let style = FieldStyle::default();
687 let plain = Field::new(FieldKind::Text, "title", "Title");
688 assert_eq!(label_text(&plain, &style), "Title");
689
690 let required = Field {
691 required: true,
692 ..plain
693 };
694 assert_eq!(label_text(&required, &style), "Title *");
695
696 // The marker is copy and the app owns it, which is why it is a knob.
697 let house = FieldStyle {
698 required_marker: "(required)",
699 ..style
700 };
701 assert_eq!(label_text(&required, &house), "Title (required)");
702 }
703
704 #[test]
705 fn a_select_and_a_checkbox_are_pressed_and_everything_else_is_typed_into() {
706 // What decides whether the control gets a well. A well is for what the
707 // user looks into, and only one of these is.
708 assert_eq!(control_shape(FieldKind::Select), Control::Chosen);
709 assert_eq!(control_shape(FieldKind::Radio), Control::Listed);
710 assert_eq!(control_shape(FieldKind::Checkbox), Control::Toggled);
711 for k in [
712 FieldKind::Text,
713 FieldKind::Secret,
714 FieldKind::Number,
715 FieldKind::Email,
716 FieldKind::Url,
717 FieldKind::Tel,
718 FieldKind::Textarea,
719 ] {
720 assert_eq!(control_shape(k), Control::Typed, "{k:?} is typed into");
721 }
722 }
723
724 #[test]
725 fn the_two_option_taking_kinds_are_drawn_differently_on_purpose() {
726 // The description holds Select and Radio apart, and a renderer that
727 // collapsed them would silently answer a question the app did not ask:
728 // audiofiles' storage style is irreversible and its alternatives have
729 // to be readable without opening anything. Asserting the two shapes
730 // differ is asserting that distinction survives the trip.
731 assert!(FieldKind::Select.offers_options());
732 assert!(FieldKind::Radio.offers_options());
733 assert_ne!(
734 control_shape(FieldKind::Select),
735 control_shape(FieldKind::Radio)
736 );
737 }
738
739 #[test]
740 fn a_hidden_field_draws_nothing_and_answers_nothing() {
741 // Where the two renderers legitimately part: a webview still emits an
742 // input because the form submits, and there is no form here.
743 let f = Field::new(FieldKind::Hidden, "id", "Id");
744 let p = palette(Color32::from_rgb(9, 9, 9));
745 egui::__run_test_ui(|ui| {
746 let drawn = field(ui, &f, Filling::Absent, None, &p, &FieldStyle::default());
747 assert!(drawn.is_none());
748 });
749 }
750
751 #[test]
752 fn a_disabled_field_stops_answering_and_a_focused_one_does_not() {
753 let f = Field::new(FieldKind::Text, "title", "Title");
754 let p = palette(Color32::from_rgb(9, 9, 9));
755 let style = FieldStyle::default();
756 egui::__run_test_ui(|ui| {
757 let mut text = String::from("x");
758 let disabled = field(
759 ui,
760 &f,
761 Filling::Text(&mut text),
762 Some(State::Disabled),
763 &p,
764 &style,
765 )
766 .unwrap();
767 assert!(!disabled.enabled());
768
769 let mut text = String::from("x");
770 let focused = field(
771 ui,
772 &f,
773 Filling::Text(&mut text),
774 Some(State::Focus),
775 &p,
776 &style,
777 )
778 .unwrap();
779 assert!(focused.enabled(), "focus is a thing you can still click");
780 });
781 }
782
783 #[test]
784 fn a_field_described_one_way_and_filled_another_is_drawn_inert() {
785 // No panic and no write-through. A checkbox handed a string cannot be
786 // filled, so it is drawn off and left alone.
787 let f = Field::new(FieldKind::Checkbox, "done", "Done");
788 let p = palette(Color32::from_rgb(9, 9, 9));
789 let mut text = String::from("untouched");
790 egui::__run_test_ui(|ui| {
791 let drawn = field(
792 ui,
793 &f,
794 Filling::Text(&mut text),
795 None,
796 &p,
797 &FieldStyle::default(),
798 );
799 assert!(drawn.is_some());
800 });
801 assert_eq!(text, "untouched");
802 }
803
804 #[test]
805 fn the_disclosure_belongs_to_the_form_and_not_to_the_field() {
806 let fields = [
807 Field::new(FieldKind::Text, "title", "Title"),
808 Field {
809 extended: true,
810 ..Field::new(FieldKind::Text, "notes", "Notes")
811 },
812 ];
813 let style = FieldStyle::default();
814
815 let mut closed = Vec::new();
816 egui::__run_test_ui(|ui| {
817 group(ui, &fields, false, &style, |_, f| closed.push(f.name));
818 });
819 assert_eq!(closed, ["title"]);
820
821 let mut open = Vec::new();
822 egui::__run_test_ui(|ui| {
823 group(ui, &fields, true, &style, |_, f| open.push(f.name));
824 });
825 assert_eq!(open, ["title", "notes"]);
826 }
827
828 #[test]
829 fn the_default_frame_is_square_and_one_point() {
830 let d = FrameStyle::default();
831 assert_eq!(d.radius, CornerRadius::ZERO);
832 assert_eq!(d.margin, Margin::ZERO);
833 assert!((d.stroke - 1.0).abs() < f32::EPSILON);
834 }
835}