1use 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
50pub 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
65pub 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
78pub 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
98pub fn edge_width(t: &Tokens) -> f32 {
100 (t.space.xs * 0.75).max(2.0)
101}
102
103pub 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
137pub 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
154pub fn markers(state: &FieldState) -> Vec<Mark> {
156 state.marks()
157}
158
159pub 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
167pub 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
179pub 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
197pub 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#[derive(Clone, Debug, PartialEq, Serialize)]
237pub struct FieldRecord {
238 pub id: String,
240 pub label: String,
241 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
261pub 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
275pub 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
283pub 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}