Skip to main content

egui_pop_core/
field.rs

1//! A field's state drawn, announced and reported: the egui side of
2//! [`egui_pop_model::field`].
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! Every input shows its [`FieldState`] the same way, the decorated
8//! input ([`crate::input`]) and the sliders alike:
9//!
10//! - **an edge**: a strip along the field's leading side in the colour
11//!   of its first state ([`FieldState::edge`]: disabled, invalid,
12//!   pending, modified), from the `field.*` tokens;
13//! - **a marker icon** per state, so the state never rests on colour
14//!   alone: a dot (modified), an asterisk (required), a crossed circle
15//!   (invalid), a clock (pending), a lock (read-only), an "i" (disabled,
16//!   whose reason is its tooltip);
17//! - **assistive technologies** get it too: required, invalid (with the
18//!   message as the description), disabled (with the reason), read-only,
19//!   busy (pending);
20//! - **agents** read every field drawn in the last pass, with its
21//!   state and its disabled reason, through [`describe`] (and the debug
22//!   bridge's `fields` collector).
23//!
24//! ```
25//! use egui_pop_core::field;
26//! use egui_pop_model::field::FieldState;
27//!
28//! fn exposure_row(ui: &mut egui::Ui) {
29//!     let state = FieldState::new().disabled("Needs an open image");
30//!     let r = ui.add_enabled(false, egui::Button::new("Pick"));
31//!     field::hover(ui, &r, &state);
32//!     field::access(ui.ctx(), r.id, &state);
33//!     field::record(ui.ctx(), r.id, "Pick", "button", &state);
34//! }
35//! ```
36
37use egui::{Align2, Color32, Context, CornerRadius, FontId, Id, Rect, Response, Ui, pos2, vec2};
38use serde::Serialize;
39use serde_json::{Value as Json, json};
40
41pub use egui_pop_model::field::{Baseline, FieldState, Mark, Modified};
42
43use crate::icon::Icon;
44use crate::kit::{Kit, State, Tone};
45use crate::state::{lock, pass, shared};
46use crate::strings::{self, FIELD_DISABLED, FIELD_MODIFIED_DEFAULT, FIELD_MODIFIED_SAVED};
47use crate::strings::{FIELD_PENDING, FIELD_REQUIRED, READ_ONLY};
48use crate::theme::Tokens;
49
50/// The colour of a mark, from the kit's `field`: the muted tone's text
51/// for a disabled or read-only field, else the border colour of the
52/// mark's tone (`danger` invalid, `info` pending, `accent` modified,
53/// `warning` required).
54pub fn color(kit: &Kit, mark: Mark) -> Color32 {
55    let tone = |tone| kit.field.style_toned(tone, State::REST);
56    match mark {
57        Mark::Disabled | Mark::ReadOnly => tone(Tone::Muted).text,
58        Mark::Invalid => tone(Tone::Danger).border_color,
59        Mark::Pending => tone(Tone::Info).border_color,
60        Mark::Modified => tone(Tone::Accent).border_color,
61        Mark::Required => tone(Tone::Warning).border_color,
62    }
63}
64
65/// The icon of a mark; the required mark is an asterisk, painted as
66/// text ([`paint_marker`]).
67pub fn icon(mark: Mark) -> Option<Icon> {
68    match mark {
69        Mark::Disabled => Some(Icon::Info),
70        Mark::Invalid => Some(Icon::Error),
71        Mark::Pending => Some(Icon::History),
72        Mark::Modified => Some(Icon::Dot),
73        Mark::ReadOnly => Some(Icon::Lock),
74        Mark::Required => None,
75    }
76}
77
78/// What a mark says, in the interface's language (the disabled and
79/// invalid marks say their reason and message).
80pub fn text(ctx: &Context, state: &FieldState, mark: Mark) -> String {
81    match mark {
82        Mark::Disabled => strings::tr_args(
83            ctx,
84            &FIELD_DISABLED,
85            &[("reason", state.disabled_reason().unwrap_or_default())],
86        ),
87        Mark::Invalid => state.message().unwrap_or_default().to_string(),
88        Mark::Pending => strings::tr(ctx, &FIELD_PENDING),
89        Mark::Modified => match state.modified.map(|m| m.against) {
90            Some(Baseline::Saved) => strings::tr(ctx, &FIELD_MODIFIED_SAVED),
91            _ => strings::tr(ctx, &FIELD_MODIFIED_DEFAULT),
92        },
93        Mark::Required => strings::tr(ctx, &FIELD_REQUIRED),
94        Mark::ReadOnly => strings::tr(ctx, &READ_ONLY),
95    }
96}
97
98/// The width of a field's edge strip.
99pub fn edge_width(t: &Tokens) -> f32 {
100    (t.space.xs * 0.75).max(2.0)
101}
102
103/// Paints the edge along a field's leading side, in its first state's
104/// colour; an invalid or pending field is outlined in it too.
105pub fn paint_edge(ui: &Ui, rect: Rect, state: &FieldState) {
106    let Some(mark) = state.edge() else {
107        return;
108    };
109    if !ui.is_rect_visible(rect) {
110        return;
111    }
112    let t = Tokens::of(ui.ctx());
113    let c = color(&Kit::of(ui.ctx()), mark);
114    let radius = t.radius.widget.round().clamp(0.0, 255.0) as u8;
115    let w = edge_width(&t);
116    let strip = Rect::from_min_max(rect.min, pos2(rect.left() + w, rect.bottom()));
117    ui.painter().rect_filled(
118        strip,
119        CornerRadius {
120            nw: radius,
121            sw: radius,
122            ne: 0,
123            se: 0,
124        },
125        c,
126    );
127    if matches!(mark, Mark::Invalid | Mark::Pending) {
128        ui.painter().rect_stroke(
129            rect,
130            CornerRadius::same(radius),
131            egui::Stroke::new(1.0, c),
132            egui::StrokeKind::Inside,
133        );
134    }
135}
136
137/// Paints one mark's marker in a square.
138pub fn paint_marker(ui: &Ui, rect: Rect, mark: Mark) {
139    let c = color(&Kit::of(ui.ctx()), mark);
140    match icon(mark) {
141        Some(i) => i.paint(ui.painter(), rect, c),
142        None => {
143            ui.painter().text(
144                rect.center() + vec2(0.0, rect.height() * 0.15),
145                Align2::CENTER_CENTER,
146                "*",
147                FontId::proportional(rect.height() * 1.3),
148                c,
149            );
150        }
151    }
152}
153
154/// The marks a field shows as markers, in order: every mark it has.
155pub fn markers(state: &FieldState) -> Vec<Mark> {
156    state.marks()
157}
158
159/// The width the markers of a state take, `side` points each.
160pub fn markers_width(state: &FieldState, side: f32, gap: f32) -> f32 {
161    match markers(state).len() {
162        0 => 0.0,
163        n => n as f32 * side + (n - 1) as f32 * gap,
164    }
165}
166
167/// Paints a state's markers from `at` (the left of the first), centred
168/// on `y`; returns where they end.
169pub fn paint_markers(ui: &Ui, at: egui::Pos2, side: f32, gap: f32, state: &FieldState) -> f32 {
170    let mut x = at.x;
171    for m in markers(state) {
172        let r = Rect::from_min_size(pos2(x, at.y - side / 2.0), vec2(side, side));
173        paint_marker(ui, r, m);
174        x += side + gap;
175    }
176    x - gap
177}
178
179/// The tooltip a field's state adds: the disabled reason (shown while
180/// disabled), the invalid message, "being checked". Returns the
181/// response with them.
182pub fn hover(ui: &Ui, response: &Response, state: &FieldState) -> Response {
183    let mut r = response.clone();
184    let ctx = ui.ctx();
185    if state.is_disabled() {
186        r = r.on_disabled_hover_text(text(ctx, state, Mark::Disabled));
187    }
188    if state.has(Mark::Invalid) {
189        r = r.on_hover_text(text(ctx, state, Mark::Invalid));
190    }
191    if state.pending {
192        r = r.on_hover_text(text(ctx, state, Mark::Pending));
193    }
194    r
195}
196
197/// Gives a field's state to assistive technologies: required, invalid
198/// (its message as the description), disabled (its reason as the
199/// description), read-only, busy while pending. A modified field says so
200/// in its description.
201pub fn access(ctx: &Context, id: Id, state: &FieldState) {
202    if state.is_plain() {
203        return;
204    }
205    let mut said: Vec<String> = Vec::new();
206    for m in state.marks() {
207        if m != Mark::Required && m != Mark::ReadOnly {
208            said.push(text(ctx, state, m));
209        }
210    }
211    let state = state.clone();
212    ctx.accesskit_node_builder(id, move |node| {
213        use egui::accesskit::Invalid;
214        if state.required {
215            node.set_required();
216        }
217        if state.invalid.is_some() {
218            node.set_invalid(Invalid::True);
219        }
220        if state.is_disabled() {
221            node.set_disabled();
222        }
223        if state.read_only {
224            node.set_read_only();
225        }
226        if state.pending {
227            node.set_busy();
228        }
229        if !said.is_empty() {
230            node.set_description(said.join(". "));
231        }
232    });
233}
234
235/// One field as drawn, for agents.
236#[derive(Clone, Debug, PartialEq, Serialize)]
237pub struct FieldRecord {
238    /// Its widget id, as the focus collector writes ids.
239    pub id: String,
240    pub label: String,
241    /// What it edits: `text`, `number`, `path`, `search`, `slider`...
242    pub kind: String,
243    pub state: FieldState,
244}
245
246#[derive(Debug, Default)]
247struct Fields {
248    pass: u64,
249    building: Vec<FieldRecord>,
250    last: Vec<FieldRecord>,
251}
252
253fn rotate(ctx: &Context, s: &mut Fields) {
254    let now = pass(ctx);
255    if s.pass != now {
256        s.pass = now;
257        s.last = std::mem::take(&mut s.building);
258    }
259}
260
261/// Records a field drawn this pass (its widget calls it), so agents see
262/// it in [`fields`] and [`describe`] from the next pass.
263pub fn record(ctx: &Context, id: Id, label: &str, kind: &str, state: &FieldState) {
264    let st = shared::<Fields>(ctx, "core.fields");
265    let mut s = lock(&st);
266    rotate(ctx, &mut s);
267    s.building.push(FieldRecord {
268        id: format!("{id:?}"),
269        label: label.into(),
270        kind: kind.into(),
271        state: state.clone(),
272    });
273}
274
275/// The fields drawn in the last complete pass.
276pub fn fields(ctx: &Context) -> Vec<FieldRecord> {
277    let st = shared::<Fields>(ctx, "core.fields");
278    let mut s = lock(&st);
279    rotate(ctx, &mut s);
280    s.last.clone()
281}
282
283/// The fields drawn in the last pass as agents read them: each one's
284/// label, kind, marks, whether it can be focused and edited, and the
285/// disabled reason and invalid message.
286pub fn describe(ctx: &Context) -> Json {
287    Json::Array(
288        fields(ctx)
289            .into_iter()
290            .map(|f| {
291                let mut d = f.state.describe();
292                if let Some(o) = d.as_object_mut() {
293                    o.insert("id".into(), json!(f.id));
294                    o.insert("label".into(), json!(f.label));
295                    o.insert("kind".into(), json!(f.kind));
296                }
297                d
298            })
299            .collect(),
300    )
301}