//! The immediate-mode renderer for [`makeover_layout`]. //! //! //! //! Named for the mode, not the library, the way `makeover-tui` is named for //! the target and not for ratatui. Immediate mode is the constraint that //! actually separates this renderer from the other two, and egui is the //! backend it is written against. //! //! It is the harshest renderer the description has to survive: no //! `box-shadow`, no `inset`, no cascade, no retained tree to mutate, and //! `Visuals.widgets.*.bg_stroke` is a single stroke with no per-side control. //! A two-tone lit edge is not something egui can be configured into producing, //! so it gets painted by hand here, once, instead of in every consuming app. //! //! # What this crate does and does not own //! //! It owns the *expression*: two mitred polylines for a bevel and a `Frame` //! for a filled region. It owns no colours, no sizes and no substitutions: //! makeover derives `surface-well` and every consumer reads the real token. //! [`Palette`] is supplied by the caller, //! already resolved, and every radius, margin and stroke width arrives in //! [`FrameStyle`]. //! //! That split is why the crate has no dependency on `makeover` itself: the app //! already resolves a theme, and coupling a renderer to a colour crate's //! version would buy nothing. //! //! # The cascade is the real difference //! //! A stylesheet can say "a pressed button inverts its bevel" once and let the //! cascade carry it. An immediate-mode renderer has nowhere to put that, so //! every call site decides. [`makeover_layout::Depth::pressed`] is what keeps //! the decision from being re-derived per widget. //! //! # Overlays //! //! [`Palette::cast`] is what overlaying means in immediate mode. [`frame`] hands //! the cast shadow to the `egui::Frame` for any depth whose fill is //! [`Fill::Overlay`], keyed off the fill rather than the variant. //! //! # The table //! //! [`table`] draws `makeover_layout::CellPart`. Two things it forces, both named //! where they land: //! //! - **`egui_extras`**, this crate's one dependency past egui. egui has no //! table, and `Grid` gives no per-column sizing, no sticky header and no //! scroll sync. A third answer here would reimplement that crate worse. //! - **[`Palette::action`]**, on the footing [`Palette::content`] sits on: a //! link in a cell needs the action intent. //! //! Narrowing works differently from the terminal's and the module header says //! why: a content column cannot be measured before the app's closure has drawn //! it, so `egui_extras` sizes it and the declared floor budgets it. //! //! Three things are host idiom rather than description, which is why they land //! here and not in `makeover-layout`, and all three are answered on a handle the //! app never sees: the `egui_extras` row and builder this crate owns. That is //! [`table::cell`]'s reasoning again: what the app cannot reach, the renderer //! owes it. //! //! - **A selected row.** [`table::Body::selected`], a predicate asked per row, //! because `set_selected` is a method on the row. Without it a file list has //! no way to show what is selected, which is most of what a file list does. //! - **Scrolling a row into view.** [`table::Body::scroll_to`], because //! `scroll_to_row` is a method on the builder. A keyboard cursor that moves //! off-screen and stays there is the bug this prevents. //! - **Dragging a divider.** [`table::TableStyle::resizable`], which is a knob //! because egui_extras offers two settings here and a renderer can honestly //! make either choice. //! //! Cells are centred on the row's centre line, always, because there is no //! second honest answer and egui's own default (top-aligned) is the one thing it //! cannot be. That is not a knob. //! //! [`table::Body`] is also what splits a table's per-frame facts from its //! description and from its style. A row count, a selection and a scroll request //! are none of them style, and none of them survive the frame. //! //! # The nodes that are not fields, tables or frames //! //! [`widget`] draws a meter, a token, a control and a figure. The four are //! ordinary nodes, so without them a screen walk has to draw them itself, one //! copy per consumer. //! //! [`Palette`] carries the three status intents together rather than one per //! widget, for the reason [`Palette::fill`] is an `Option`: `Tone` is five //! members wide, and a resolver missing one has to invent a colour, which is a //! substitution this crate does not make. //! # Forms //! //! The field vocabulary sits on top of the depth vocabulary: //! [`makeover_layout::Field`] rendered to egui widgets, in [`field`], and a set //! of them laid down a column in [`group`]. //! //! `makeover-webview`'s form emitter is the precedent, followed rather than //! re-derived, including the parts that are bug fixes: a //! select handed a value none of its options carries keeps that value visible //! instead of silently reading as the first option, which is a save-the-wrong- //! thing bug goingson hit for real. //! //! What differs is forced by the mode and not chosen: //! //! - **The value arrives as a `&mut`.** [`Filling`] borrows the app's own field //! and the widget writes through it. There is no DOM to read back out of, //! which is also why the description deliberately does not carry the value. //! - **A text control is drawn as a well and a select is not.** The description //! holds that a well is for anything the user looks *into*, and a text field //! is its own example; a select and a checkbox are pressed rather than looked //! into, so they keep egui's own control painting. //! - **Focus is not describable, and egui owns all of it here.** **Reach**, //! **focus** and the **focus ring** are this renderer's three answers and //! egui already has all three: its own id stack decides what is reachable, //! its own state decides what holds the keyboard, and it paints exactly one //! ring. A description states none of them, and drawing a second ring on top //! of egui's would break the one-ring rule. The terms //! are defined once in `makeover_layout`'s crate header, "Reach, focus and //! the focus ring". [`makeover_layout::State::Disabled`] *is* drawn, because //! egui has no opinion about it until told. //! - **App-level chrome is not drawn here, and it is not this crate's to //! draw.** `quasi-router` names the affordances that outlive one screen: a //! `Chrome` of key bindings, and an `Outcome::Over` for a screen drawn over //! another. Both are answered by `quasi-webview` and `quasi-tui`, and neither //! is answerable here, because this crate depends on `makeover-layout` and //! not on `quasi-router` — it is the peer of `makeover-webview` and //! `makeover-tui`, one layer below the renderers that consume a `Screen`. //! What is missing is the egui crate at *that* layer, which does not exist: //! nothing renders a quasi `Screen` in egui at all, and chrome is one item on //! the list such a crate would owe. Said here because this is where a reader //! looks for it, and because the silent version reads as "egui does not need //! a palette" rather than "nobody has built the renderer yet". //! # An interval is a sixth control shape //! //! [`FieldKind::Interval`] is drawn as `Control::Spanned`: two drag boxes on one //! row with the word `to` between them. //! //! - **Dragged rather than typed**, because that is what these controls already //! were. audiofiles' six filter axes are `DragValue` pairs sharing an extent, //! a speed and a suffix, and describing them into two text boxes would be a //! port that cost the app a control. //! - **One row, not two wells stacked.** Two wells are two questions on screen //! whatever the description says, and the arrangement is the whole content of //! the kind. //! - **An empty end reads as the bound it stands for.** An unset minimum sits //! on the low edge and stores no filter, which is what the shipped control //! did; egui's `DragValue` has no empty state, and a text box in its place //! would cost the app a control. With no extent to fall back on it reads //! zero -- the one number this renderer invents, invented where the //! description declined to say anything. //! - **The word rather than a dash**, which on a signed axis is a minus sign. //! audiofiles filters loudness in dBFS. //! //! `Axis` holds the four facts both boxes share, because they are one axis: //! reading `min`, `max`, `step` and `unit` once is what stops the two ends //! drifting apart. //! //! # A number draws its unit //! //! [`Field::unit`], and this host is the one with somewhere better than the //! label to put it: egui's `Slider` draws a suffix beside its readout. //! //! So a slider takes it as a suffix, inside the control. A typed number has no //! readout of its own and takes it as a muted label after the box. Every other //! kind ignores it, and the description says which those are -- //! `FieldKind::measurable`, rather than a `matches!` kept here. //! //! # The slider's track is a curve //! //! `makeover-layout` says what a slider is: a fraction and a function //! taking numbers to numbers, with `min` and `max` being `f(0)` and `f(1)` //! rather than the control's extent. This host has the easiest job of the //! three, because egui already has the control -- `Slider::logarithmic` is a //! constant-ratio track, so the mapping is a builder call rather than an //! arithmetic of its own. //! //! Two things worth knowing. The granularity rides on the curve, so a range //! reads `Field::curve.step()` and every other kind reads `Field::step`; the //! step is in the value's own units under either curve, so the display //! precision derives from it directly. And the fallback for a ratio curve //! across zero is asked of `Curve::is_ratio` rather than matched on the //! variant, so this renderer and a terminal cannot disagree about when a //! logarithmic request is honoured. //! //! # The slider, the unanswered chooser, and the option that is not offered //! yet //! //! Three things a description can say here. //! //! - **[`FieldKind::Range`] is a fifth control shape**, `Control::Slid`, drawn //! with egui's `Slider`. A range missing an end falls back to a well rather //! than to invented bounds, which is what //! `makeover_layout::Field::bounded` is for. //! - **`Field::placeholder` reads on a chooser**, so a select with nothing //! chosen does not show an empty box. //! - **`Choice::unavailable` is drawn rather than dropped.** The option stays //! in the list, inert, with its precondition beside it instead of behind a //! hover — a greyed row with no reason reads as a dead end, which is the //! whole finding. //! - **`Choice::detail` is drawn under the option in a //! radio group and inside the row in a combo.** A closed chooser hides its //! list, so everything an option carries has to travel with its row; a group //! has a line to spare and putting a sentence beside the control instead //! would push every option's radio out of line with its neighbours. //! //! The value still arrives as a `&mut String` and a slider is a number, so the //! parse and the write-back are this renderer's, and the write happens only on //! a real drag: a value the app put there that this host cannot read survives //! being looked at. #![forbid(unsafe_code)] use egui::{ Color32, ComboBox, CornerRadius, DragValue, Margin, Painter, Rect, Response, RichText, Shape, Slider, Stroke, TextEdit, Ui, }; use makeover_layout::{ Bevel, Choice, Depth, Edge, Field, FieldKind, Fill, State, ThemeVariant, Tone, }; use std::ops::RangeInclusive; /// Columns, narrowing, cell parts and the sort caret, over `egui_extras`. pub mod table; pub mod widget; /// The resolved colours this renderer needs, as flat values. /// /// Built by the app from whatever it already uses to resolve a theme, then /// held and reused. Deliberately not a trait and not string-keyed: a bevel is /// painted per widget per frame, and a map lookup per edge is a cost with /// nothing to show for it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Palette { /// `surface-page`. pub page: Color32, /// `surface-raised`. pub raised: Color32, /// `surface-overlay`. pub overlay: Color32, /// `surface-well`. /// /// Required, not optional. makeover derives it for every theme, so a /// resolved palette without a well is not a thing that exists here. /// `makeover-tui` keeps its own `Option` for a different reason, since a /// terminal can have the colour and still be unable to show it. pub well: Color32, /// `surface-sunken`. /// /// A surface set back from the one it sits on, by colour and nothing else. /// Not a well: a well is a hole with an edge, and this has no edge. An /// immediate-mode renderer paints an arbitrary rect, so unlike /// `makeover-tui` it has no excuse for declining this one. /// /// Required rather than optional, on the same footing as `well`: all 31 /// themes makeover embeds author it. pub sunken: Color32, /// `bevel-light`. pub bevel_light: Color32, /// `bevel-dark`. pub bevel_dark: Color32, /// `elevation`. /// /// What a surface that floats OVER the page is cast onto it with. The one /// intent here that is about a surface's relationship to the page rather /// than about the surface, which is why it is a translucent near-black on /// every theme rather than something read off the palette's own ramp. /// /// **Only for a surface that overlays.** A menu, a tooltip, a modal. A /// surface *in* the layout takes a bevel, and reaching for this on a panel /// or a card is how a pre-Platinum look survives a conversion under a new /// name. /// /// egui has a real answer for this where a terminal does not: see /// [`Palette::cast`], which is the shadow to hand an /// [`egui::Frame`](egui::Frame). pub elevation: Color32, /// `content`. /// /// Ordinary text. pub content: Color32, /// `content-secondary`. /// /// Inactive but usable: it still answers a press. The middle tone of the /// three (wiki `three-tone-convention`), and the one an unchosen option in /// a choice field takes. /// /// Not [`content_muted`](Self::content_muted), which carries a claim: /// `State::Disabled` resolves to it, so a live control wearing it tells the /// user it will not answer. `makeover-tui` draws the same widget the same /// way from `makeover-tui@230bf63`. /// /// A step of `content` toward the page, derived at load by `makeover` /// rather than authored, so it is read off the resolved theme here like /// any other token and never re-derived. pub content_secondary: Color32, /// `content-muted`. /// /// A field's hint, and what /// [`makeover_layout::State::Disabled`](makeover_layout::State::Disabled) /// resolves to. Both readings come from the description rather than from /// here: `State::Disabled` names this intent by token. pub content_muted: Color32, /// `action-primary`. /// /// What a control is drawn in. /// /// This is the intent [`CellPart`](makeover_layout::CellPart) exists to /// separate. A cell holding a control that takes the cell's text colour is /// the drift `CellPart` names. pub action: Color32, /// `danger`. /// /// A field's error message, a destructive control, a bar that has run over. pub danger: Color32, /// `success`. /// /// The three status intents arrive together and not one at a time: /// [`Tone`] is five members wide and a resolver missing one has to invent /// a colour for it, which is the substitution [`Palette::fill`] refuses. pub success: Color32, /// `warning`. pub warning: Color32, /// `info`. pub info: Color32, } impl Palette { /// Resolve a surface intent, or `None` for one this renderer does not know. /// /// A plain lookup, and no substitution. /// /// `Option`, because [`Fill`] is `#[non_exhaustive]` and a total function /// over an open enum can only stay total by inventing a colour for a member /// it has never heard of. Every member the description has today is /// answered with `Some`. #[must_use] pub const fn fill(&self, fill: Fill) -> Option { match fill { Fill::Page => Some(self.page), Fill::Raised => Some(self.raised), Fill::Overlay => Some(self.overlay), Fill::Well => Some(self.well), Fill::Sunken => Some(self.sunken), _ => None, } } /// The colour a [`Tone`] reads as. /// /// Total, unlike [`fill`](Self::fill), and the difference is not an /// inconsistency. `Fill` is `#[non_exhaustive]` and `Tone` is not: the /// description layer settled tone at five members and grows surfaces, so a /// total function here cannot be made to invent a colour by an upstream /// release the way a total `fill` could. /// /// [`Tone::Neutral`] is [`content`](Self::content) rather than a colour of /// its own, which is what "an ordinary fact" means: a neutral badge is text /// in a box, not a fifth status. #[must_use] pub const fn tone(&self, tone: Tone) -> Color32 { match tone { Tone::Neutral => self.content, Tone::Info => self.info, Tone::Success => self.success, Tone::Warning => self.warning, Tone::Danger => self.danger, } } /// The cast shadow for a surface that overlays the page. /// /// What "overlaying" means in immediate mode, answered rather than skipped. /// egui already paints shadows for its menus and windows through /// [`egui::Frame::shadow`], so the honest port is to hand that machinery the /// theme's tone instead of egui's own default, not to invent a painter here /// the way [`paint_bevel`] had to. /// /// The geometry matches what `makeover-webview` composes, in points rather /// than pixels: a small downward offset and a wide soft blur. A Platinum-era /// menu sits just off the page rather than hovering above it. /// /// ```no_run /// # let palette: makeover_immediate::Palette = unimplemented!(); /// # let ui: &mut egui::Ui = unimplemented!(); /// egui::Frame::popup(ui.style()) /// .shadow(palette.cast()) /// .show(ui, |ui| { ui.label("over the page"); }); /// ``` #[must_use] pub const fn cast(&self) -> egui::Shadow { egui::Shadow { offset: [0, 2], blur: 24, spread: 0, color: self.elevation, } } /// Resolve a bevel edge intent. #[must_use] pub const fn edge(&self, edge: Edge) -> Color32 { match edge { Edge::Light => self.bevel_light, Edge::Dark => self.bevel_dark, } } } /// The geometry a framed region is drawn with. /// /// Every field is a value, which is why they all arrive from the caller: /// radius and border width belong to `makeover-geometry`, and margins come /// from its relational gaps. #[derive(Debug, Clone, Copy, PartialEq)] pub struct FrameStyle { /// Corner radius. Square under the Platinum default. pub radius: CornerRadius, /// Inner margin between the frame and its contents. pub margin: Margin, /// Bevel stroke width, in points. pub stroke: f32, } impl Default for FrameStyle { /// A one-point square frame with no inner margin. fn default() -> Self { Self { radius: CornerRadius::ZERO, margin: Margin::ZERO, stroke: 1.0, } } } /// Paint a two-tone edge just inside `rect`. /// /// Fill first, bevel after: this adds two polylines and nothing else, so it /// composes over whatever is already there. That is what lets it go over an /// [`egui::TextEdit`] after `ui.add`, where the widget's own fill has landed. /// /// Two three-point polylines meeting at opposite corners, rather than four /// segments, so egui mitres the corner joins instead of leaving a notch. /// /// The dark polyline is drawn second, so the two corners where the runs meet /// take its tone. That is the right answer here rather than a concession. /// [`makeover_layout::Bevel`] holds those corners to belong to both edges, and /// a renderer with room to divide one should; at the default one-point stroke /// the corner is a one-point square, so the division is sub-pixel and /// antialiasing resolves it to the same blend the mitre already gives. Splitting /// it would add a seam and no information. `makeover-tui` does split, because a /// terminal cell is large enough that not splitting costs a visible cell of edge /// weight — the same rule, at a resolution where it has something to say. pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) { let (top_left, bottom_right) = bevel.edges(); // Inset by half a stroke so the line lands inside `rect` rather than // straddling its edge, which on a fractional-scale display is the // difference between one crisp pixel and two dim ones. let r = rect.shrink(stroke / 2.0); painter.add(Shape::line( vec![r.left_bottom(), r.left_top(), r.right_top()], Stroke::new(stroke, palette.edge(top_left)), )); painter.add(Shape::line( vec![r.right_top(), r.right_bottom(), r.left_bottom()], Stroke::new(stroke, palette.edge(bottom_right)), )); } /// Draw a region at a given [`Depth`]: its fill and its edge, together. /// /// [`Depth::Flat`] gets neither, and inherits whatever it sits on. That is the /// difference between level-with and painted-the-same-colour, and it is the /// reason `Depth::fill` returns an [`Option`] rather than defaulting to the /// page. pub fn frame( ui: &mut Ui, depth: Depth, palette: &Palette, style: FrameStyle, add_contents: impl FnOnce(&mut Ui) -> R, ) -> R { let mut f = egui::Frame::new() .corner_radius(style.radius) .inner_margin(style.margin); // Two ways there is no fill to paint, and they collapse to the same // outcome: the depth names none (Depth::Flat), or it names one this // renderer cannot resolve. Either way the frame goes unfilled and the // bevel below carries the depth on its own, which is the rule this // module already documents for Flat. if let Some(fill) = depth.fill().and_then(|f| palette.fill(f)) { f = f.fill(fill); } // A surface that overlays the page is cast onto it. [`Palette::cast`] has // answered what that means here since 0.10.0 and nothing could reach it: a // description had no way to say Overlay until makeover-layout 0.14.0, so // the answer sat beside the question. Keyed off the fill rather than the // variant, so it stays right for whatever else the description calls an // overlay later. if depth.fill() == Some(Fill::Overlay) { f = f.shadow(palette.cast()); } let framed = f.show(ui, add_contents); if let Some(bevel) = depth.bevel() { paint_bevel( ui.painter(), framed.response.rect, bevel, palette, style.stroke, ); } framed.inner } /// The geometry a field group is drawn with. /// /// Values again, for the reason [`FrameStyle`] is: every number here belongs to /// `makeover-geometry` and arrives already resolved. #[derive(Debug, Clone, Copy, PartialEq)] pub struct FieldStyle { /// The well a text control sits in. pub frame: FrameStyle, /// Between a field's own parts: its label, its control, its hint and its /// error. pub gap: f32, /// Between one field and the next. pub group_gap: f32, /// What marks a required field, appended to its label. /// /// A knob rather than a constant, because it is the one piece of *copy* in /// this crate and copy is not a renderer's call. A webview does not need it /// at all — it emits the `required` attribute and the browser answers — so /// this renderer is the first place where a compulsory field either shows /// that it is or silently does not. pub required_marker: &'static str, } impl Default for FieldStyle { /// The default frame, no gaps, and an asterisk. fn default() -> Self { Self { frame: FrameStyle::default(), gap: 0.0, group_gap: 0.0, required_marker: "*", } } } /// What the field currently holds, borrowed from wherever the app keeps it. /// /// The immediate-mode counterpart of `makeover_webview::form::Value`, and the /// place the two renderers are forced apart: there the value is read back out /// of the DOM after the fact, and here the widget writes through this borrow as /// it is edited. Same reason the description carries neither. /// /// An enum rather than a bag of options, on the reasoning /// `makeover_webview::form::Value` records: a checkbox holding a string is /// unsayable here, where a struct would let it be said and then have to cope. #[derive(Debug, Default)] pub enum Filling<'a> { /// Nothing to edit. The control is drawn and does not answer. #[default] Absent, /// The buffer behind anything that takes typed text, a select included: /// what a select holds is the `value` of one of its [`Choice`]s. /// /// [`Choice`]: makeover_layout::Choice Text(&'a mut String), /// A checkbox, on or off. On(&'a mut bool), /// The two buffers behind a [`FieldKind::Interval`], lower first. /// /// Two buffers rather than one string with a separator, which is /// [`makeover_layout::Field::upper_name`]'s reason one level down: an /// interval is submitted under two names, so it is edited as two values, /// and a delimiter this crate owned could appear inside either of them. /// /// Either end may be empty while the other stands. An open end is an /// answer -- "over 120 BPM" -- rather than a half-filled box. Between { /// The lower end's buffer. lower: &'a mut String, /// The upper end's buffer. upper: &'a mut String, }, } /// The label, marked if the field is compulsory. fn label_text(field: &Field<'_>, style: &FieldStyle) -> String { if field.required { format!("{} {}", field.label, style.required_marker) } else { field.label.to_owned() } } /// The four shapes a control comes in here, which is fewer than there are /// kinds. /// /// [`FieldKind`] is `#[non_exhaustive]` and grows; this does not, because the /// ways egui has of asking for a value do not. Reducing the open set to this /// closed one in one total function is what keeps a new kind from needing a new /// arm at every match below. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Control { /// Typed into, so it is drawn as a well: the user looks into it. Typed, /// Picked from a control that shows one option at a time. Pressed rather /// than looked into, so egui's own control painting stands. Chosen, /// Picked from options that are all on screen at once. /// /// Apart from [`Chosen`](Self::Chosen) because the description holds them /// apart, and holding them apart is the whole content of /// [`FieldKind::Radio`]: same question, and an answer the user can read /// without opening anything. Listed, /// Held on or off. Toggled, /// Dragged across an extent that is on screen the whole time. /// /// Apart from [`Typed`](Self::Typed) for the reason /// [`FieldKind::Range`] is apart from `Number`: the two ends are what the /// question means, so a well with a figure in it is not a quieter version /// of this control, it is a different one. Slid, /// Picked from a list of themes that arrives grouped and marked. /// /// Apart from [`Chosen`](Self::Chosen) rather than folded into it, and the /// distinction is the same one [`Listed`](Self::Listed) draws: it is not a /// different question, it is a different amount of structure on screen. A /// theme picker's rows carry a group heading and a contrast mark, and both /// come from members [`Field::options`] does not have, so a shared arm /// would be a `matches!` on the kind inside the loop rather than one arm /// less. Themed, /// Two values dragged across one axis, drawn as one question. /// /// Apart from [`Typed`](Self::Typed) for the reason /// [`FieldKind::Interval`] is apart from `Number`: two wells one under the /// other are two questions on screen, whatever the description says, and /// the arrangement is the whole content of the kind. Spanned, } /// Which shape a kind takes. /// /// The wildcard falls to [`Control::Typed`] on purpose: a kind added to the /// description since this renderer was built degrades to a text box, which /// accepts any value the others would, rather than to nothing drawn at all. /// /// `FieldKind::File` lands there rather than growing a shape of its own. egui's /// honest answer is a button that opens a native picker, which is a fifth /// control and a file-dialog dependency, and no consumer of this crate asks for /// a file field. The membership test is that every renderer *could* answer /// honestly, not that each one does on the day. A path in a text box is not /// nothing. /// /// `Field::accept` and `Field::multiple` land on the same position: both are the picker's arguments, and this /// renderer has no picker to give them to. They are not lost — the description /// still carries them, and the day the native dialog arrives here it is opened /// with them rather than with a filter written twice. /// /// `FieldKind::Date` and `FieldKind::DateTime` land there too, on the same /// footing and with one thing owed. A /// calendar is a sixth control and bare `egui` has none, so a typed value is /// the honest answer here; what the app gets is the format the description /// names, `makeover_layout::DATE_FORMAT` and `DATETIME_FORMAT`, which is why /// those are constants rather than a sentence. audiofiles is the only consumer /// of this crate and asks for neither today. A calendar popup is the upgrade /// whenever one does. /// /// `Field::as_instant` is carried and not honoured, on /// the same footing. It asks for the typed wall-clock value to be submitted as /// the moment it names, and this renderer has no submission to convert on: it /// draws the control and the app reads the value back, so the conversion would /// belong wherever that read happens rather than here. What the app gets is the /// local value in `DATETIME_FORMAT`, which is what it got before the member /// existed. No described site on this host asks for it today. /// One row of a closed chooser, as the single string it has room for. /// /// A combo hides its list, so everything an option carries has to travel with /// the row it belongs to: there is no second line to put a detail on and no /// space beside the row to put a reason in. That is the same constraint a /// ``'s option is. let text = combo_row(opt); if opt.unavailable.is_some() { ui.add_enabled_ui(false, |ui| { ui.selectable_value( value, opt.value.to_owned(), RichText::new(text).color(palette.content_muted), ); }); continue; } ui.selectable_value( value, opt.value.to_owned(), RichText::new(text).color(option_color(value, opt.value, palette)), ); } }) .response } // The grouping comes out of the order rather than out of a group list: // `Field::themes` arrives sorted by variant, so the run of one variant // is the group and a heading opens whenever the variant changes. Same // walk as `makeover-webview`'s `` emission, which is what // keeps two renderers from disagreeing about where a group starts. Control::Themed => { let value = match filling { Filling::Text(text) => text, _ => &mut discard, }; let shown = themed_text(field, value); ComboBox::from_id_salt(field.name) .selected_text(RichText::new(shown).color(palette.content)) .show_ui(ui, |ui| { if let Some(follow) = field.follows { // First and outside every heading. It names no theme // and sits in no variant, so a heading over it would be // inventing a fourth variant for one row. ui.selectable_value( value, follow.value.to_owned(), RichText::new(follow.label).color(option_color( value, follow.value, palette, )), ); } let mut open: Option = None; for theme in field.themes { if open != Some(theme.variant) { // A heading rather than a `selectable_value`: it is // not pickable, and egui has no inert row that // still reads as a row. `content_muted` is the tone // for something that is not an answer, which is the // ghost text's tone eight lines up. if open.is_some() { ui.separator(); } ui.label( RichText::new(theme.variant.heading()).color(palette.content_muted), ); open = Some(theme.variant); } ui.selectable_value( value, theme.id.to_owned(), RichText::new(format!("{} {}", theme.name, theme.contrast.badge())) .color(option_color(value, theme.id, palette)), ); } }) .response } } } /// What a theme picker's closed control reads. /// /// [`chosen_text`]'s counterpart, and it is separate for the reason /// [`Control::Themed`] is: the label lives on a [`makeover_layout::ThemeChoice`] /// rather than on a [`Choice`], and the follow row is a third place to look. /// /// No placeholder arm. A theme picker is never unanswered in the way a select /// is — an app that resolved a theme to paint this control with has one — and /// falling back to the raw value is the honest report on a stored id whose /// theme has since been deleted. fn themed_text<'a>(field: &'a Field<'a>, value: &'a str) -> &'a str { if let Some(follow) = field.follows && follow.value == value { return follow.label; } field .themes .iter() .find(|theme| theme.id == value) .map_or(value, |theme| theme.name) } /// One field, as the column the app drops into its form. /// /// The anatomy is `makeover-webview`'s, so the two renderers put a form /// together the same way: label, control, hint, error, top to bottom, with a /// checkbox labelling itself instead of taking a label above. /// /// Returns [`None`] for a [`FieldKind::Hidden`] field, which is what /// [`FieldKind::visible`] means and is the honest answer here: a webview still /// emits an input for it because the form submits, and an immediate-mode /// renderer has no form and no submission, so a hidden field is a value the app /// already holds and there is nothing to draw or to respond to. /// /// `state` is the description's interaction axis. /// [`State::Disabled`] greys the field and stops it answering, through /// [`State::suppresses_interaction`] rather than through a second reading of /// what disabled means. Focus is not on that axis and never reaches here: egui /// owns reach, focus and the ring for this renderer, and one ring means not a /// second one per renderer that happens to have opinions. pub fn field( ui: &mut Ui, field: &Field<'_>, filling: Filling<'_>, state: Option, palette: &Palette, style: &FieldStyle, ) -> Option { if !field.kind.visible() { return None; } let enabled = !state.is_some_and(State::suppresses_interaction); let text = if enabled { palette.content } else { palette.content_muted }; let response = ui .vertical(|ui| { ui.spacing_mut().item_spacing.y = style.gap; // A checkbox labels itself, on the right of the box. // `FieldKind::labels_itself` is the description saying so, and both // webview apps special-cased it inline before it did. let named_by = (!field.kind.labels_itself()) .then(|| ui.label(RichText::new(label_text(field, style)).color(text))); let response = ui .add_enabled_ui(enabled, |ui| { control( ui, field, filling, palette, style, named_by.as_ref().map(|l| l.id), ) }) .inner; // The label, attached rather than merely adjacent. // // Drawing it above the control and stopping there is what this did // until 2026-08-22, and it put an unnamed box in the accessibility // tree with some text near it: a screen reader announced a text // field with no question, and a prefilled one announced its own // contents instead. audiofiles' four name modals were the site that // measured it, through a harness reading what the panel drew. // // Worth stating why it was worth fixing here rather than in each // app: `Field::label` is a member the description carries so a // renderer does not have to guess, `makeover-webview` has always // named it in `aria-describedby`, and the two renderers disagreeing // about a fact the description states is the one thing this layer // exists to prevent. A checkbox is unaffected -- egui names one from // its own text, which is what `labels_itself` already says. let response = match named_by { Some(label) => response.labelled_by(label.id), None => response, }; // Standing help, then what the answer costs, then what is wrong // now. All three, in that order, for the reason the webview // renderer names all three in `aria-describedby`: an error // appearing must not take the hint away with it. This host has the // room, so unlike makeover-tui it never has to choose -- the // precedence rule on `Field::note` is for the renderer that does. if let Some(hint) = field.hint { ui.label(RichText::new(hint).color(palette.content_muted)); } // The note carries its own tone, and `Palette::tone` is what // resolves it, so a Neutral note is ordinary content rather than // a colour this renderer picked. if let Some((tone, note)) = field.note { ui.label(RichText::new(note).color(palette.tone(tone))); } if let Some(error) = field.error { ui.label(RichText::new(error).color(palette.danger)); } response }) .inner; Some(response) } /// A set of fields, laid down a column. /// /// `show_extended` is the disclosure, and it is a parameter rather than state /// held here because the disclosure belongs to the *form* and not to any field: /// [`Field::extended`] marks which fields are behind one, and the app owns /// whether it is open. That is the same division `makeover-webview` draws when /// it marks the group `data-extended` and emits no control to toggle it. /// /// `draw` is called once per field that should be visible, in order. Taking a /// callback rather than a slice of [`Filling`]s is what keeps the app's own /// values borrowed one at a time: a form's fields usually live in different /// structs, and a parallel array would have to be built each frame and kept in /// step with the description by hand. pub fn group<'a>( ui: &mut Ui, fields: &'a [Field<'a>], show_extended: bool, style: &FieldStyle, mut draw: impl FnMut(&mut Ui, &'a Field<'a>), ) { ui.vertical(|ui| { ui.spacing_mut().item_spacing.y = style.group_gap; for f in fields { if f.extended && !show_extended { continue; } draw(ui, f); } }); } #[cfg(test)] mod tests;