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 substitutions: makeover
20//! derives `surface-well` and every consumer reads the real token. [`Palette`]
21//! is supplied by the caller already resolved.
22//!
23//! It picks no sizes either. Every radius, margin, stroke width and floor
24//! arrives in a style type ([`FrameStyle`], [`FieldStyle`], [`piece::PieceStyle`],
25//! [`table::TableStyle`], [`host::Metrics`]), and where one has a default it is
26//! the suite's number rather than this crate's: the focus ring and the target
27//! floor in [`host::Metrics`] default to what `makeover-webview` emits.
28//!
29//! `makeover` itself is linked only by the `theme` feature, for
30//! `Palette::from_theme`: it embeds every shipped theme file, and an app that
31//! resolves its own colours should not carry them.
32//!
33//! # The cascade is the real difference
34//!
35//! A stylesheet can say "a pressed button inverts its bevel" once and let the
36//! cascade carry it. An immediate-mode renderer has nowhere to put that, so
37//! every call site decides. [`makeover_layout::Depth::pressed`] is what keeps
38//! the decision from being re-derived per widget.
39//!
40//! # Overlays
41//!
42//! [`Palette::cast`] is what overlaying means in immediate mode. [`frame`] hands
43//! the cast shadow to the `egui::Frame` for any depth whose fill is
44//! [`Fill::Overlay`], keyed off the fill rather than the variant.
45//!
46//! # The table
47//!
48//! [`table`] draws `makeover_layout::CellPart`. Two things it forces, both named
49//! where they land:
50//!
51//! - **`egui_extras`**, this crate's one dependency past egui. egui has no
52//! table, and `Grid` gives no per-column sizing, no sticky header and no
53//! scroll sync. A third answer here would reimplement that crate worse.
54//! - **[`Palette::action`]**, on the footing [`Palette::content`] sits on: a
55//! link in a cell needs the action intent.
56//!
57//! Narrowing works differently from the terminal's and the module header says
58//! why: a content column cannot be measured before the app's closure has drawn
59//! it, so `egui_extras` sizes it and the declared floor budgets it.
60//!
61//! Three things are host idiom rather than description, which is why they land
62//! here and not in `makeover-layout`, and all three are answered on a handle the
63//! app never sees: the `egui_extras` row and builder this crate owns. That is
64//! [`table::cell`]'s reasoning again: what the app cannot reach, the renderer
65//! owes it.
66//!
67//! - **A selected row.** [`table::Body::selected`], a predicate asked per row,
68//! because `set_selected` is a method on the row. Without it a file list has
69//! no way to show what is selected, which is most of what a file list does.
70//! - **Scrolling a row into view.** [`table::Body::scroll_to`], because
71//! `scroll_to_row` is a method on the builder. A keyboard cursor that moves
72//! off-screen and stays there is the bug this prevents.
73//! - **Dragging a divider.** [`table::TableStyle::resizable`], which is a knob
74//! because egui_extras offers two settings here and a renderer can honestly
75//! make either choice.
76//!
77//! Cells are centred on the row's centre line, always, because there is no
78//! second honest answer and egui's own default (top-aligned) is the one thing it
79//! cannot be. That is not a knob.
80//!
81//! [`table::Body`] is also what splits a table's per-frame facts from its
82//! description and from its style. A row count, a selection and a scroll request
83//! are none of them style, and none of them survive the frame.
84//!
85//! # The nodes that are not fields, tables or frames
86//!
87//! [`piece`] draws a meter, a token, a control and a figure. The four are
88//! ordinary nodes, so without them a screen walk has to draw them itself, one
89//! copy per consumer.
90//!
91//! [`Palette`] carries the three status intents together rather than one per
92//! widget, for the reason [`Palette::fill`] is an `Option`: `Tone` is five
93//! members wide, and a resolver missing one has to invent a colour, which is a
94//! substitution this crate does not make.
95//! # Forms
96//!
97//! The field vocabulary sits on top of the depth vocabulary:
98//! [`makeover_layout::Field`] rendered to egui widgets, in [`field`], and a set
99//! of them laid down a column in [`group`].
100//!
101//! `makeover-webview`'s form emitter is the precedent, followed rather than
102//! re-derived, including the parts that are bug fixes: a
103//! select handed a value none of its options carries keeps that value visible
104//! instead of silently reading as the first option, which is a save-the-wrong-
105//! thing bug goingson hit for real.
106//!
107//! What differs is forced by the mode and not chosen:
108//!
109//! - **The value arrives as a `&mut`.** [`Editing`] borrows the app's own field
110//! and the widget writes through it. There is no DOM to read back out of,
111//! which is also why the description deliberately does not carry the value.
112//! - **A text control is drawn as a well and a select is not.** The description
113//! holds that a well is for anything the user looks *into*, and a text field
114//! is its own example; a select and a checkbox are pressed rather than looked
115//! into, so they keep egui's own control painting.
116//! - **Focus is not describable, and egui owns all of it here.** **Reach**,
117//! **focus** and the **focus ring** are this renderer's three answers and
118//! egui already has all three: its own id stack decides what is reachable,
119//! its own state decides what holds the keyboard, and it paints exactly one
120//! ring. A description states none of them, and drawing a second ring on top
121//! of egui's would break the one-ring rule. The terms
122//! are defined once in `makeover_layout`'s crate header, "Reach, focus and
123//! the focus ring". [`makeover_layout::State::Disabled`] *is* drawn, because
124//! egui has no opinion about it until told.
125//! - **App-level chrome is not drawn here, and it is not this crate's to
126//! draw.** `quasi-router` names the affordances that outlive one screen: a
127//! `Chrome` of key bindings, and an `Outcome::Over` for a screen drawn over
128//! another. Both are answered by `quasi-webview` and `quasi-tui`, and neither
129//! is answerable here, because this crate depends on `makeover-layout` and
130//! not on `quasi-router`: it is the peer of `makeover-webview` and
131//! `makeover-tui`, one layer below the renderers that consume a `Screen`.
132//! What is missing is the egui crate at *that* layer, which does not exist:
133//! nothing renders a quasi `Screen` in egui at all, and chrome is one item on
134//! the list such a crate would owe. Said here because this is where a reader
135//! looks for it, and because the silent version reads as "egui does not need
136//! a palette" rather than "nobody has built the renderer yet".
137
138//! # An interval is a sixth control shape
139//!
140//! [`FieldKind::Interval`] is drawn as `Control::Spanned`: two drag boxes on one
141//! row with the word `to` between them.
142//!
143//! - **Dragged rather than typed**, because that is what these controls already
144//! were. audiofiles' six filter axes are `DragValue` pairs sharing an extent,
145//! a speed and a suffix, and describing them into two text boxes would be a
146//! port that cost the app a control.
147//! - **One row, not two wells stacked.** Two wells are two questions on screen
148//! whatever the description says, and the arrangement is the whole content of
149//! the kind.
150//! - **An empty end reads as the bound it stands for.** An unset minimum sits
151//! on the low edge and stores no filter, which is what the shipped control
152//! did; egui's `DragValue` has no empty state, and a text box in its place
153//! would cost the app a control. With no extent to fall back on it reads
154//! zero, the one number this renderer invents, invented where the
155//! description declined to say anything.
156//! - **The word rather than a dash**, which on a signed axis is a minus sign.
157//! audiofiles filters loudness in dBFS.
158//!
159//! `Axis` holds the four facts both boxes share, because they are one axis:
160//! reading `min`, `max`, `step` and `unit` once is what stops the two ends
161//! drifting apart.
162//!
163//! # A number draws its unit
164//!
165//! [`Field::unit`], and this host is the one with somewhere better than the
166//! label to put it: egui's `Slider` draws a suffix beside its readout.
167//!
168//! So a slider takes it as a suffix, inside the control. A typed number has no
169//! readout of its own and takes it as a muted label after the box. Every other
170//! kind ignores it, and the description says which those are --
171//! `FieldKind::measurable`, rather than a `matches!` kept here.
172//!
173//! # The slider's track is a curve
174//!
175//! `makeover-layout` says what a slider is: a fraction and a function
176//! taking numbers to numbers, with `min` and `max` being `f(0)` and `f(1)`
177//! rather than the control's extent. This host has the easiest job of the
178//! three, because egui already has the control: `Slider::logarithmic` is a
179//! constant-ratio track, so the mapping is a builder call rather than an
180//! arithmetic of its own.
181//!
182//! Two things worth knowing. The granularity rides on the curve, so a range
183//! reads `Field::curve.step()` and every other kind reads `Field::step`; the
184//! step is in the value's own units under either curve, so the display
185//! precision derives from it directly. And the fallback for a ratio curve
186//! across zero is asked of `Curve::is_ratio` rather than matched on the
187//! variant, so this renderer and a terminal cannot disagree about when a
188//! logarithmic request is honoured.
189//!
190//! # The slider, the unanswered chooser, and the option that is not offered
191//! yet
192//!
193//! Three things a description can say here.
194//!
195//! - **[`FieldKind::Range`] is a fifth control shape**, `Control::Slid`, drawn
196//! with egui's `Slider`. A range missing an end falls back to a well rather
197//! than to invented bounds, which is what
198//! `makeover_layout::Field::bounded` is for.
199//! - **`Field::placeholder` reads on a chooser**, so a select with nothing
200//! chosen does not show an empty box.
201//! - **`Choice::unavailable` is drawn rather than dropped.** The option stays
202//! in the list, inert, with its precondition beside it instead of behind a
203//! hover. A greyed row with no reason reads as a dead end, which is the
204//! whole finding.
205//! - **`Choice::detail` is drawn under the option in a
206//! radio group and inside the row in a combo.** A closed chooser hides its
207//! list, so everything an option carries has to travel with its row; a group
208//! has a line to spare and putting a sentence beside the control instead
209//! would push every option's radio out of line with its neighbours.
210//!
211//! The value still arrives as a `&mut String` and a slider is a number, so the
212//! parse and the write-back are this renderer's, and the write happens only on
213//! a real drag: a value the app put there that this host cannot read survives
214//! being looked at.
215
216#![forbid(unsafe_code)]
217
218use egui::{
219 Color32, ComboBox, CornerRadius, DragValue, Margin, Painter, Rect, Response, RichText, Shape,
220 Slider, Stroke, TextEdit, Ui,
221};
222use makeover_layout::{
223 Bevel, Choice, Depth, Edge, Field, FieldKind, Fill, State, ThemeVariant, Tone,
224};
225use std::ops::RangeInclusive;
226
227pub mod host;
228pub mod piece;
229pub mod table;
230
231/// The resolved colours this renderer needs, as flat values.
232///
233/// Built by the app from whatever it already uses to resolve a theme, then
234/// held and reused. Deliberately not a trait and not string-keyed: a bevel is
235/// painted per widget per frame, and a map lookup per edge is a cost with
236/// nothing to show for it.
237///
238/// `#[non_exhaustive]`, so a colour added here is not a breaking change: build
239/// one with `Palette::from_theme` (the `theme` feature), or start from
240/// [`Palette::two_tone`] and set every colour the app resolves.
241#[derive(Debug, Clone, Copy, PartialEq, Eq)]
242#[non_exhaustive]
243pub struct Palette {
244 /// `surface-page`.
245 pub page: Color32,
246 /// `surface-raised`.
247 pub raised: Color32,
248 /// `surface-overlay`.
249 pub overlay: Color32,
250 /// `surface-well`.
251 ///
252 /// Required, not optional. makeover derives it for every theme, so a
253 /// resolved palette without a well is not a thing that exists here.
254 /// `makeover-tui` keeps its own `Option` for a different reason, since a
255 /// terminal can have the colour and still be unable to show it.
256 pub well: Color32,
257 /// `surface-sunken`.
258 ///
259 /// A surface set back from the one it sits on, by colour and nothing else.
260 /// Not a well: a well is a hole with an edge, and this has no edge. An
261 /// immediate-mode renderer paints an arbitrary rect, so unlike
262 /// `makeover-tui` it has no excuse for declining this one.
263 ///
264 /// Required rather than optional, on the same footing as `well`: all 31
265 /// themes makeover embeds author it.
266 pub sunken: Color32,
267 /// `bevel-light`.
268 pub bevel_light: Color32,
269 /// `bevel-dark`.
270 pub bevel_dark: Color32,
271 /// `elevation`.
272 ///
273 /// What a surface that floats OVER the page is cast onto it with. The one
274 /// intent here that is about a surface's relationship to the page rather
275 /// than about the surface, which is why it is a translucent near-black on
276 /// every theme rather than something read off the palette's own ramp.
277 ///
278 /// **Only for a surface that overlays.** A menu, a tooltip, a modal. A
279 /// surface *in* the layout takes a bevel, and reaching for this on a panel
280 /// or a card is how a pre-Platinum look survives a conversion under a new
281 /// name.
282 ///
283 /// egui has a real answer for this where a terminal does not: see
284 /// [`Palette::cast`], which is the shadow to hand an
285 /// [`egui::Frame`].
286 pub elevation: Color32,
287 /// `content`.
288 ///
289 /// Ordinary text.
290 pub content: Color32,
291 /// `content-secondary`.
292 ///
293 /// Inactive but usable: it still answers a press. The middle tone of the
294 /// three (wiki `three-tone-convention`), and the one an unchosen option in
295 /// a choice field takes.
296 ///
297 /// Not [`content_muted`](Self::content_muted), which carries a claim:
298 /// `State::Disabled` resolves to it, so a live control wearing it tells the
299 /// user it will not answer. `makeover-tui` draws the same widget the same
300 /// way from `makeover-tui@230bf63`.
301 ///
302 /// A step of `content` toward the page, derived at load by `makeover`
303 /// rather than authored, so it is read off the resolved theme here like
304 /// any other token and never re-derived.
305 pub content_secondary: Color32,
306 /// `content-muted`.
307 ///
308 /// A field's hint, and what
309 /// [`makeover_layout::State::Disabled`]
310 /// resolves to. Both readings come from the description rather than from
311 /// here: `State::Disabled` names this intent by token.
312 pub content_muted: Color32,
313 /// `action-primary`.
314 ///
315 /// What a control is drawn in.
316 ///
317 /// This is the intent [`CellPart`](makeover_layout::CellPart) exists to
318 /// separate. A cell holding a control that takes the cell's text colour is
319 /// the drift `CellPart` names.
320 pub action: Color32,
321 /// `content-on-action`: ink that stays readable on [`action`](Self::action).
322 ///
323 /// Derived by the theme with `readable_on(action)` rather than picked here,
324 /// so a theme whose action hue is pale gets dark ink without this renderer
325 /// knowing which themes those are.
326 ///
327 /// The one thing that fills with `action` is the act a screen is for
328 /// ([`makeover_layout::Act::leading`]), which is why this arrived with it.
329 /// A renderer that fills with the accent and leaves the label on the
330 /// ordinary content colour is one theme change away from unreadable.
331 pub content_on_action: Color32,
332 /// `danger`.
333 ///
334 /// A field's error message, a destructive control, a bar that has run over.
335 pub danger: Color32,
336 /// `success`.
337 ///
338 /// The three status intents arrive together and not one at a time:
339 /// [`Tone`] is five members wide and a resolver missing one has to invent
340 /// a colour for it, which is the substitution [`Palette::fill`] refuses.
341 pub success: Color32,
342 /// `warning`.
343 pub warning: Color32,
344 /// `info`.
345 pub info: Color32,
346 /// `border`, the authored line colour.
347 ///
348 /// A neutral badge's edge: a badge on the raised ground is raised too, so
349 /// the edge is what draws it.
350 pub border: Color32,
351 /// `info-surface`: raised with 12 percent of `info`. A badge's fill.
352 ///
353 /// The four tone surfaces arrive together for the status intents' reason.
354 pub info_surface: Color32,
355 /// `success-surface`.
356 pub success_surface: Color32,
357 /// `warning-surface`.
358 pub warning_surface: Color32,
359 /// `danger-surface`.
360 pub danger_surface: Color32,
361 /// `row-hover`: the row under the pointer, at 9 percent.
362 pub row_hover: Color32,
363 /// `row-rule`: the hairline between rows and around a table, at 26
364 /// percent.
365 pub row_rule: Color32,
366 /// `row-selected`: a selected row, raised with 18 percent of the accent.
367 ///
368 /// A fill and never a foreground, so a row that is red for a failure stays
369 /// red while it is selected.
370 pub row_selected: Color32,
371}
372
373impl Palette {
374 /// Every surface `page` and every ink `ink`, with no cast shadow.
375 ///
376 /// A starting point for the setters, legible on its own and wrong in every
377 /// detail a theme decides: an app that resolves its own colours starts here
378 /// and sets each one, and a colour added to this type later arrives at one
379 /// of these two rather than as a compile error in every consumer.
380 #[must_use]
381 pub const fn two_tone(page: Color32, ink: Color32) -> Self {
382 Self {
383 page,
384 raised: page,
385 overlay: page,
386 well: page,
387 sunken: page,
388 bevel_light: page,
389 bevel_dark: ink,
390 elevation: Color32::TRANSPARENT,
391 content: ink,
392 content_secondary: ink,
393 content_muted: ink,
394 action: ink,
395 content_on_action: page,
396 danger: ink,
397 success: ink,
398 warning: ink,
399 info: ink,
400 border: ink,
401 info_surface: page,
402 success_surface: page,
403 warning_surface: page,
404 danger_surface: page,
405 row_hover: page,
406 row_rule: ink,
407 row_selected: page,
408 }
409 }
410
411 /// Set [`page`](Self::page).
412 #[must_use]
413 pub const fn page(mut self, colour: Color32) -> Self {
414 self.page = colour;
415 self
416 }
417
418 /// Set [`raised`](Self::raised).
419 #[must_use]
420 pub const fn raised(mut self, colour: Color32) -> Self {
421 self.raised = colour;
422 self
423 }
424
425 /// Set [`overlay`](Self::overlay).
426 #[must_use]
427 pub const fn overlay(mut self, colour: Color32) -> Self {
428 self.overlay = colour;
429 self
430 }
431
432 /// Set [`well`](Self::well).
433 #[must_use]
434 pub const fn well(mut self, colour: Color32) -> Self {
435 self.well = colour;
436 self
437 }
438
439 /// Set [`sunken`](Self::sunken).
440 #[must_use]
441 pub const fn sunken(mut self, colour: Color32) -> Self {
442 self.sunken = colour;
443 self
444 }
445
446 /// Set [`bevel_light`](Self::bevel_light).
447 #[must_use]
448 pub const fn bevel_light(mut self, colour: Color32) -> Self {
449 self.bevel_light = colour;
450 self
451 }
452
453 /// Set [`bevel_dark`](Self::bevel_dark).
454 #[must_use]
455 pub const fn bevel_dark(mut self, colour: Color32) -> Self {
456 self.bevel_dark = colour;
457 self
458 }
459
460 /// Set [`elevation`](Self::elevation).
461 #[must_use]
462 pub const fn elevation(mut self, colour: Color32) -> Self {
463 self.elevation = colour;
464 self
465 }
466
467 /// Set [`content`](Self::content).
468 #[must_use]
469 pub const fn content(mut self, colour: Color32) -> Self {
470 self.content = colour;
471 self
472 }
473
474 /// Set [`content_secondary`](Self::content_secondary).
475 #[must_use]
476 pub const fn content_secondary(mut self, colour: Color32) -> Self {
477 self.content_secondary = colour;
478 self
479 }
480
481 /// Set [`content_muted`](Self::content_muted).
482 #[must_use]
483 pub const fn content_muted(mut self, colour: Color32) -> Self {
484 self.content_muted = colour;
485 self
486 }
487
488 /// Set [`action`](Self::action).
489 #[must_use]
490 pub const fn action(mut self, colour: Color32) -> Self {
491 self.action = colour;
492 self
493 }
494
495 /// Set [`content_on_action`](Self::content_on_action).
496 #[must_use]
497 pub const fn content_on_action(mut self, colour: Color32) -> Self {
498 self.content_on_action = colour;
499 self
500 }
501
502 /// Set [`danger`](Self::danger).
503 #[must_use]
504 pub const fn danger(mut self, colour: Color32) -> Self {
505 self.danger = colour;
506 self
507 }
508
509 /// Set [`success`](Self::success).
510 #[must_use]
511 pub const fn success(mut self, colour: Color32) -> Self {
512 self.success = colour;
513 self
514 }
515
516 /// Set [`warning`](Self::warning).
517 #[must_use]
518 pub const fn warning(mut self, colour: Color32) -> Self {
519 self.warning = colour;
520 self
521 }
522
523 /// Set [`info`](Self::info).
524 #[must_use]
525 pub const fn info(mut self, colour: Color32) -> Self {
526 self.info = colour;
527 self
528 }
529
530 /// Set [`border`](Self::border).
531 #[must_use]
532 pub const fn border(mut self, colour: Color32) -> Self {
533 self.border = colour;
534 self
535 }
536
537 /// Set [`info_surface`](Self::info_surface).
538 #[must_use]
539 pub const fn info_surface(mut self, colour: Color32) -> Self {
540 self.info_surface = colour;
541 self
542 }
543
544 /// Set [`success_surface`](Self::success_surface).
545 #[must_use]
546 pub const fn success_surface(mut self, colour: Color32) -> Self {
547 self.success_surface = colour;
548 self
549 }
550
551 /// Set [`warning_surface`](Self::warning_surface).
552 #[must_use]
553 pub const fn warning_surface(mut self, colour: Color32) -> Self {
554 self.warning_surface = colour;
555 self
556 }
557
558 /// Set [`danger_surface`](Self::danger_surface).
559 #[must_use]
560 pub const fn danger_surface(mut self, colour: Color32) -> Self {
561 self.danger_surface = colour;
562 self
563 }
564
565 /// Set [`row_hover`](Self::row_hover).
566 #[must_use]
567 pub const fn row_hover(mut self, colour: Color32) -> Self {
568 self.row_hover = colour;
569 self
570 }
571
572 /// Set [`row_rule`](Self::row_rule).
573 #[must_use]
574 pub const fn row_rule(mut self, colour: Color32) -> Self {
575 self.row_rule = colour;
576 self
577 }
578
579 /// Set [`row_selected`](Self::row_selected).
580 #[must_use]
581 pub const fn row_selected(mut self, colour: Color32) -> Self {
582 self.row_selected = colour;
583 self
584 }
585
586 /// Every colour, read from a resolved makeover theme.
587 ///
588 /// # Errors
589 ///
590 /// [`MissingToken`] naming the first token the theme does not resolve.
591 /// makeover derives every one of these for every shipped theme, so this
592 /// fails only on a theme file missing a base intent.
593 #[cfg(feature = "theme")]
594 pub fn from_theme(tokens: &makeover::SemanticTokens) -> Result<Self, MissingToken> {
595 use makeover::Token;
596 let colour = |token: Token| {
597 tokens
598 .rgba(token)
599 .map(|(r, g, b, a)| Color32::from_rgba_unmultiplied(r, g, b, a))
600 .ok_or(MissingToken(token))
601 };
602 Ok(Self {
603 page: colour(Token::SurfacePage)?,
604 raised: colour(Token::SurfaceRaised)?,
605 overlay: colour(Token::SurfaceOverlay)?,
606 well: colour(Token::SurfaceWell)?,
607 sunken: colour(Token::SurfaceSunken)?,
608 bevel_light: colour(Token::BevelLight)?,
609 bevel_dark: colour(Token::BevelDark)?,
610 elevation: colour(Token::Elevation)?,
611 content: colour(Token::Content)?,
612 content_secondary: colour(Token::ContentSecondary)?,
613 content_muted: colour(Token::ContentMuted)?,
614 action: colour(Token::Action)?,
615 content_on_action: colour(Token::ContentOnAction)?,
616 danger: colour(Token::Danger)?,
617 success: colour(Token::Success)?,
618 warning: colour(Token::Warning)?,
619 info: colour(Token::Info)?,
620 border: colour(Token::Border)?,
621 info_surface: colour(Token::InfoSurface)?,
622 success_surface: colour(Token::SuccessSurface)?,
623 warning_surface: colour(Token::WarningSurface)?,
624 danger_surface: colour(Token::DangerSurface)?,
625 row_hover: colour(Token::RowHover)?,
626 row_rule: colour(Token::RowRule)?,
627 row_selected: colour(Token::RowSelected)?,
628 })
629 }
630}
631
632/// A token `Palette::from_theme` needed and the theme did not resolve.
633#[cfg(feature = "theme")]
634#[derive(Debug, Clone, Copy, PartialEq, Eq)]
635pub struct MissingToken(pub makeover::Token);
636
637#[cfg(feature = "theme")]
638impl std::fmt::Display for MissingToken {
639 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
640 write!(f, "the theme resolves no `{}`", self.0.as_str())
641 }
642}
643
644#[cfg(feature = "theme")]
645impl std::error::Error for MissingToken {}
646
647impl Palette {
648 /// Resolve a surface intent, or `None` for one this renderer does not know.
649 ///
650 /// A plain lookup, and no substitution.
651 ///
652 /// `Option`, because [`Fill`] is `#[non_exhaustive]` and a total function
653 /// over an open enum can only stay total by inventing a colour for a member
654 /// it has never heard of. Every member the description has today is
655 /// answered with `Some`.
656 #[must_use]
657 pub const fn fill(&self, fill: Fill) -> Option<Color32> {
658 match fill {
659 Fill::Page => Some(self.page),
660 Fill::Raised => Some(self.raised),
661 Fill::Overlay => Some(self.overlay),
662 Fill::Well => Some(self.well),
663 Fill::Sunken => Some(self.sunken),
664 _ => None,
665 }
666 }
667
668 /// The colour a [`Tone`] reads as.
669 ///
670 /// Total, unlike [`fill`](Self::fill), and the difference is not an
671 /// inconsistency. `Fill` is `#[non_exhaustive]` and `Tone` is not: the
672 /// description layer settled tone at five members and grows surfaces, so a
673 /// total function here cannot be made to invent a colour by an upstream
674 /// release the way a total `fill` could.
675 ///
676 /// [`Tone::Neutral`] is [`content`](Self::content) rather than a colour of
677 /// its own, which is what "an ordinary fact" means: a neutral badge is text
678 /// in a box, not a fifth status.
679 #[must_use]
680 pub const fn tone(&self, tone: Tone) -> Color32 {
681 match tone {
682 Tone::Neutral => self.content,
683 Tone::Info => self.info,
684 Tone::Success => self.success,
685 Tone::Warning => self.warning,
686 Tone::Danger => self.danger,
687 // A tone this renderer has not learnt yet reads as an ordinary
688 // fact rather than as a status it might misstate.
689 _ => self.content,
690 }
691 }
692
693 /// What a badge of this tone is filled with: its tone surface, or the
694 /// raised surface for [`Tone::Neutral`], as `makeover-webview` fills one.
695 #[must_use]
696 pub const fn tone_surface(&self, tone: Tone) -> Color32 {
697 match tone {
698 Tone::Neutral => self.raised,
699 Tone::Info => self.info_surface,
700 Tone::Success => self.success_surface,
701 Tone::Warning => self.warning_surface,
702 Tone::Danger => self.danger_surface,
703 _ => self.raised,
704 }
705 }
706
707 /// What a badge of this tone is edged with: its tone, or
708 /// [`border`](Self::border) for [`Tone::Neutral`], whose tone is the ink.
709 #[must_use]
710 pub const fn tone_edge(&self, tone: Tone) -> Color32 {
711 match tone {
712 Tone::Neutral => self.border,
713 other => self.tone(other),
714 }
715 }
716
717 /// The cast shadow for a surface that overlays the page.
718 ///
719 /// What "overlaying" means in immediate mode, answered rather than skipped.
720 /// egui already paints shadows for its menus and windows through
721 /// [`egui::Frame::shadow`], so the honest port is to hand that machinery the
722 /// theme's tone instead of egui's own default, not to invent a painter here
723 /// the way [`paint_bevel`] had to.
724 ///
725 /// The geometry matches what `makeover-webview` composes, in points rather
726 /// than pixels: a small downward offset and a wide soft blur. A Platinum-era
727 /// menu sits just off the page rather than hovering above it.
728 ///
729 /// ```no_run
730 /// # let palette: makeover_immediate::Palette = unimplemented!();
731 /// # let ui: &mut egui::Ui = unimplemented!();
732 /// egui::Frame::popup(ui.style())
733 /// .shadow(palette.cast())
734 /// .show(ui, |ui| { ui.label("over the page"); });
735 /// ```
736 #[must_use]
737 pub const fn cast(&self) -> egui::Shadow {
738 egui::Shadow {
739 offset: [0, 2],
740 blur: 24,
741 spread: 0,
742 color: self.elevation,
743 }
744 }
745
746 /// Resolve a bevel edge intent.
747 #[must_use]
748 pub const fn edge(&self, edge: Edge) -> Color32 {
749 match edge {
750 Edge::Light => self.bevel_light,
751 Edge::Dark => self.bevel_dark,
752 // An edge this renderer has not learnt is drawn as the border, the
753 // one line every surface already has.
754 _ => self.border,
755 }
756 }
757}
758
759/// The geometry a framed region is drawn with.
760///
761/// Every field is a value, which is why they all arrive from the caller:
762/// radius and border width belong to `makeover-geometry`, and margins come
763/// from its relational gaps.
764#[derive(Debug, Clone, Copy, PartialEq)]
765pub struct FrameStyle {
766 /// Corner radius. Square under the Platinum default.
767 pub radius: CornerRadius,
768 /// Inner margin between the frame and its contents.
769 pub margin: Margin,
770 /// Bevel stroke width, in points.
771 pub stroke: f32,
772}
773
774impl Default for FrameStyle {
775 /// A one-point square frame with no inner margin.
776 fn default() -> Self {
777 Self {
778 radius: CornerRadius::ZERO,
779 margin: Margin::ZERO,
780 stroke: 1.0,
781 }
782 }
783}
784
785/// Paint a two-tone edge just inside `rect`.
786///
787/// Fill first, bevel after: this adds two polylines and nothing else, so it
788/// composes over whatever is already there. That is what lets it go over an
789/// [`egui::TextEdit`] after `ui.add`, where the widget's own fill has landed.
790///
791/// Two three-point polylines meeting at opposite corners, rather than four
792/// segments, so egui mitres the corner joins instead of leaving a notch.
793///
794/// The dark polyline is drawn second, so the two corners where the runs meet
795/// take its tone. That is the right answer here rather than a concession.
796/// [`makeover_layout::Bevel`] holds those corners to belong to both edges, and
797/// a renderer with room to divide one should; at the default one-point stroke
798/// the corner is a one-point square, so the division is sub-pixel and
799/// antialiasing resolves it to the same blend the mitre already gives. Splitting
800/// it would add a seam and no information. `makeover-tui` does split, because a
801/// terminal cell is large enough that not splitting costs a visible cell of edge
802/// weight. The same rule, at a resolution where it has something to say.
803pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) {
804 let (top_left, bottom_right) = bevel.edges();
805
806 // Inset by half a stroke so the line lands inside `rect` rather than
807 // straddling its edge, which on a fractional-scale display is the
808 // difference between one crisp pixel and two dim ones.
809 let r = rect.shrink(stroke / 2.0);
810
811 painter.add(Shape::line(
812 vec![r.left_bottom(), r.left_top(), r.right_top()],
813 Stroke::new(stroke, palette.edge(top_left)),
814 ));
815 // Three points close the box, two leave the bottom open: the shaded run
816 // comes down the right side and stops. That is the folder tab, and it is
817 // the same edge the browser draws by dropping the shadow's vertical
818 // offset. The lit polyline is untouched either way, so the join is the
819 // only thing that changes.
820 let shaded = if bevel.draws_bottom() {
821 vec![r.right_top(), r.right_bottom(), r.left_bottom()]
822 } else {
823 vec![r.right_top(), r.right_bottom()]
824 };
825 painter.add(Shape::line(
826 shaded,
827 Stroke::new(stroke, palette.edge(bottom_right)),
828 ));
829}
830
831/// Draw a region at a given [`Depth`]: its fill and its edge, together.
832///
833/// [`Depth::Flat`] gets neither, and inherits whatever it sits on. That is the
834/// difference between level-with and painted-the-same-colour, and it is the
835/// reason `Depth::fill` returns an [`Option`] rather than defaulting to the
836/// page.
837pub fn frame<R>(
838 ui: &mut Ui,
839 depth: Depth,
840 palette: &Palette,
841 style: FrameStyle,
842 add_contents: impl FnOnce(&mut Ui) -> R,
843) -> R {
844 let mut f = egui::Frame::new()
845 .corner_radius(style.radius)
846 .inner_margin(style.margin);
847 // Two ways there is no fill to paint, and they collapse to the same
848 // outcome: the depth names none (Depth::Flat), or it names one this
849 // renderer cannot resolve. Either way the frame goes unfilled and the
850 // bevel below carries the depth on its own, which is the rule this
851 // module already documents for Flat.
852 if let Some(fill) = depth.fill().and_then(|f| palette.fill(f)) {
853 f = f.fill(fill);
854 }
855 // A surface that overlays the page is cast onto it, with
856 // [`Palette::cast`]. Keyed off the fill rather than the variant, so it stays right for whatever else the description calls an
857 // overlay later.
858 if depth.fill() == Some(Fill::Overlay) {
859 f = f.shadow(palette.cast());
860 }
861 let framed = f.show(ui, add_contents);
862 if let Some(bevel) = depth.bevel() {
863 paint_bevel(
864 ui.painter(),
865 framed.response.rect,
866 bevel,
867 palette,
868 style.stroke,
869 );
870 }
871 framed.inner
872}
873
874/// The geometry a field group is drawn with.
875///
876/// Values again, for the reason [`FrameStyle`] is: every number here belongs to
877/// `makeover-geometry` and arrives already resolved.
878#[derive(Debug, Clone, Copy, PartialEq)]
879pub struct FieldStyle {
880 /// The well a text control sits in.
881 pub frame: FrameStyle,
882 /// Between a field's own parts: its label, its control, its hint and its
883 /// error.
884 pub gap: f32,
885 /// Between one field and the next.
886 pub group_gap: f32,
887 /// What marks a required field, appended to its label.
888 ///
889 /// A knob rather than a constant, because it is the one piece of *copy* in
890 /// this crate and copy is not a renderer's call. A webview does not need it
891 /// at all (it emits the `required` attribute and the browser answers), so
892 /// this renderer is the first place where a compulsory field either shows
893 /// that it is or silently does not.
894 pub required_marker: &'static str,
895}
896
897impl Default for FieldStyle {
898 /// The default frame, no gaps, and an asterisk.
899 fn default() -> Self {
900 Self {
901 frame: FrameStyle::default(),
902 gap: 0.0,
903 group_gap: 0.0,
904 required_marker: "*",
905 }
906 }
907}
908
909/// What the field currently holds, borrowed from wherever the app keeps it.
910///
911/// The editable counterpart of [`makeover_layout::Value`], which is what the
912/// other renderers read: there the value is read back after the fact, and here
913/// the widget writes through this borrow as it is edited. The description
914/// carries neither, for the same reason.
915///
916/// An enum rather than a bag of options, on the reasoning
917/// [`makeover_layout::Value`] records: a checkbox holding a string is
918/// unsayable here, where a struct would let it be said and then have to cope.
919///
920/// `#[non_exhaustive]`: a host builds these and never matches on them, so the
921/// next shape of held value costs nobody a match arm.
922#[derive(Debug, Default)]
923#[non_exhaustive]
924pub enum Editing<'a> {
925 /// Nothing to edit. The control is drawn and does not answer.
926 #[default]
927 Absent,
928 /// The buffer behind anything that takes typed text, a select included:
929 /// what a select holds is the `value` of one of its [`Choice`]s.
930 ///
931 /// [`Choice`]: makeover_layout::Choice
932 Text(&'a mut String),
933 /// A checkbox, on or off.
934 On(&'a mut bool),
935 /// The values of a [`FieldKind::Checklist`]'s ticked options.
936 ///
937 /// The values rather than a bool per option, because the options are the
938 /// description's and the set is the app's: a host keeps what was ticked
939 /// under the option values it submits, and a parallel list of bools would
940 /// have to be re-aligned with the options every time the list changed.
941 /// Ticking pushes the option's value and unticking removes it, so the order
942 /// is the order things were ticked in, which is no order a handler should
943 /// read anything into.
944 Ticked(&'a mut Vec<String>),
945 /// The two buffers behind a [`FieldKind::Interval`], lower first.
946 ///
947 /// Two buffers rather than one string with a separator, which is
948 /// [`makeover_layout::Field::upper_name`]'s reason one level down: an
949 /// interval is submitted under two names, so it is edited as two values,
950 /// and a delimiter this crate owned could appear inside either of them.
951 ///
952 /// Either end may be empty while the other stands. An open end is an
953 /// answer ("over 120 BPM") rather than a half-filled box.
954 Between {
955 /// The lower end's buffer.
956 lower: &'a mut String,
957 /// The upper end's buffer.
958 upper: &'a mut String,
959 },
960}
961
962/// The four shapes a control comes in here, which is fewer than there are
963/// kinds.
964///
965/// [`FieldKind`] is `#[non_exhaustive]` and grows; this does not, because the
966/// ways egui has of asking for a value do not. Reducing the open set to this
967/// closed one in one total function is what keeps a new kind from needing a new
968/// arm at every match below.
969#[derive(Debug, Clone, Copy, PartialEq, Eq)]
970enum Control {
971 /// Typed into, so it is drawn as a well: the user looks into it.
972 Typed,
973 /// Picked from a control that shows one option at a time. Pressed rather
974 /// than looked into, so egui's own control painting stands.
975 Chosen,
976 /// Picked from options that are all on screen at once.
977 ///
978 /// Apart from [`Chosen`](Self::Chosen) because the description holds them
979 /// apart, and holding them apart is the whole content of
980 /// [`FieldKind::Radio`]: same question, and an answer the user can read
981 /// without opening anything.
982 Listed,
983 /// Ticked from options that are all on screen at once, as many as apply.
984 ///
985 /// Apart from [`Listed`](Self::Listed) because picking one leaves the
986 /// others standing, and apart from [`Toggled`](Self::Toggled) because it is
987 /// one question: [`FieldKind::Checklist`] asks it above its boxes, where a
988 /// checkbox is its own label.
989 Ticked,
990 /// Held on or off.
991 Toggled,
992 /// Dragged across an extent that is on screen the whole time.
993 ///
994 /// Apart from [`Typed`](Self::Typed) for the reason
995 /// [`FieldKind::Range`] is apart from `Number`: the two ends are what the
996 /// question means, so a well with a figure in it is not a quieter version
997 /// of this control, it is a different one.
998 Slid,
999 /// Picked from a list of themes that arrives grouped and marked.
1000 ///
1001 /// Apart from [`Chosen`](Self::Chosen) rather than folded into it, and the
1002 /// distinction is the same one [`Listed`](Self::Listed) draws: it is not a
1003 /// different question, it is a different amount of structure on screen. A
1004 /// theme picker's rows carry a group heading and a contrast mark, and both
1005 /// come from members [`Field::options`] does not have, so a shared arm
1006 /// would be a `matches!` on the kind inside the loop rather than one arm
1007 /// less.
1008 Themed,
1009 /// Two values dragged across one axis, drawn as one question.
1010 ///
1011 /// Apart from [`Typed`](Self::Typed) for the reason
1012 /// [`FieldKind::Interval`] is apart from `Number`: two wells one under the
1013 /// other are two questions on screen, whatever the description says, and
1014 /// the arrangement is the whole content of the kind.
1015 Spanned,
1016}
1017
1018/// Which shape a kind takes.
1019///
1020/// The wildcard falls to [`Control::Typed`] on purpose: a kind added to the
1021/// description since this renderer was built degrades to a text box, which
1022/// accepts any value the others would, rather than to nothing drawn at all.
1023///
1024/// `FieldKind::File` lands there rather than growing a shape of its own. egui's
1025/// honest answer is a button that opens a native picker, which is a fifth
1026/// control and a file-dialog dependency, and no consumer of this crate asks for
1027/// a file field. The membership test is that every renderer *could* answer
1028/// honestly, not that each one does on the day. A path in a text box is not
1029/// nothing.
1030///
1031/// `Field::accept` and `Field::multiple` land on the same position: both are the picker's arguments, and this
1032/// renderer has no picker to give them to. They are not lost: the description
1033/// still carries them, and the day the native dialog arrives here it is opened
1034/// with them rather than with a filter written twice.
1035///
1036/// `FieldKind::Date` and `FieldKind::DateTime` land there too, on the same
1037/// footing and with one thing owed. A
1038/// calendar is a sixth control and bare `egui` has none, so a typed value is
1039/// the honest answer here; what the app gets is the format the description
1040/// names, `makeover_layout::DATE_FORMAT` and `DATETIME_FORMAT`, which is why
1041/// those are constants rather than a sentence. audiofiles is the only consumer
1042/// of this crate and asks for neither today. A calendar popup is the upgrade
1043/// whenever one does.
1044///
1045/// `Field::as_instant` is carried and not honoured, on
1046/// the same footing. It asks for the typed wall-clock value to be submitted as
1047/// the moment it names, and this renderer has no submission to convert on: it
1048/// draws the control and the app reads the value back, so the conversion would
1049/// belong wherever that read happens rather than here. What the app gets is the
1050/// local value in `DATETIME_FORMAT`, which is what it got before the member
1051/// existed. No described site on this host asks for it today.
1052/// One row of a closed chooser, as the single string it has room for.
1053///
1054/// A combo hides its list, so everything an option carries has to travel with
1055/// the row it belongs to: there is no second line to put a detail on and no
1056/// space beside the row to put a reason in. That is the same constraint a
1057/// `<select>`'s option has in the webview, and it takes the same answer.
1058///
1059/// The order is what the option *is* before why it cannot be picked, which is
1060/// the order the two read in and the order the radio group draws them in.
1061fn combo_row(opt: &Choice<'_>) -> String {
1062 let mut text = opt.label.to_owned();
1063 for extra in [opt.detail, opt.unavailable].into_iter().flatten() {
1064 text.push_str(" ");
1065 text.push_str(extra);
1066 }
1067 text
1068}
1069
1070/// How far an option's second line is inset, in points.
1071///
1072/// The width of egui's radio button plus the gap after it, so the line starts under the label rather than under the control. A
1073/// magnitude, which is `makeover-geometry`'s subject and not this crate's --
1074/// but this one is measured off a widget egui draws and sizes, so there is
1075/// nothing for a spacing scale to say about it.
1076const OPTION_DETAIL_INDENT: f32 = 22.0;
1077
1078const fn control_shape(kind: FieldKind) -> Control {
1079 match kind {
1080 FieldKind::Select => Control::Chosen,
1081 FieldKind::Radio => Control::Listed,
1082 FieldKind::Checklist => Control::Ticked,
1083 FieldKind::Checkbox => Control::Toggled,
1084 FieldKind::Range => Control::Slid,
1085 FieldKind::Interval => Control::Spanned,
1086 FieldKind::Theme => Control::Themed,
1087 _ => Control::Typed,
1088 }
1089}
1090
1091/// The shape the field actually gets, which is the kind's unless the field is
1092/// missing what that shape needs.
1093///
1094/// One case, and `makeover-layout` names it: a [`FieldKind::Range`] carries its
1095/// extent in [`Field::min`] and [`Field::max`], and a range missing an end has
1096/// nothing to slide across. egui's `Slider` demands a `RangeInclusive`, so
1097/// inventing one would be this renderer picking bounds the app never stated and
1098/// the user then dragging against them.
1099///
1100/// It falls back to [`Control::Typed`], which is where every kind this renderer
1101/// cannot draw natively already lands: a number in a well is a true report of
1102/// the value and takes any answer the slider would.
1103fn shape_of(field: &Field<'_>) -> Control {
1104 match control_shape(field.kind) {
1105 Control::Slid if !field.bounded() => Control::Typed,
1106 shape => shape,
1107 }
1108}
1109
1110/// The two ends of a range, as egui wants them.
1111///
1112/// `None` when either end is missing or is not a number this host can read.
1113/// The description carries the bounds as text on purpose (the bound of a date
1114/// is a date), so parsing them is the renderer's job and failing to is a real
1115/// outcome rather than an assertion.
1116///
1117/// A bound that parses but is not finite (`inf`, `NaN`, `1e400`) is not a
1118/// number this host can read either: egui's slider asserts on it in debug and
1119/// writes `NaN` back into the app's value in release.
1120fn extent(field: &Field<'_>) -> Option<RangeInclusive<f64>> {
1121 let min = field.min?.parse::<f64>().ok().filter(|n| n.is_finite())?;
1122 let max = field.max?.parse::<f64>().ok().filter(|n| n.is_finite())?;
1123 Some(min..=max)
1124}
1125
1126/// The step as a number, the way HTML reads `step`.
1127///
1128/// `any` is no step, and so is anything that is not a finite number above
1129/// zero: HTML ignores an invalid step rather than refusing the input, and
1130/// the webview hands the string to the browser, so this matches what the
1131/// same field does there.
1132fn step_value(step: Option<&str>) -> Option<f64> {
1133 step?
1134 .trim()
1135 .parse::<f64>()
1136 .ok()
1137 .filter(|n| n.is_finite() && *n > 0.0)
1138}
1139
1140/// The most decimals a step is read to, which is `f64`'s own precision and
1141/// under emath's limit.
1142const MAX_DECIMALS: usize = 15;
1143
1144/// How many decimals to write a dragged value back with.
1145///
1146/// Read off [`Field::step`], which is the only thing that says what
1147/// granularity the question has: a step of `0.01` is a two-decimal question and
1148/// a step of `1` is a whole-number one. Without a step the host's own
1149/// granularity stands, and egui's is continuous, so the value is written back
1150/// at whatever precision it round-trips at.
1151///
1152/// Read off the number rather than the spelling, so `1e-3` is three decimals
1153/// like `0.001`, and `any` or a step that is not a number is none: it takes
1154/// egui's continuous granularity, which is what HTML does with it.
1155fn decimals(step: Option<&str>) -> Option<usize> {
1156 let step = step_value(step)?;
1157 // The shortest decimal that round-trips, which is how the step was
1158 // written, and its digits after the point are the precision it asks for.
1159 let written = format!("{step}");
1160 Some(
1161 written
1162 .split_once('.')
1163 .map_or(0, |(_, fraction)| fraction.len())
1164 .min(MAX_DECIMALS),
1165 )
1166}
1167
1168/// A dragged number as the text written back, or `None` when there is no
1169/// number to write. egui can hand back `NaN` from a range it could not
1170/// resolve, and an app's value should keep what it had rather than read "NaN".
1171fn written_back(number: f64, step: Option<&str>) -> Option<String> {
1172 if !number.is_finite() {
1173 return None;
1174 }
1175 Some(match decimals(step) {
1176 Some(places) => format!("{number:.places$}"),
1177 None => number.to_string(),
1178 })
1179}
1180
1181/// What a select shows for the value it currently holds.
1182///
1183/// A value no option carries stays on screen as itself rather than reading as
1184/// whichever option happens to be first. goingson saved a backup retention of
1185/// 10 against a 1/3/7/14/0 list and the browser silently showed it as 1, so the
1186/// next save wrote a value nobody chose; `makeover-webview` grew the fix as a
1187/// stray `<option>` and this is the same fix in the shape egui allows.
1188///
1189/// The empty value is the one case that reads as unanswered rather than as an
1190/// answer, and [`chosen_text`] is what puts the field's ghost text there.
1191fn shown_label<'a>(options: &'a [Choice<'a>], value: &'a str) -> &'a str {
1192 options
1193 .iter()
1194 .find(|opt| opt.value == value)
1195 .map_or(value, |opt| opt.label)
1196}
1197
1198/// What a select's closed control reads, and in which tone.
1199///
1200/// A chooser with nothing chosen would show an empty box: `shown_label` falls
1201/// back to the value, and the unanswered value is the empty string. The
1202/// placeholder is where an instruction such as "Select device..." goes, rather
1203/// than on a disabled button elsewhere on the screen.
1204///
1205/// [`Field::placeholder`] is the description's word for "what the field reads
1206/// while it is empty", on a chooser as on a typed kind. Muted because it is not
1207/// an answer, the same tone the typed kinds' ghost text takes.
1208///
1209/// A value no option carries but that is *not* empty stays as itself, in
1210/// `content`: that is the goingson retention bug and it is a wrong answer
1211/// rather than an absent one.
1212///
1213/// Returns the words and the tone rather than a built [`RichText`], because
1214/// what it decides is both of them and only one of them is readable back off a
1215/// `RichText`.
1216///
1217/// [`Field::placeholder`]: makeover_layout::Field::placeholder
1218fn chosen_text<'a>(field: &'a Field<'a>, value: &'a str, palette: &Palette) -> (&'a str, Color32) {
1219 match field.placeholder {
1220 Some(ghost) if value.is_empty() => (ghost, palette.content_muted),
1221 _ => (shown_label(field.options, value), palette.content),
1222 }
1223}
1224
1225/// What one option in a choice field is drawn in.
1226///
1227/// The chosen one is the emphasised thing and takes `content`; the rest take
1228/// [`content_secondary`](Palette::content_secondary), because an option that is
1229/// not chosen is still an option and pressing it chooses it. Muted would be the
1230/// lie: [`State::Disabled`] resolves to it, so a five-option field read as one
1231/// live row and four dead ones. `makeover-tui` draws it the same way
1232/// (`makeover-tui@230bf63`); wiki `three-tone-convention` is the table.
1233fn option_color(value: &str, option: &str, palette: &Palette) -> Color32 {
1234 if value == option {
1235 palette.content
1236 } else {
1237 palette.content_secondary
1238 }
1239}
1240
1241/// Which end of an interval a box is.
1242///
1243/// Named rather than a bool, because what it selects is not a side but a
1244/// fallback: an empty end reads as the bound it stands for, and which bound
1245/// that is depends on the end.
1246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1247enum Bound {
1248 /// The lower end, falling back to the start of the extent.
1249 Low,
1250 /// The upper end, falling back to its end.
1251 High,
1252}
1253
1254/// The facts an interval's two boxes share.
1255///
1256/// One struct because they are one axis: [`Field::min`], [`Field::max`],
1257/// [`Field::step`] and [`Field::unit`] describe the question rather than either
1258/// end of it, so reading them once is what stops the two boxes drifting apart.
1259struct Axis<'a> {
1260 /// The extent both ends are dragged inside, when it is one this host can
1261 /// read.
1262 extent: Option<RangeInclusive<f64>>,
1263 /// The granularity, as the description writes it.
1264 step: Option<&'a str>,
1265 /// What the axis is measured in.
1266 unit: Option<&'a str>,
1267}
1268
1269impl Axis<'_> {
1270 /// What an empty end reads as: the bound it stands for.
1271 ///
1272 /// Zero with no extent to fall back on. That is the one number this
1273 /// renderer invents, and it invents it where the description declined to
1274 /// say anything: an unbounded interval has no edge for the end to sit on,
1275 /// and a drag box has to start somewhere.
1276 fn edge(&self, which: Bound) -> f64 {
1277 self.extent.as_ref().map_or(0.0, |extent| match which {
1278 Bound::Low => *extent.start(),
1279 Bound::High => *extent.end(),
1280 })
1281 }
1282
1283 /// One end of the interval, as a drag box.
1284 ///
1285 /// # An empty end reads as its bound
1286 ///
1287 /// Which is what the shipped control did before it was described: an unset
1288 /// minimum sits on the low edge and stores no filter. egui's `DragValue`
1289 /// holds a number and has no empty state to offer, so the alternative was a
1290 /// text box, and that would cost the app a control on the way into being
1291 /// described.
1292 ///
1293 /// With no extent to fall back on, an empty end reads zero. That is the one
1294 /// number this renderer invents, and it invents it where the description
1295 /// declined to say anything: an unbounded interval has no edge for the end
1296 /// to sit on, and a drag box has to start somewhere.
1297 ///
1298 /// Nothing is written back until the user drags, so a value the app put
1299 /// there survives being looked at: the same guarantee the slider makes.
1300 fn end(&self, ui: &mut Ui, value: &mut String, which: Bound) -> Response {
1301 let mut number = value
1302 .parse::<f64>()
1303 .ok()
1304 .filter(|n| n.is_finite())
1305 .unwrap_or(self.edge(which));
1306 let mut drag = DragValue::new(&mut number);
1307 if let Some(extent) = self.extent.clone() {
1308 drag = drag.range(extent);
1309 }
1310 if let Some(places) = decimals(self.step) {
1311 drag = drag.max_decimals(places);
1312 }
1313 if let Some(step) = step_value(self.step) {
1314 drag = drag.speed(step);
1315 }
1316 // Inside the control, beside the readout, which is where `Field::unit`
1317 // was decided to belong and where these boxes already put it.
1318 if let Some(unit) = self.unit {
1319 drag = drag.suffix(format!(" {unit}"));
1320 }
1321 let response = ui.add(drag);
1322 if response.changed()
1323 && let Some(text) = written_back(number, self.step)
1324 {
1325 *value = text;
1326 }
1327 response
1328 }
1329}
1330
1331/// The control alone, without its label, hint or error.
1332fn control(
1333 ui: &mut Ui,
1334 field: &Field<'_>,
1335 editing: Editing<'_>,
1336 palette: &Palette,
1337 style: &FieldStyle,
1338 named_by: Option<egui::Id>,
1339) -> Response {
1340 // The mismatch path: described as one thing and filled as another. Nothing
1341 // here can fix it, so it is drawn as the empty, inert version of what was
1342 // described, visible on screen, in the way an empty select is at the
1343 // webview renderer, rather than reported in a log nobody reads.
1344 let mut discard = String::new();
1345 // The interval's second scratch buffer. Two ends means the mismatch path
1346 // needs two places to write nothing to.
1347 let mut spare = String::new();
1348 let mut off = false;
1349
1350 match shape_of(field) {
1351 Control::Slid => {
1352 let value = match editing {
1353 Editing::Text(text) => text,
1354 _ => &mut discard,
1355 };
1356 // `shape_of` has already refused an unbounded range, so the extent
1357 // is only missing here if a bound is not a number (a date range,
1358 // say), which this control cannot draw either.
1359 let Some(extent) = extent(field) else {
1360 return ui.label(RichText::new(value.as_str()).color(palette.content));
1361 };
1362
1363 // A value the host cannot read starts at the low end rather than at
1364 // zero, which may be outside the extent entirely. Nothing is
1365 // written back until the user drags, so an unreadable value the app
1366 // put there survives being looked at.
1367 let mut number = value
1368 .parse::<f64>()
1369 .ok()
1370 .filter(|n| n.is_finite())
1371 .unwrap_or(*extent.start());
1372 // The granularity is the curve's, in the value's own units, so the
1373 // display precision is read off it directly.
1374 let step = field.curve.step();
1375 let mut slider = Slider::new(&mut number, extent.clone()).text("");
1376 if let Some(places) = decimals(step) {
1377 slider = slider.max_decimals(places);
1378 }
1379 if let Some(step) = step_value(step) {
1380 slider = slider.step_by(step);
1381 }
1382 // egui's own constant-ratio track, which is this host's answer to
1383 // `Curve::Logarithmic`. `is_ratio` rather than a match on the
1384 // variant, because a ratio across zero is not one: makeover-layout
1385 // decides the fallback so that four renderers cannot disagree about
1386 // when it applies.
1387 if field.curve.is_ratio(*extent.start(), *extent.end()) {
1388 slider = slider.logarithmic(true);
1389 }
1390 // The unit goes inside the control, beside the readout egui already
1391 // draws. That placement is the argument `Field::unit` was decided
1392 // on: it is where these controls put it before they were described,
1393 // and it is the one a label could never reach.
1394 if let Some(unit) = field.shown_unit() {
1395 slider = slider.suffix(format!(" {unit}"));
1396 }
1397 let response = ui.add(slider);
1398 if response.changed()
1399 && let Some(text) = written_back(number, step)
1400 {
1401 *value = text;
1402 }
1403 response
1404 }
1405 // One question, so one row. Two wells stacked would be two questions on
1406 // screen whatever the description said, which is the reading
1407 // `FieldKind::Interval` exists to prevent.
1408 //
1409 // Dragged rather than typed, because that is what these controls
1410 // already were: audiofiles' six filter axes are `DragValue` pairs with
1411 // a shared extent, a speed and a suffix, and a port that turned them
1412 // into text boxes would be a description costing the app a control.
1413 Control::Spanned => {
1414 let (lower, upper) = match editing {
1415 Editing::Between { lower, upper } => (lower, upper),
1416 _ => (&mut discard, &mut spare),
1417 };
1418 let axis = Axis {
1419 extent: extent(field),
1420 step: field.step,
1421 unit: field.shown_unit(),
1422 };
1423 ui.horizontal(|ui| {
1424 let low = axis.end(ui, lower, Bound::Low);
1425 // The word rather than a dash. A dash between two numbers is a
1426 // minus sign on a signed axis, and audiofiles filters loudness
1427 // in dBFS.
1428 ui.label(RichText::new("to").color(palette.content_secondary));
1429 let high = axis.end(ui, upper, Bound::High);
1430 // Both ends, by name. A union response carries the first id, so
1431 // labelling the union outside this arm names the lower box and
1432 // leaves the upper one announced as whatever number is in it --
1433 // which is how an interval half-kept the fix that gave every
1434 // other shape its question.
1435 if let Some(id) = named_by {
1436 low.clone().labelled_by(id);
1437 high.clone().labelled_by(id);
1438 }
1439 low | high
1440 })
1441 .inner
1442 }
1443 Control::Typed => {
1444 let text = match editing {
1445 Editing::Text(text) => text,
1446 _ => &mut discard,
1447 };
1448 // An empty frame and no margin: the well is this crate's, and egui's
1449 // own control background and padding would sit underneath it saying
1450 // something different about both.
1451 // Keyed on the description's own `multiline` and not on the
1452 // member: a markdown field is several lines by definition, and a
1453 // single-line edit would be a control the value cannot fit in. egui
1454 // does nothing else with the markdown, which is the honest answer
1455 // rather than a gap: the source is text, and editing it as text
1456 // loses none of it.
1457 let mut edit = if field.kind.multiline() {
1458 TextEdit::multiline(text)
1459 } else {
1460 TextEdit::singleline(text)
1461 }
1462 .frame(egui::Frame::NONE)
1463 .margin(Margin::ZERO)
1464 .text_color(palette.content)
1465 .password(field.kind.confidential());
1466 if let Some(ghost) = field.placeholder {
1467 edit = edit.hint_text(RichText::new(ghost).color(palette.content_muted));
1468 }
1469 let response = frame(ui, Depth::Well, palette, style.frame, |ui| ui.add(edit));
1470 // A typed number has no readout of its own to sit beside, so the
1471 // unit follows the box. Muted, because it is a fact about the value
1472 // rather than a second thing to read.
1473 match field.shown_unit() {
1474 Some(unit) => {
1475 ui.label(RichText::new(unit).color(palette.content_muted));
1476 response
1477 }
1478 None => response,
1479 }
1480 }
1481 Control::Toggled => {
1482 let on = match editing {
1483 Editing::On(on) => on,
1484 _ => &mut off,
1485 };
1486 ui.checkbox(on, RichText::new(field.label).color(palette.content))
1487 }
1488 Control::Listed => {
1489 let value = match editing {
1490 Editing::Text(text) => text,
1491 _ => &mut discard,
1492 };
1493 // No `shown_label` counterpart, and none is needed: a value no
1494 // option carries leaves every button unfilled, which is already
1495 // the honest report on screen. The select needs the fix because it
1496 // has one slot and must put *something* in it.
1497 let group = ui.vertical(|ui| {
1498 let mut answered: Option<Response> = None;
1499 for opt in field.options {
1500 // An option that cannot be picked yet is drawn and does not
1501 // answer, with the precondition beside it rather than
1502 // behind a hover: a greyed row with no reason reads as a
1503 // dead end, which is the state `Choice::unavailable` exists
1504 // to stop being sayable.
1505 let picked = if let Some(reason) = opt.unavailable {
1506 ui.horizontal(|ui| {
1507 let picked = ui
1508 .add_enabled_ui(false, |ui| {
1509 ui.radio_value(
1510 value,
1511 opt.value.to_owned(),
1512 RichText::new(opt.label).color(palette.content_muted),
1513 )
1514 })
1515 .inner;
1516 ui.label(RichText::new(reason).color(palette.content_muted));
1517 picked
1518 })
1519 .inner
1520 } else {
1521 ui.radio_value(
1522 value,
1523 opt.value.to_owned(),
1524 RichText::new(opt.label).color(option_color(value, opt.value, palette)),
1525 )
1526 };
1527 // What picking it means, under the option rather than
1528 // beside it. The placement is the difference from the reason above: a precondition is
1529 // short enough to sit on the line, and a sentence saying
1530 // what a tier is would push every option's control out of
1531 // line with its neighbours.
1532 //
1533 // Indented past the radio, so it reads as belonging to the
1534 // option above rather than as a label of its own. Muted,
1535 // the same reading `.form-option-detail` takes in the
1536 // webview: the line orients the label, it does not compete
1537 // with it.
1538 if let Some(detail) = opt.detail {
1539 ui.horizontal(|ui| {
1540 ui.add_space(OPTION_DETAIL_INDENT);
1541 ui.label(RichText::new(detail).color(palette.content_muted));
1542 });
1543 }
1544 answered = Some(match answered {
1545 Some(prev) => prev.union(picked),
1546 None => picked,
1547 });
1548 }
1549 answered
1550 });
1551 // A group described with no options answers as its own empty area
1552 // rather than as no response at all, which keeps the caller's
1553 // `.changed()` chain working on a field whose option list has not
1554 // loaded yet.
1555 group.inner.unwrap_or(group.response)
1556 }
1557 Control::Ticked => {
1558 // A host that lends no set still draws what the description
1559 // marked, which is `Choice::chosen` and the whole of what a
1560 // checklist carries about its answer.
1561 let mut seeded: Vec<String>;
1562 let ticked = if let Editing::Ticked(ticked) = editing {
1563 ticked
1564 } else {
1565 seeded = field
1566 .options
1567 .iter()
1568 .filter(|opt| opt.chosen)
1569 .map(|opt| opt.value.to_owned())
1570 .collect();
1571 &mut seeded
1572 };
1573 let group = ui.vertical(|ui| {
1574 let mut answered: Option<Response> = None;
1575 for opt in field.options {
1576 let mut on = ticked.iter().any(|value| value == opt.value);
1577 let before = on;
1578 // The radio group's rule for an option that cannot be
1579 // picked yet: drawn, inert, and saying why on its own line.
1580 let color = if !opt.available() {
1581 palette.content_muted
1582 } else if on {
1583 palette.content
1584 } else {
1585 palette.content_secondary
1586 };
1587 let picked = ui
1588 .horizontal(|ui| {
1589 let picked = ui
1590 .add_enabled_ui(opt.available(), |ui| {
1591 ui.checkbox(&mut on, RichText::new(opt.label).color(color))
1592 })
1593 .inner;
1594 if let Some(reason) = opt.unavailable {
1595 ui.label(RichText::new(reason).color(palette.content_muted));
1596 }
1597 picked
1598 })
1599 .inner;
1600 if on != before {
1601 if on {
1602 ticked.push(opt.value.to_owned());
1603 } else {
1604 ticked.retain(|value| value != opt.value);
1605 }
1606 }
1607 // Under the option, indented past the box, for the reason
1608 // the radio group gives.
1609 if let Some(detail) = opt.detail {
1610 ui.horizontal(|ui| {
1611 ui.add_space(OPTION_DETAIL_INDENT);
1612 ui.label(RichText::new(detail).color(palette.content_muted));
1613 });
1614 }
1615 answered = Some(match answered {
1616 Some(prev) => prev.union(picked),
1617 None => picked,
1618 });
1619 }
1620 answered
1621 });
1622 group.inner.unwrap_or(group.response)
1623 }
1624 Control::Chosen => {
1625 let value = match editing {
1626 Editing::Text(text) => text,
1627 _ => &mut discard,
1628 };
1629 let (shown, tone) = chosen_text(field, value, palette);
1630 ComboBox::from_id_salt(field.name)
1631 .selected_text(RichText::new(shown).color(tone))
1632 .show_ui(ui, |ui| {
1633 for opt in field.options {
1634 // Same rule as the radio group: shown, inert, and
1635 // saying why. A closed control hides its list, so the
1636 // reason has to travel with the row it belongs to.
1637 // A closed control hides its list, so everything an
1638 // option carries has to travel with the row it belongs
1639 // to. That is why both extra strings run into the text
1640 // here and neither does in the group above: a combo
1641 // row is a row, the way a `<select>`'s option is.
1642 let text = combo_row(opt);
1643 if opt.unavailable.is_some() {
1644 ui.add_enabled_ui(false, |ui| {
1645 ui.selectable_value(
1646 value,
1647 opt.value.to_owned(),
1648 RichText::new(text).color(palette.content_muted),
1649 );
1650 });
1651 continue;
1652 }
1653 ui.selectable_value(
1654 value,
1655 opt.value.to_owned(),
1656 RichText::new(text).color(option_color(value, opt.value, palette)),
1657 );
1658 }
1659 })
1660 .response
1661 }
1662 // The grouping comes out of the order rather than out of a group list:
1663 // `Field::themes` arrives sorted by variant, so the run of one variant
1664 // is the group and a heading opens whenever the variant changes. Same
1665 // walk as `makeover-webview`'s `<optgroup>` emission, which is what
1666 // keeps two renderers from disagreeing about where a group starts.
1667 Control::Themed => {
1668 let value = match editing {
1669 Editing::Text(text) => text,
1670 _ => &mut discard,
1671 };
1672 let shown = themed_text(field, value);
1673 ComboBox::from_id_salt(field.name)
1674 .selected_text(RichText::new(shown).color(palette.content))
1675 .show_ui(ui, |ui| {
1676 if let Some(follow) = field.follows {
1677 // First and outside every heading. It names no theme
1678 // and sits in no variant, so a heading over it would be
1679 // inventing a fourth variant for one row.
1680 ui.selectable_value(
1681 value,
1682 follow.value.to_owned(),
1683 RichText::new(follow.label).color(option_color(
1684 value,
1685 follow.value,
1686 palette,
1687 )),
1688 );
1689 }
1690 let mut open: Option<ThemeVariant> = None;
1691 for theme in field.themes {
1692 if open != Some(theme.variant) {
1693 // A heading rather than a `selectable_value`: it is
1694 // not pickable, and egui has no inert row that
1695 // still reads as a row. `content_muted` is the tone
1696 // for something that is not an answer, which is the
1697 // ghost text's tone eight lines up.
1698 if open.is_some() {
1699 ui.separator();
1700 }
1701 ui.label(
1702 RichText::new(theme.variant.heading()).color(palette.content_muted),
1703 );
1704 open = Some(theme.variant);
1705 }
1706 ui.selectable_value(
1707 value,
1708 theme.id.to_owned(),
1709 RichText::new(format!("{} {}", theme.name, theme.contrast.badge()))
1710 .color(option_color(value, theme.id, palette)),
1711 );
1712 }
1713 })
1714 .response
1715 }
1716 }
1717}
1718
1719/// What a theme picker's closed control reads.
1720///
1721/// [`chosen_text`]'s counterpart, and it is separate for the reason
1722/// [`Control::Themed`] is: the label lives on a [`makeover_layout::ThemeChoice`]
1723/// rather than on a [`Choice`], and the follow row is a third place to look.
1724///
1725/// No placeholder arm. A theme picker is never unanswered in the way a select
1726/// is (an app that resolved a theme to paint this control with has one), and
1727/// falling back to the raw value is the honest report on a stored id whose
1728/// theme has since been deleted.
1729fn themed_text<'a>(field: &'a Field<'a>, value: &'a str) -> &'a str {
1730 if let Some(follow) = field.follows
1731 && follow.value == value
1732 {
1733 return follow.label;
1734 }
1735 field
1736 .themes
1737 .iter()
1738 .find(|theme| theme.id == value)
1739 .map_or(value, |theme| theme.name)
1740}
1741
1742/// One field, as the column the app drops into its form.
1743///
1744/// The anatomy is `makeover-webview`'s, so the two renderers put a form
1745/// together the same way: label, control, hint, error, top to bottom, with a
1746/// checkbox labelling itself instead of taking a label above.
1747///
1748/// Returns [`None`] for a [`FieldKind::Hidden`] field, which is what
1749/// [`FieldKind::visible`] means and is the honest answer here: a webview still
1750/// emits an input for it because the form submits, and an immediate-mode
1751/// renderer has no form and no submission, so a hidden field is a value the app
1752/// already holds and there is nothing to draw or to respond to.
1753///
1754/// `state` is the description's interaction axis.
1755/// [`State::Disabled`] greys the field and stops it answering, through
1756/// [`State::suppresses_interaction`] rather than through a second reading of
1757/// what disabled means. Focus is not on that axis and never reaches here: egui
1758/// owns reach, focus and the ring for this renderer, and one ring means not a
1759/// second one per renderer that happens to have opinions.
1760pub fn field(
1761 ui: &mut Ui,
1762 field: &Field<'_>,
1763 editing: Editing<'_>,
1764 state: Option<State>,
1765 palette: &Palette,
1766 style: &FieldStyle,
1767) -> Option<Response> {
1768 if !field.kind.visible() {
1769 return None;
1770 }
1771 let enabled = !state.is_some_and(State::suppresses_interaction);
1772 let text = if enabled {
1773 palette.content
1774 } else {
1775 palette.content_muted
1776 };
1777
1778 let response = ui
1779 .vertical(|ui| {
1780 ui.spacing_mut().item_spacing.y = style.gap;
1781
1782 // A checkbox labels itself, on the right of the box.
1783 // `FieldKind::labels_itself` is the description saying so, and both
1784 // webview apps special-cased it inline before it did.
1785 let named_by = (!field.kind.labels_itself()).then(|| {
1786 ui.label(RichText::new(field.marked_label(style.required_marker)).color(text))
1787 });
1788
1789 let response = ui
1790 .add_enabled_ui(enabled, |ui| {
1791 control(
1792 ui,
1793 field,
1794 editing,
1795 palette,
1796 style,
1797 named_by.as_ref().map(|l| l.id),
1798 )
1799 })
1800 .inner;
1801
1802 // The label, attached rather than merely adjacent.
1803 //
1804 // Drawn above the control and no more, it would put an unnamed box
1805 // in the accessibility tree with some text near it: a screen reader
1806 // would announce a text field with no question, and a prefilled one
1807 // its own contents instead.
1808 //
1809 // Here rather than in each app: `Field::label` is a member the
1810 // description carries so a renderer does not have to guess,
1811 // `makeover-webview` names it in `aria-describedby`, and the two renderers disagreeing
1812 // about a fact the description states is the one thing this layer
1813 // exists to prevent. A checkbox is unaffected: egui names one from
1814 // its own text, which is what `labels_itself` already says.
1815 let response = match named_by {
1816 Some(label) => response.labelled_by(label.id),
1817 None => response,
1818 };
1819
1820 // Standing help, then what the answer costs, then what is wrong
1821 // now. All three, in that order, for the reason the webview
1822 // renderer names all three in `aria-describedby`: an error
1823 // appearing must not take the hint away with it. This host has the
1824 // room, so unlike makeover-tui it never has to choose. The
1825 // precedence rule on `Field::note` is for the renderer that does.
1826 if let Some(hint) = field.hint {
1827 ui.label(RichText::new(hint).color(palette.content_muted));
1828 }
1829 // The note carries its own tone, and `Palette::tone` is what
1830 // resolves it, so a Neutral note is ordinary content rather than
1831 // a colour this renderer picked.
1832 if let Some((tone, note)) = field.note {
1833 ui.label(RichText::new(note).color(palette.tone(tone)));
1834 }
1835 if let Some(error) = field.error {
1836 ui.label(RichText::new(error).color(palette.danger));
1837 }
1838 response
1839 })
1840 .inner;
1841
1842 Some(response)
1843}
1844
1845/// A set of fields, laid down a column.
1846///
1847/// `show_extended` is the disclosure, and it is a parameter rather than state
1848/// held here because the disclosure belongs to the *form* and not to any field:
1849/// [`Field::extended`] marks which fields are behind one, and the app owns
1850/// whether it is open. That is the same division `makeover-webview` draws when
1851/// it marks the group `data-extended` and emits no control to toggle it.
1852///
1853/// `draw` is called once per field that should be visible, in order. Taking a
1854/// callback rather than a slice of [`Editing`]s is what keeps the app's own
1855/// values borrowed one at a time: a form's fields usually live in different
1856/// structs, and a parallel array would have to be built each frame and kept in
1857/// step with the description by hand.
1858pub fn group<'a>(
1859 ui: &mut Ui,
1860 fields: &'a [Field<'a>],
1861 show_extended: bool,
1862 style: &FieldStyle,
1863 mut draw: impl FnMut(&mut Ui, &'a Field<'a>),
1864) {
1865 ui.vertical(|ui| {
1866 ui.spacing_mut().item_spacing.y = style.group_gap;
1867 for f in fields {
1868 if f.extended && !show_extended {
1869 continue;
1870 }
1871 draw(ui, f);
1872 }
1873 });
1874}
1875
1876#[cfg(test)]
1877mod tests;