1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! [`Steps`]: a **step indicator** — the numbered breadcrumb of a multi-step form
//! or wizard, in the Material `Stepper` style.
//!
//! A row of round numbered markers joined by connectors, each in one of three
//! states: **done** (a tick, accent), **current** (the number, accent), **upcoming**
//! (the number, a bordered surface). A label sits under each marker.
//!
//! The widget is **purely visual**: navigation (Next/Previous) and per-step
//! validation stay in the application (one [`crate::form::Form`] per step, buttons
//! that change the current step). Since the name `Stepper` is already taken by the
//! −/value/+ numeric picker, this indicator is called `Steps`.
use frus_core::{
Color, Point, Rect, ResolvedTextStyle, Role, Scene, SemanticsProperties, TextStyle,
};
use frus_layout::{Align, Dimension, FlexDirection, Justify, Style};
use crate::flex::Flex;
use crate::icons::Icons;
use crate::interaction::Status;
use crate::theme::Theme;
use crate::widget::Widget;
/// The diameter of a (round) marker.
const MARKER_D: f32 = 28.0;
/// The radius of a marker.
const R: f32 = MARKER_D / 2.0;
/// The marker → label gap.
const LABEL_GAP: f32 = 8.0;
/// The figure inside a marker. The reference writes this one out too — a step's index is
/// 12 px there, with the step's own style as the way to change it.
const NUM_SIZE: f32 = 12.0;
/// Total height of the indicator (marker + label).
const HEIGHT: f32 = 56.0;
/// A step's label: what the caller said, else what the theme says, else the reference's —
/// a step is titled in `bodyLarge`.
///
/// The reference sets that title *beside* the marker and this one sits *under* it: the
/// placement is ours, the role is read rather than invented, and an application that wants
/// a caption under its markers says so on the widget or in the theme.
///
/// **Resolved once** so that the number the bar is measured with is the number the glyphs
/// are drawn at. Resolving is the single place the reader's font setting is applied
/// (milestone 403).
fn label_style(over: Option<TextStyle>, theme: Option<&Theme>) -> ResolvedTextStyle {
over.or(theme.and_then(|t| t.widgets.steps.label_text_style))
.unwrap_or_else(|| crate::theme::type_scale(theme).body_large)
.resolved()
}
/// The figure inside a marker.
///
/// Untold it is [`ResolvedTextStyle::exact`] — **geometry, not type**: it sits inside a
/// circle of a fixed `MARKER_D`, and a figure that grew with the reader's setting would
/// leave it. A style that *is* told is resolved like any other, because a caller who names
/// this one has taken that decision back.
fn index_style(over: Option<TextStyle>, theme: Option<&Theme>) -> ResolvedTextStyle {
match over.or(theme.and_then(|t| t.widgets.steps.index_text_style)) {
Some(style) => style.resolved(),
None => ResolvedTextStyle::exact(NUM_SIZE),
}
}
/// The bar's height: the constant, unless the labels the reader asked to enlarge no longer
/// fit under the markers.
fn bar_height(label: &ResolvedTextStyle) -> f32 {
HEIGHT.max(MARKER_D + LABEL_GAP + label.line_height() + 4.0)
}
/// The step indicator of a multi-step form.
///
/// ```
/// use frus_widgets::Steps;
/// // Three steps, the second in progress (so the first counts as "done").
/// let steps: Steps<()> = Steps::new(["Account", "Profile", "Review"]).current(1);
/// ```
pub struct Steps<Msg = crate::callback::Callback> {
labels: Vec<String>,
current: usize,
/// Overridden accent color; `None` = the theme's `primary`.
color: Option<Color>,
/// An **explicit** per-step "done" mask (validity). Empty → the default rule
/// (`i < current`, see [`completed`](Self::completed)).
completed: Vec<bool>,
label_text_style: Option<TextStyle>,
index_text_style: Option<TextStyle>,
/// Empty, or **one** row of clickable hotspots laid over the markers when
/// [`on_tap`](Self::on_tap) is supplied.
children: Vec<Box<dyn Widget<Msg>>>,
}
impl<Msg: Clone + 'static> Steps<Msg> {
/// Creates an indicator from the step labels; the current step is the first one.
pub fn new(labels: impl IntoIterator<Item = impl Into<String>>) -> Self {
Self {
labels: labels.into_iter().map(Into::into).collect(),
current: 0,
color: None,
completed: Vec::new(),
label_text_style: None,
index_text_style: None,
children: Vec::new(),
}
}
/// The captions under the markers, over the theme's and the reference's.
#[must_use]
pub fn label_text_style(mut self, style: TextStyle) -> Self {
self.label_text_style = Some(style);
self
}
/// The figures inside the markers, over the theme's and the framework's.
///
/// Naming one also puts it back **under the reader's font setting**. Untold, the figure
/// is geometry rather than type — it sits inside a circle of a fixed diameter, and one
/// that grew with the reader's setting would leave it. A caller who names this style has
/// taken that decision back.
#[must_use]
pub fn index_text_style(mut self, style: TextStyle) -> Self {
self.index_text_style = Some(style);
self
}
/// Explicitly marks the **done** steps (a tick) with one flag per step — typically each
/// step's **validity**, rather than position alone. Without this call, a step counts as
/// "done" if it precedes the current one (`i < current`).
pub fn completed(mut self, flags: impl IntoIterator<Item = bool>) -> Self {
self.completed = flags.into_iter().collect();
self
}
/// Sets the **current** step (the earlier ones are "done", the later ones "upcoming").
/// Clamped to the last index.
pub fn current(mut self, index: usize) -> Self {
self.current = index.min(self.labels.len().saturating_sub(1));
self
}
/// Overrides the accent color (done and current markers + the connectors crossed).
pub fn color(mut self, color: Color) -> Self {
self.color = Some(color);
self
}
/// Makes the markers **clickable**: clicking step `i`'s marker emits `on_tap(i)` (to jump
/// there — typically a step already visited). Lays a row of transparent clickable zones
/// **exactly** over the markers (a `SpaceBetween` distribution of marker-sized boxes),
/// without changing the rendering.
pub fn on_tap(mut self, on_tap: impl Fn(usize) -> Msg) -> Self {
let mut row: Flex<Msg> = Flex::row().justify(Justify::SpaceBetween);
for (i, label) in self.labels.iter().enumerate() {
row = row.child(Hotspot {
label: label.clone(),
message: on_tap(i),
});
}
self.children = vec![Box::new(row)];
self
}
}
impl<Msg> Steps<Msg> {
fn sizing(&self, theme: Option<&Theme>) -> Style {
let label = label_style(self.label_text_style, theme);
Style {
height: Dimension::Length(bar_height(&label)),
// Any row of hotspots occupies the top, the markers' band.
flex_direction: FlexDirection::Column,
align: Align::Stretch,
..Default::default()
}
}
/// Is step `i` **done**? The explicit mask if one is supplied, otherwise `i < current`.
fn is_done(&self, i: usize) -> bool {
if self.completed.is_empty() {
i < self.current
} else {
self.completed.get(i).copied().unwrap_or(false)
}
}
/// The x of marker `i`'s centre within `bounds` (markers spread from edge to edge).
fn center_x(&self, bounds: Rect, i: usize) -> f32 {
let n = self.labels.len();
if n <= 1 {
bounds.x + bounds.width * 0.5
} else {
bounds.x + R + i as f32 * (bounds.width - 2.0 * R) / (n as f32 - 1.0)
}
}
}
impl<Msg: Clone> Widget<Msg> for Steps<Msg> {
/// It asks to **fill the width it is offered** rather than declaring one — see
/// [`Widget::fill_axes`]. A `width: 100%` resolves against the parent's *resolved*
/// width, which a parent that shrink-wraps does not have yet.
fn style(&self) -> Style {
self.sizing(None)
}
fn style_themed(&self, theme: &Theme) -> Style {
self.sizing(Some(theme))
}
/// The width it was **offered**, not the width its parent came out at.
fn fill_axes(&self, _theme: &Theme) -> crate::widget::FillAxes {
crate::widget::FillAxes::WIDTH
}
fn children(&self) -> &[Box<dyn Widget<Msg>>] {
&self.children
}
fn paint(&self, bounds: Rect, status: Status, theme: &Theme, scene: &mut Scene) {
let n = self.labels.len();
if n == 0 {
return;
}
let o = status.opacity;
let accent = self.color.unwrap_or(theme.primary);
let cy = bounds.y + R;
// Connectors (under the markers): crossed (accent) up to the current step, else border.
for i in 0..n.saturating_sub(1) {
let x0 = self.center_x(bounds, i) + R;
let x1 = self.center_x(bounds, i + 1) - R;
let col = if self.is_done(i) {
accent
} else {
theme.border
};
let rect = Rect::new(x0, cy - 1.0, (x1 - x0).max(0.0), 2.0);
scene.draw_rect(rect, col.fade(o), 0.0, 0.0, Color::TRANSPARENT);
}
// Markers + numbers/ticks + labels.
for i in 0..n {
let cx = self.center_x(bounds, i);
let rect = Rect::new(cx - R, cy - R, MARKER_D, MARKER_D);
let current = i == self.current;
// The current step shows its number (even when valid); the others show a tick
// if done (validity), otherwise their number.
let completed = !current && self.is_done(i);
let (fill, bw, bc) = if completed || current {
(accent, 0.0, Color::TRANSPARENT)
} else {
(theme.surface, 1.5, theme.border)
};
scene.draw_rect(rect, fill.fade(o), R, bw, bc.fade(o));
if completed {
// A tick (a centred 16 px icon) on an accent background.
let path = Icons::CHECK.placed(16.0, cx - 8.0, cy - 8.0, theme.direction);
scene.fill_path(&path, theme.on_primary.fade(o));
} else {
let num = (i + 1).to_string();
let num_style = index_style(self.index_text_style, Some(theme));
let m = frus_text::measure_resolved(&num, &num_style);
let color = if current {
theme.on_primary
} else {
theme.on_surface
};
let p = Point::new(cx - m.width * 0.5, cy - m.height * 0.5);
scene.text(p, num, &num_style, color.fade(o));
}
// The label under the marker, centred; dimmed away from the current step.
let label = &self.labels[i];
let label_s = label_style(self.label_text_style, Some(theme));
let lm = frus_text::measure_resolved(label, &label_s);
let alpha = if current { o } else { 0.6 * o };
// Centred on the marker, **kept inside the bar**. The first and last markers
// sit one radius from the edges, so a label wider than `MARKER_D` hangs off
// the end of the widget — which it always could, and which a label read at
// the reference's `bodyLarge` rather than at a private 12 px makes ordinary.
let lx = (cx - lm.width * 0.5)
.clamp(bounds.x, (bounds.x + bounds.width - lm.width).max(bounds.x));
let p = Point::new(lx, bounds.y + MARKER_D + LABEL_GAP);
scene.text(p, label.clone(), &label_s, theme.on_surface.fade(alpha));
}
}
fn on_click(&self) -> Option<Msg> {
None
}
}
/// A **transparent** clickable zone the size of a marker, laid over it when
/// [`Steps::on_tap`] is used: it draws nothing but captures the click (and the keyboard
/// focus) to jump to the matching step.
struct Hotspot<Msg> {
label: String,
message: Msg,
}
impl<Msg: Clone> Widget<Msg> for Hotspot<Msg> {
fn style(&self) -> Style {
Style {
width: Dimension::Length(MARKER_D),
height: Dimension::Length(MARKER_D),
..Default::default()
}
}
fn children(&self) -> &[Box<dyn Widget<Msg>>] {
&[]
}
fn paint(&self, _bounds: Rect, _status: Status, _theme: &Theme, _scene: &mut Scene) {}
fn on_click(&self) -> Option<Msg> {
Some(self.message.clone())
}
fn focusable(&self) -> bool {
true
}
fn semantics(&self) -> Option<SemanticsProperties> {
Some(
SemanticsProperties::new(Role::Button)
.label(self.label.clone())
.clickable(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use frus_core::Primitive;
fn paint_steps(steps: &Steps<()>) -> Vec<Primitive> {
let mut scene = Scene::new();
Widget::<()>::paint(
steps,
Rect::new(0.0, 0.0, 400.0, HEIGHT),
Status::default(),
&Theme::default(),
&mut scene,
);
scene.primitives().to_vec()
}
#[test]
fn current_is_clamped_to_last() {
let steps = Steps::<()>::new(["A", "B", "C"]).current(9);
assert_eq!(steps.current, 2);
assert_eq!(Steps::<()>::new(Vec::<String>::new()).current(3).current, 0);
}
#[test]
fn markers_reflect_progress() {
// 4 steps, the 3rd (index 2) current: 0 and 1 done; 2 current; 3 upcoming.
let prims = paint_steps(&Steps::<()>::new(["A", "B", "C", "D"]).current(2));
let has_text = |t: &str| {
prims
.iter()
.any(|p| matches!(p, Primitive::Text { text, .. } if text == t))
};
// Done → ticks (no number); current → "3"; upcoming → "4".
assert!(
has_text("3") && has_text("4"),
"the numbers of the current and upcoming steps"
);
assert!(
!has_text("1") && !has_text("2"),
"the done steps show a tick"
);
// One tick (a filled path) per done step.
let checks = prims
.iter()
.filter(|p| matches!(p, Primitive::Path { fill: Some(_), .. }))
.count();
assert_eq!(checks, 2, "two ticks for the two done steps");
// All the labels are drawn.
assert!(has_text("A") && has_text("B") && has_text("C") && has_text("D"));
}
#[test]
fn completed_mask_overrides_position() {
// Without a mask: "done" = position (i < current).
let default = Steps::<()>::new(["A", "B", "C"]).current(2);
assert!(default.is_done(0) && default.is_done(1));
assert!(
!default.is_done(2),
"the current step is not done by default"
);
// With a mask (validity): independent of position.
let masked = Steps::<()>::new(["A", "B", "C"])
.current(1)
.completed([false, false, true]);
assert!(
!masked.is_done(0),
"step 0 invalid → not done despite i < current"
);
assert!(
masked.is_done(2),
"step 2 valid → done even though i > current"
);
// A mask shorter than the number of steps: the missing ones are not done.
let short = Steps::<()>::new(["A", "B", "C"]).completed([true]);
assert!(short.is_done(0) && !short.is_done(1) && !short.is_done(2));
}
#[test]
fn on_tap_overlays_clickable_hotspots() {
#[derive(Clone, Debug, PartialEq)]
enum Msg {
Go(usize),
}
// Without on_tap: no children (purely visual).
let plain = Steps::<Msg>::new(["A", "B", "C"]).current(1);
assert!(Widget::<Msg>::children(&plain).is_empty());
// With on_tap: a row of children whose every marker emits its index.
let tappable = Steps::new(["A", "B", "C"]).current(1).on_tap(Msg::Go);
let row = Widget::<Msg>::children(&tappable);
assert_eq!(row.len(), 1, "a single row of hotspots");
let spots = row[0].children();
assert_eq!(spots.len(), 3, "one hotspot per step");
assert_eq!(spots[0].on_click(), Some(Msg::Go(0)));
assert_eq!(spots[2].on_click(), Some(Msg::Go(2)));
assert!(spots[0].focusable(), "a hotspot is focusable");
}
}