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 draws
17//!
18//! The parts of the description that carry no vocabulary member: depth
19//! ([`frame`], [`paint_bevel`]), the resolved colours ([`Palette`]), a table's
20//! per-frame facts and cell tones ([`table`]), the token and the waiting
21//! marks ([`piece`]), and the egui visuals and metrics a host starts from
22//! ([`host`]).
23//!
24//! The vocabulary members (fields, columns, meters, controls, facts, figures
25//! and charts) are drawn by `quasi-immediate`, which owns those types through
26//! `quasi-router` and calls into this crate for everything above. The style
27//! types it draws them with stay here: [`FieldStyle`], [`Editing`],
28//! [`piece::PieceStyle`] and [`table::TableStyle`].
29//!
30//! # What this crate does and does not own
31//!
32//! It owns the *expression*: two mitred polylines for a bevel and a `Frame`
33//! for a filled region. It owns no colours and no substitutions: makeover
34//! derives `surface-well` and every consumer reads the real token. [`Palette`]
35//! is supplied by the caller already resolved.
36//!
37//! It picks no sizes either. Every radius, margin, stroke width and floor
38//! arrives in a style type ([`FrameStyle`], [`FieldStyle`], [`piece::PieceStyle`],
39//! [`table::TableStyle`], [`host::Metrics`]), and where one has a default it is
40//! the suite's number rather than this crate's: the focus ring and the target
41//! floor in [`host::Metrics`] default to what `makeover-webview` emits.
42//!
43//! `makeover` itself is linked only by the `theme` feature, for
44//! `Palette::from_theme`: it embeds every shipped theme file, and an app that
45//! resolves its own colours should not carry them.
46//!
47//! # The cascade is the real difference
48//!
49//! A stylesheet can say "a pressed button inverts its bevel" once and let the
50//! cascade carry it. An immediate-mode renderer has nowhere to put that, so
51//! every call site decides. [`makeover_layout::Depth::pressed`] is what keeps
52//! the decision from being re-derived per widget.
53//!
54//! # Overlays
55//!
56//! [`Palette::cast`] is what overlaying means in immediate mode. [`frame`] hands
57//! the cast shadow to the `egui::Frame` for any depth whose fill is
58//! [`Fill::Overlay`], keyed off the fill rather than the variant.
59//!
60//! # Tones
61//!
62//! [`Palette`] carries the three status intents together rather than one per
63//! widget, for the reason [`Palette::fill`] is an `Option`: `Tone` is five
64//! members wide, and a resolver missing one has to invent a colour, which is a
65//! substitution this crate does not make.
66//!
67//! # Focus and chrome
68//!
69//! **Focus is not describable, and egui owns all of it here.** Reach, focus
70//! and the focus ring are this renderer's three answers and egui already has
71//! all three: its own id stack decides what is reachable, its own state decides
72//! what holds the keyboard, and it paints exactly one ring. Drawing a second
73//! ring on top of egui's would break the one-ring rule. The terms are defined
74//! once in `makeover_layout`'s crate header, "Reach, focus and the focus ring".
75//!
76//! **App-level chrome is not drawn here.** `quasi-router` names the affordances
77//! that outlive one screen, and `quasi-immediate` answers them: this crate
78//! depends on `makeover-layout` and not on `quasi-router`, one layer below the
79//! renderers that consume a `Screen`.
80
81#![forbid(unsafe_code)]
82
83use egui::{Color32, CornerRadius, Margin, Painter, Rect, Shape, Stroke, Ui};
84use makeover_layout::{Bevel, Depth, Edge, Fill, Tone};
85
86pub mod host;
87pub mod piece;
88pub mod table;
89
90/// The resolved colours this renderer needs, as flat values.
91///
92/// Built by the app from whatever it already uses to resolve a theme, then
93/// held and reused. Deliberately not a trait and not string-keyed: a bevel is
94/// painted per widget per frame, and a map lookup per edge is a cost with
95/// nothing to show for it.
96///
97/// `#[non_exhaustive]`, so a colour added here is not a breaking change: build
98/// one with `Palette::from_theme` (the `theme` feature), or start from
99/// [`Palette::two_tone`] and set every colour the app resolves.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101#[non_exhaustive]
102pub struct Palette {
103 /// `surface-page`.
104 pub page: Color32,
105 /// `surface-raised`.
106 pub raised: Color32,
107 /// `surface-overlay`.
108 pub overlay: Color32,
109 /// `surface-well`.
110 ///
111 /// Required, not optional. makeover derives it for every theme, so a
112 /// resolved palette without a well is not a thing that exists here.
113 /// `makeover-tui` keeps its own `Option` for a different reason, since a
114 /// terminal can have the colour and still be unable to show it.
115 pub well: Color32,
116 /// `surface-sunken`.
117 ///
118 /// A surface set back from the one it sits on, by colour and nothing else.
119 /// Not a well: a well is a hole with an edge, and this has no edge. An
120 /// immediate-mode renderer paints an arbitrary rect, so unlike
121 /// `makeover-tui` it has no excuse for declining this one.
122 ///
123 /// Required rather than optional, on the same footing as `well`: all 31
124 /// themes makeover embeds author it.
125 pub sunken: Color32,
126 /// `bevel-light`.
127 pub bevel_light: Color32,
128 /// `bevel-dark`.
129 pub bevel_dark: Color32,
130 /// `elevation`.
131 ///
132 /// What a surface that floats OVER the page is cast onto it with. The one
133 /// intent here that is about a surface's relationship to the page rather
134 /// than about the surface, which is why it is a translucent near-black on
135 /// every theme rather than something read off the palette's own ramp.
136 ///
137 /// **Only for a surface that overlays.** A menu, a tooltip, a modal. A
138 /// surface *in* the layout takes a bevel, and reaching for this on a panel
139 /// or a card is how a pre-Platinum look survives a conversion under a new
140 /// name.
141 ///
142 /// egui has a real answer for this where a terminal does not: see
143 /// [`Palette::cast`], which is the shadow to hand an
144 /// [`egui::Frame`].
145 pub elevation: Color32,
146 /// `content`.
147 ///
148 /// Ordinary text.
149 pub content: Color32,
150 /// `content-secondary`.
151 ///
152 /// Inactive but usable: it still answers a press. The middle tone of the
153 /// three (wiki `three-tone-convention`), and the one an unchosen option in
154 /// a choice field takes.
155 ///
156 /// Not [`content_muted`](Self::content_muted), which carries a claim:
157 /// `State::Disabled` resolves to it, so a live control wearing it tells the
158 /// user it will not answer. `makeover-tui` draws the same widget the same
159 /// way from `makeover-tui@230bf63`.
160 ///
161 /// A step of `content` toward the page, derived at load by `makeover`
162 /// rather than authored, so it is read off the resolved theme here like
163 /// any other token and never re-derived.
164 pub content_secondary: Color32,
165 /// `content-muted`.
166 ///
167 /// A field's hint, and what
168 /// [`makeover_layout::State::Disabled`]
169 /// resolves to. Both readings come from the description rather than from
170 /// here: `State::Disabled` names this intent by token.
171 pub content_muted: Color32,
172 /// `action-primary`.
173 ///
174 /// What a control is drawn in.
175 ///
176 /// This is the intent [`CellPart`](makeover_layout::CellPart) exists to
177 /// separate. A cell holding a control that takes the cell's text colour is
178 /// the drift `CellPart` names.
179 pub action: Color32,
180 /// `content-on-action`: ink that stays readable on [`action`](Self::action).
181 ///
182 /// Derived by the theme with `readable_on(action)` rather than picked here,
183 /// so a theme whose action hue is pale gets dark ink without this renderer
184 /// knowing which themes those are.
185 ///
186 /// The one thing that fills with `action` is the act a screen is for, the
187 /// leading control, which is why this colour exists.
188 /// A renderer that fills with the accent and leaves the label on the
189 /// ordinary content colour is one theme change away from unreadable.
190 pub content_on_action: Color32,
191 /// `danger`.
192 ///
193 /// A field's error message, a destructive control, a bar that has run over.
194 pub danger: Color32,
195 /// `success`.
196 ///
197 /// The three status intents arrive together and not one at a time:
198 /// [`Tone`] is five members wide and a resolver missing one has to invent
199 /// a colour for it, which is the substitution [`Palette::fill`] refuses.
200 pub success: Color32,
201 /// `warning`.
202 pub warning: Color32,
203 /// `info`.
204 pub info: Color32,
205 /// `border`, the authored line colour.
206 ///
207 /// A neutral badge's edge: a badge on the raised ground is raised too, so
208 /// the edge is what draws it.
209 pub border: Color32,
210 /// `info-surface`: raised with 12 percent of `info`. A badge's fill.
211 ///
212 /// The four tone surfaces arrive together for the status intents' reason.
213 pub info_surface: Color32,
214 /// `success-surface`.
215 pub success_surface: Color32,
216 /// `warning-surface`.
217 pub warning_surface: Color32,
218 /// `danger-surface`.
219 pub danger_surface: Color32,
220 /// `row-hover`: the row under the pointer, at 9 percent.
221 pub row_hover: Color32,
222 /// `row-rule`: the hairline between rows and around a table, at 26
223 /// percent.
224 pub row_rule: Color32,
225 /// `row-selected`: a selected row, raised with 18 percent of the accent.
226 ///
227 /// A fill and never a foreground, so a row that is red for a failure stays
228 /// red while it is selected.
229 pub row_selected: Color32,
230}
231
232impl Palette {
233 /// Every surface `page` and every ink `ink`, with no cast shadow.
234 ///
235 /// A starting point for the setters, legible on its own and wrong in every
236 /// detail a theme decides: an app that resolves its own colours starts here
237 /// and sets each one, and a colour added to this type later arrives at one
238 /// of these two rather than as a compile error in every consumer.
239 #[must_use]
240 pub const fn two_tone(page: Color32, ink: Color32) -> Self {
241 Self {
242 page,
243 raised: page,
244 overlay: page,
245 well: page,
246 sunken: page,
247 bevel_light: page,
248 bevel_dark: ink,
249 elevation: Color32::TRANSPARENT,
250 content: ink,
251 content_secondary: ink,
252 content_muted: ink,
253 action: ink,
254 content_on_action: page,
255 danger: ink,
256 success: ink,
257 warning: ink,
258 info: ink,
259 border: ink,
260 info_surface: page,
261 success_surface: page,
262 warning_surface: page,
263 danger_surface: page,
264 row_hover: page,
265 row_rule: ink,
266 row_selected: page,
267 }
268 }
269
270 /// Set [`page`](Self::page).
271 #[must_use]
272 pub const fn page(mut self, colour: Color32) -> Self {
273 self.page = colour;
274 self
275 }
276
277 /// Set [`raised`](Self::raised).
278 #[must_use]
279 pub const fn raised(mut self, colour: Color32) -> Self {
280 self.raised = colour;
281 self
282 }
283
284 /// Set [`overlay`](Self::overlay).
285 #[must_use]
286 pub const fn overlay(mut self, colour: Color32) -> Self {
287 self.overlay = colour;
288 self
289 }
290
291 /// Set [`well`](Self::well).
292 #[must_use]
293 pub const fn well(mut self, colour: Color32) -> Self {
294 self.well = colour;
295 self
296 }
297
298 /// Set [`sunken`](Self::sunken).
299 #[must_use]
300 pub const fn sunken(mut self, colour: Color32) -> Self {
301 self.sunken = colour;
302 self
303 }
304
305 /// Set [`bevel_light`](Self::bevel_light).
306 #[must_use]
307 pub const fn bevel_light(mut self, colour: Color32) -> Self {
308 self.bevel_light = colour;
309 self
310 }
311
312 /// Set [`bevel_dark`](Self::bevel_dark).
313 #[must_use]
314 pub const fn bevel_dark(mut self, colour: Color32) -> Self {
315 self.bevel_dark = colour;
316 self
317 }
318
319 /// Set [`elevation`](Self::elevation).
320 #[must_use]
321 pub const fn elevation(mut self, colour: Color32) -> Self {
322 self.elevation = colour;
323 self
324 }
325
326 /// Set [`content`](Self::content).
327 #[must_use]
328 pub const fn content(mut self, colour: Color32) -> Self {
329 self.content = colour;
330 self
331 }
332
333 /// Set [`content_secondary`](Self::content_secondary).
334 #[must_use]
335 pub const fn content_secondary(mut self, colour: Color32) -> Self {
336 self.content_secondary = colour;
337 self
338 }
339
340 /// Set [`content_muted`](Self::content_muted).
341 #[must_use]
342 pub const fn content_muted(mut self, colour: Color32) -> Self {
343 self.content_muted = colour;
344 self
345 }
346
347 /// Set [`action`](Self::action).
348 #[must_use]
349 pub const fn action(mut self, colour: Color32) -> Self {
350 self.action = colour;
351 self
352 }
353
354 /// Set [`content_on_action`](Self::content_on_action).
355 #[must_use]
356 pub const fn content_on_action(mut self, colour: Color32) -> Self {
357 self.content_on_action = colour;
358 self
359 }
360
361 /// Set [`danger`](Self::danger).
362 #[must_use]
363 pub const fn danger(mut self, colour: Color32) -> Self {
364 self.danger = colour;
365 self
366 }
367
368 /// Set [`success`](Self::success).
369 #[must_use]
370 pub const fn success(mut self, colour: Color32) -> Self {
371 self.success = colour;
372 self
373 }
374
375 /// Set [`warning`](Self::warning).
376 #[must_use]
377 pub const fn warning(mut self, colour: Color32) -> Self {
378 self.warning = colour;
379 self
380 }
381
382 /// Set [`info`](Self::info).
383 #[must_use]
384 pub const fn info(mut self, colour: Color32) -> Self {
385 self.info = colour;
386 self
387 }
388
389 /// Set [`border`](Self::border).
390 #[must_use]
391 pub const fn border(mut self, colour: Color32) -> Self {
392 self.border = colour;
393 self
394 }
395
396 /// Set [`info_surface`](Self::info_surface).
397 #[must_use]
398 pub const fn info_surface(mut self, colour: Color32) -> Self {
399 self.info_surface = colour;
400 self
401 }
402
403 /// Set [`success_surface`](Self::success_surface).
404 #[must_use]
405 pub const fn success_surface(mut self, colour: Color32) -> Self {
406 self.success_surface = colour;
407 self
408 }
409
410 /// Set [`warning_surface`](Self::warning_surface).
411 #[must_use]
412 pub const fn warning_surface(mut self, colour: Color32) -> Self {
413 self.warning_surface = colour;
414 self
415 }
416
417 /// Set [`danger_surface`](Self::danger_surface).
418 #[must_use]
419 pub const fn danger_surface(mut self, colour: Color32) -> Self {
420 self.danger_surface = colour;
421 self
422 }
423
424 /// Set [`row_hover`](Self::row_hover).
425 #[must_use]
426 pub const fn row_hover(mut self, colour: Color32) -> Self {
427 self.row_hover = colour;
428 self
429 }
430
431 /// Set [`row_rule`](Self::row_rule).
432 #[must_use]
433 pub const fn row_rule(mut self, colour: Color32) -> Self {
434 self.row_rule = colour;
435 self
436 }
437
438 /// Set [`row_selected`](Self::row_selected).
439 #[must_use]
440 pub const fn row_selected(mut self, colour: Color32) -> Self {
441 self.row_selected = colour;
442 self
443 }
444
445 /// Every colour, read from a resolved makeover theme.
446 ///
447 /// # Errors
448 ///
449 /// [`MissingToken`] naming the first token the theme does not resolve.
450 /// makeover derives every one of these for every shipped theme, so this
451 /// fails only on a theme file missing a base intent.
452 #[cfg(feature = "theme")]
453 pub fn from_theme(tokens: &makeover::SemanticTokens) -> Result<Self, MissingToken> {
454 use makeover::Token;
455 let colour = |token: Token| {
456 tokens
457 .rgba(token)
458 .map(|(r, g, b, a)| Color32::from_rgba_unmultiplied(r, g, b, a))
459 .ok_or(MissingToken(token))
460 };
461 Ok(Self {
462 page: colour(Token::SurfacePage)?,
463 raised: colour(Token::SurfaceRaised)?,
464 overlay: colour(Token::SurfaceOverlay)?,
465 well: colour(Token::SurfaceWell)?,
466 sunken: colour(Token::SurfaceSunken)?,
467 bevel_light: colour(Token::BevelLight)?,
468 bevel_dark: colour(Token::BevelDark)?,
469 elevation: colour(Token::Elevation)?,
470 content: colour(Token::Content)?,
471 content_secondary: colour(Token::ContentSecondary)?,
472 content_muted: colour(Token::ContentMuted)?,
473 action: colour(Token::Action)?,
474 content_on_action: colour(Token::ContentOnAction)?,
475 danger: colour(Token::Danger)?,
476 success: colour(Token::Success)?,
477 warning: colour(Token::Warning)?,
478 info: colour(Token::Info)?,
479 border: colour(Token::Border)?,
480 info_surface: colour(Token::InfoSurface)?,
481 success_surface: colour(Token::SuccessSurface)?,
482 warning_surface: colour(Token::WarningSurface)?,
483 danger_surface: colour(Token::DangerSurface)?,
484 row_hover: colour(Token::RowHover)?,
485 row_rule: colour(Token::RowRule)?,
486 row_selected: colour(Token::RowSelected)?,
487 })
488 }
489}
490
491/// A token `Palette::from_theme` needed and the theme did not resolve.
492#[cfg(feature = "theme")]
493#[derive(Debug, Clone, Copy, PartialEq, Eq)]
494pub struct MissingToken(pub makeover::Token);
495
496#[cfg(feature = "theme")]
497impl std::fmt::Display for MissingToken {
498 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
499 write!(f, "the theme resolves no `{}`", self.0.as_str())
500 }
501}
502
503#[cfg(feature = "theme")]
504impl std::error::Error for MissingToken {}
505
506impl Palette {
507 /// Resolve a surface intent, or `None` for one this renderer does not know.
508 ///
509 /// A plain lookup, and no substitution.
510 ///
511 /// `Option`, because [`Fill`] is `#[non_exhaustive]` and a total function
512 /// over an open enum can only stay total by inventing a colour for a member
513 /// it has never heard of. Every member the description has today is
514 /// answered with `Some`.
515 #[must_use]
516 pub const fn fill(&self, fill: Fill) -> Option<Color32> {
517 match fill {
518 Fill::Page => Some(self.page),
519 Fill::Raised => Some(self.raised),
520 Fill::Overlay => Some(self.overlay),
521 Fill::Well => Some(self.well),
522 Fill::Sunken => Some(self.sunken),
523 _ => None,
524 }
525 }
526
527 /// The colour a [`Tone`] reads as.
528 ///
529 /// Total, unlike [`fill`](Self::fill), and the difference is not an
530 /// inconsistency. `Fill` is `#[non_exhaustive]` and `Tone` is not: the
531 /// description layer settled tone at five members and grows surfaces, so a
532 /// total function here cannot be made to invent a colour by an upstream
533 /// release the way a total `fill` could.
534 ///
535 /// [`Tone::Neutral`] is [`content`](Self::content) rather than a colour of
536 /// its own, which is what "an ordinary fact" means: a neutral badge is text
537 /// in a box, not a fifth status.
538 #[must_use]
539 pub const fn tone(&self, tone: Tone) -> Color32 {
540 match tone {
541 Tone::Neutral => self.content,
542 Tone::Info => self.info,
543 Tone::Success => self.success,
544 Tone::Warning => self.warning,
545 Tone::Danger => self.danger,
546 // A tone this renderer has not learnt yet reads as an ordinary
547 // fact rather than as a status it might misstate.
548 _ => self.content,
549 }
550 }
551
552 /// What a badge of this tone is filled with: its tone surface, or the
553 /// raised surface for [`Tone::Neutral`], as `makeover-webview` fills one.
554 #[must_use]
555 pub const fn tone_surface(&self, tone: Tone) -> Color32 {
556 match tone {
557 Tone::Neutral => self.raised,
558 Tone::Info => self.info_surface,
559 Tone::Success => self.success_surface,
560 Tone::Warning => self.warning_surface,
561 Tone::Danger => self.danger_surface,
562 _ => self.raised,
563 }
564 }
565
566 /// What a badge of this tone is edged with: its tone, or
567 /// [`border`](Self::border) for [`Tone::Neutral`], whose tone is the ink.
568 #[must_use]
569 pub const fn tone_edge(&self, tone: Tone) -> Color32 {
570 match tone {
571 Tone::Neutral => self.border,
572 other => self.tone(other),
573 }
574 }
575
576 /// The cast shadow for a surface that overlays the page.
577 ///
578 /// What "overlaying" means in immediate mode, answered rather than skipped.
579 /// egui already paints shadows for its menus and windows through
580 /// [`egui::Frame::shadow`], so the honest port is to hand that machinery the
581 /// theme's tone instead of egui's own default, not to invent a painter here
582 /// the way [`paint_bevel`] had to.
583 ///
584 /// The geometry matches what `makeover-webview` composes, in points rather
585 /// than pixels: a small downward offset and a wide soft blur. A Platinum-era
586 /// menu sits just off the page rather than hovering above it.
587 ///
588 /// ```no_run
589 /// # let palette: makeover_immediate::Palette = unimplemented!();
590 /// # let ui: &mut egui::Ui = unimplemented!();
591 /// egui::Frame::popup(ui.style())
592 /// .shadow(palette.cast())
593 /// .show(ui, |ui| { ui.label("over the page"); });
594 /// ```
595 #[must_use]
596 pub const fn cast(&self) -> egui::Shadow {
597 egui::Shadow {
598 offset: [0, 2],
599 blur: 24,
600 spread: 0,
601 color: self.elevation,
602 }
603 }
604
605 /// Resolve a bevel edge intent.
606 #[must_use]
607 pub const fn edge(&self, edge: Edge) -> Color32 {
608 match edge {
609 Edge::Light => self.bevel_light,
610 Edge::Dark => self.bevel_dark,
611 // An edge this renderer has not learnt is drawn as the border, the
612 // one line every surface already has.
613 _ => self.border,
614 }
615 }
616}
617
618/// The geometry a framed region is drawn with.
619///
620/// Every field is a value, which is why they all arrive from the caller:
621/// radius and border width belong to `makeover-geometry`, and margins come
622/// from its relational gaps.
623#[derive(Debug, Clone, Copy, PartialEq)]
624pub struct FrameStyle {
625 /// Corner radius. Square under the Platinum default.
626 pub radius: CornerRadius,
627 /// Inner margin between the frame and its contents.
628 pub margin: Margin,
629 /// Bevel stroke width, in points.
630 pub stroke: f32,
631}
632
633impl Default for FrameStyle {
634 /// A one-point square frame with no inner margin.
635 fn default() -> Self {
636 Self {
637 radius: CornerRadius::ZERO,
638 margin: Margin::ZERO,
639 stroke: 1.0,
640 }
641 }
642}
643
644/// Paint a two-tone edge just inside `rect`.
645///
646/// Fill first, bevel after: this adds two polylines and nothing else, so it
647/// composes over whatever is already there. That is what lets it go over an
648/// [`egui::TextEdit`] after `ui.add`, where the widget's own fill has landed.
649///
650/// Two three-point polylines meeting at opposite corners, rather than four
651/// segments, so egui mitres the corner joins instead of leaving a notch.
652///
653/// The dark polyline is drawn second, so the two corners where the runs meet
654/// take its tone. That is the right answer here rather than a concession.
655/// [`makeover_layout::Bevel`] holds those corners to belong to both edges, and
656/// a renderer with room to divide one should; at the default one-point stroke
657/// the corner is a one-point square, so the division is sub-pixel and
658/// antialiasing resolves it to the same blend the mitre already gives. Splitting
659/// it would add a seam and no information. `makeover-tui` does split, because a
660/// terminal cell is large enough that not splitting costs a visible cell of edge
661/// weight. The same rule, at a resolution where it has something to say.
662pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) {
663 let (top_left, bottom_right) = bevel.edges();
664
665 // Inset by half a stroke so the line lands inside `rect` rather than
666 // straddling its edge, which on a fractional-scale display is the
667 // difference between one crisp pixel and two dim ones.
668 let r = rect.shrink(stroke / 2.0);
669
670 painter.add(Shape::line(
671 vec![r.left_bottom(), r.left_top(), r.right_top()],
672 Stroke::new(stroke, palette.edge(top_left)),
673 ));
674 // Three points close the box, two leave the bottom open: the shaded run
675 // comes down the right side and stops. That is the folder tab, and it is
676 // the same edge the browser draws by dropping the shadow's vertical
677 // offset. The lit polyline is untouched either way, so the join is the
678 // only thing that changes.
679 let shaded = if bevel.draws_bottom() {
680 vec![r.right_top(), r.right_bottom(), r.left_bottom()]
681 } else {
682 vec![r.right_top(), r.right_bottom()]
683 };
684 painter.add(Shape::line(
685 shaded,
686 Stroke::new(stroke, palette.edge(bottom_right)),
687 ));
688}
689
690/// Draw a region at a given [`Depth`]: its fill and its edge, together.
691///
692/// [`Depth::Flat`] gets neither, and inherits whatever it sits on. That is the
693/// difference between level-with and painted-the-same-colour, and it is the
694/// reason `Depth::fill` returns an [`Option`] rather than defaulting to the
695/// page.
696pub fn frame<R>(
697 ui: &mut Ui,
698 depth: Depth,
699 palette: &Palette,
700 style: FrameStyle,
701 add_contents: impl FnOnce(&mut Ui) -> R,
702) -> R {
703 let mut f = egui::Frame::new()
704 .corner_radius(style.radius)
705 .inner_margin(style.margin);
706 // Two ways there is no fill to paint, and they collapse to the same
707 // outcome: the depth names none (Depth::Flat), or it names one this
708 // renderer cannot resolve. Either way the frame goes unfilled and the
709 // bevel below carries the depth on its own, which is the rule this
710 // module already documents for Flat.
711 if let Some(fill) = depth.fill().and_then(|f| palette.fill(f)) {
712 f = f.fill(fill);
713 }
714 // A surface that overlays the page is cast onto it, with
715 // [`Palette::cast`]. Keyed off the fill rather than the variant, so it stays right for whatever else the description calls an
716 // overlay later.
717 if depth.fill() == Some(Fill::Overlay) {
718 f = f.shadow(palette.cast());
719 }
720 let framed = f.show(ui, add_contents);
721 if let Some(bevel) = depth.bevel() {
722 paint_bevel(
723 ui.painter(),
724 framed.response.rect,
725 bevel,
726 palette,
727 style.stroke,
728 );
729 }
730 framed.inner
731}
732
733/// The geometry a field group is drawn with.
734///
735/// The fields themselves are drawn by `quasi-immediate`; the style lives here
736/// beside [`FrameStyle`], which it embeds, so an app sets both in one place.
737/// Values again, for the reason [`FrameStyle`] is: every number here belongs to
738/// `makeover-geometry` and arrives already resolved.
739#[derive(Debug, Clone, Copy, PartialEq)]
740pub struct FieldStyle {
741 /// The well a text control sits in.
742 pub frame: FrameStyle,
743 /// Between a field's own parts: its label, its control, its hint and its
744 /// error.
745 pub gap: f32,
746 /// Between one field and the next.
747 pub group_gap: f32,
748 /// What marks a required field, appended to its label.
749 ///
750 /// A knob rather than a constant, because it is the one piece of *copy* in
751 /// this crate and copy is not a renderer's call. A webview does not need it
752 /// at all (it emits the `required` attribute and the browser answers), so
753 /// this renderer is the first place where a compulsory field either shows
754 /// that it is or silently does not.
755 pub required_marker: &'static str,
756}
757
758impl Default for FieldStyle {
759 /// The default frame, no gaps, and an asterisk.
760 fn default() -> Self {
761 Self {
762 frame: FrameStyle::default(),
763 gap: 0.0,
764 group_gap: 0.0,
765 required_marker: "*",
766 }
767 }
768}
769
770/// What the field currently holds, borrowed from wherever the app keeps it.
771///
772/// Handed to `quasi-immediate`'s field, which writes through it as the user
773/// edits.
774///
775/// The editable counterpart of [`makeover_layout::Value`], which is what the
776/// other renderers read: there the value is read back after the fact, and here
777/// the widget writes through this borrow as it is edited. The description
778/// carries neither, for the same reason.
779///
780/// An enum rather than a bag of options, on the reasoning
781/// [`makeover_layout::Value`] records: a checkbox holding a string is
782/// unsayable here, where a struct would let it be said and then have to cope.
783///
784/// `#[non_exhaustive]`: a host builds these and never matches on them, so the
785/// next shape of held value costs nobody a match arm.
786#[derive(Debug, Default)]
787#[non_exhaustive]
788pub enum Editing<'a> {
789 /// Nothing to edit. The control is drawn and does not answer.
790 #[default]
791 Absent,
792 /// The buffer behind anything that takes typed text, a select included:
793 /// what a select holds is the `value` of one of its options.
794 Text(&'a mut String),
795 /// A checkbox, on or off.
796 On(&'a mut bool),
797 /// The values of a [`FieldKind::Checklist`](makeover_layout::FieldKind::Checklist)'s ticked options.
798 ///
799 /// The values rather than a bool per option, because the options are the
800 /// description's and the set is the app's: a host keeps what was ticked
801 /// under the option values it submits, and a parallel list of bools would
802 /// have to be re-aligned with the options every time the list changed.
803 /// Ticking pushes the option's value and unticking removes it, so the order
804 /// is the order things were ticked in, which is no order a handler should
805 /// read anything into.
806 Ticked(&'a mut Vec<String>),
807 /// The two buffers behind a [`FieldKind::Interval`](makeover_layout::FieldKind::Interval), lower first.
808 ///
809 /// Two buffers rather than one string with a separator: an
810 /// interval is submitted under two names, so it is edited as two values,
811 /// and a delimiter this crate owned could appear inside either of them.
812 ///
813 /// Either end may be empty while the other stands. An open end is an
814 /// answer ("over 120 BPM") rather than a half-filled box.
815 Between {
816 /// The lower end's buffer.
817 lower: &'a mut String,
818 /// The upper end's buffer.
819 upper: &'a mut String,
820 },
821}
822
823#[cfg(test)]
824mod tests;