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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! [`Card`]: a themed surface — background, radius, shadow or outline — with one child.
use frus_core::{BorderRadius, Color, Insets, Rect, Scene, ShapeBorder};
use frus_layout::Style;
use crate::interaction::Status;
use crate::theme::Theme;
use crate::widget::Widget;
/// The room a card leaves around itself, in logical pixels, when the caller has not
/// said otherwise — the reference's figure. Cards are usually stacked, and two of them
/// flush against each other read as one.
pub const CARD_MARGIN: f32 = 4.0;
/// The default depth of an [`CardVariant::Elevated`] card. Elevation is a **height**,
/// not a blur radius: [`Card::elevation`] says how far off the surface the card sits,
/// and the shadow is derived from it.
pub const CARD_ELEVATION: f32 = 1.0;
/// The room a card leaves **inside** itself by default. An addition of this framework:
/// the reference's card has no padding and leaves it to the content.
pub const CARD_PADDING: f32 = 16.0;
/// Which of the three cards this is.
///
/// The reference has three, and they are not interchangeable: each says something
/// different about how far the card should stand off what is behind it. This used to be
/// one widget drawing a shadow **and** an outline, which is none of the three.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CardVariant {
/// Lifted off the surface by a shadow, no outline. The default.
#[default]
Elevated,
/// A flatter tonal surface: no shadow, no outline. For a card inside something
/// already elevated, where a second shadow only adds noise.
Filled,
/// An outline and no shadow — the quietest of the three, and the one that survives
/// on a background a shadow would be invisible against.
Outlined,
}
/// A card: a surface container, in the theme's colours.
///
/// ```ignore
/// Card::new().child(content) // elevated, the default
/// Card::new().outlined().child(content) // an outline, no shadow
/// Card::new().elevation(6.0).radius(20.0) // further off the surface
/// Card::new().color(theme.scheme.primary_container) // its own colour
/// Card::new().margin(0.0) // flush, for a caller that
/// // spaces its own children
/// ```
///
/// Everything here is a **default**, not a rule: the colour, the rounding, the depth,
/// the margin and the padding are all the caller's to set.
pub struct Card<Msg = crate::callback::Callback> {
/// `None` = the theme's, then [`CardVariant::Elevated`].
variant: Option<CardVariant>,
/// `None` = the theme's, then 16.
padding: Option<f32>,
/// `None` = [`CARD_MARGIN`].
margin: Option<f32>,
/// `None` = [`CARD_ELEVATION`] for an elevated card, and no shadow for the others.
elevation: Option<f32>,
/// `None` = the theme's surface for this variant.
color: Option<Color>,
/// `None` = the theme's shape, then its radius, then the framework's corner.
shape: Option<ShapeBorder>,
children: Vec<Box<dyn Widget<Msg>>>,
}
impl<Msg> Card<Msg> {
/// Creates an elevated card, with a default padding of 16.
pub fn new() -> Self {
Self {
variant: None,
padding: None,
margin: None,
elevation: None,
color: None,
shape: None,
children: Vec::new(),
}
}
/// Chooses the variant.
pub fn variant(mut self, variant: CardVariant) -> Self {
self.variant = Some(variant);
self
}
/// A flat tonal card: no shadow, no outline.
pub fn filled(self) -> Self {
self.variant(CardVariant::Filled)
}
/// An outlined card: a hairline, no shadow.
pub fn outlined(self) -> Self {
self.variant(CardVariant::Outlined)
}
/// Uniform padding **inside** the card. An addition of this framework — the
/// reference's card has none and leaves it to the content — kept because a card
/// whose text touches its own edge is the more common mistake.
pub fn padding(mut self, padding: f32) -> Self {
self.padding = Some(padding);
self
}
/// Uniform room **outside** the card. Defaults to [`CARD_MARGIN`]; `0.0` for a
/// caller that spaces its children itself.
pub fn margin(mut self, margin: f32) -> Self {
self.margin = Some(margin);
self
}
/// How far off the surface the card sits. `0.0` removes the shadow; the default is
/// [`CARD_ELEVATION`] for an elevated card and nothing for the other two.
pub fn elevation(mut self, elevation: f32) -> Self {
self.elevation = Some(elevation);
self
}
/// Overrides the background colour.
pub fn color(mut self, color: Color) -> Self {
self.color = Some(color);
self
}
/// Overrides the corner radii (uniform via `f32`, per corner via [`BorderRadius`]).
/// **What shape the card is** — the reference's `shape` (`card.dart`), over the
/// corners [`radius`](Self::radius) names. They are **one** field, and the last of the
/// two called is the one that counts.
///
/// Milestone 451 gave the card the field and the resolution and — the CHANGELOG
/// notwithstanding — never gave it this builder, so a caller could still only ask for
/// a corner. This is that builder.
#[must_use]
pub fn shape(mut self, shape: ShapeBorder) -> Self {
self.shape = Some(shape);
self
}
/// Rounds the card's corners with `radius`. It is the same field as
/// [`shape`](Self::shape): the last of the two called is the one that counts.
pub fn radius(mut self, radius: impl Into<BorderRadius>) -> Self {
self.shape = Some(ShapeBorder::rounded(radius));
self
}
/// Sets the card's content.
pub fn child(mut self, child: impl Widget<Msg> + 'static) -> Self {
self.children.clear();
self.children.push(Box::new(child));
self
}
/// Which of the three this is: what was asked for, then the theme's, then elevated.
fn kind(&self, theme: Option<&Theme>) -> CardVariant {
self.variant
.or_else(|| theme.and_then(|t| t.widgets.card.variant))
.unwrap_or_default()
}
/// The depth actually used: what was asked for, then the theme's, then the
/// variant's own.
fn depth(&self, theme: &Theme) -> f32 {
self.elevation
.or(theme.widgets.card.elevation)
.unwrap_or(match self.kind(Some(theme)) {
CardVariant::Elevated => CARD_ELEVATION,
CardVariant::Filled | CardVariant::Outlined => 0.0,
})
}
/// The background actually used.
fn background(&self, theme: &Theme) -> Color {
self.color
.or(theme.widgets.card.color)
.unwrap_or(match self.kind(Some(theme)) {
// The two ends of the ladder the reference puts them on
// (`card.dart:313` and `:348`): a card off the page takes the least
// emphasis a container has, a filled one the most.
CardVariant::Elevated => theme.scheme.surface_container_low,
CardVariant::Filled => theme.scheme.surface_container_highest,
CardVariant::Outlined => theme.scheme.surface,
})
}
}
impl<Msg> Default for Card<Msg> {
fn default() -> Self {
Self::new()
}
}
impl<Msg> Card<Msg> {
/// The two spacings, resolved together: caller, then theme, then ours.
fn spacing(&self, theme: Option<&Theme>) -> (f32, f32) {
let padding = self
.padding
.or_else(|| theme.and_then(|t| t.widgets.card.padding))
.unwrap_or(CARD_PADDING);
let margin = self
.margin
.or_else(|| theme.and_then(|t| t.widgets.card.margin))
.unwrap_or(CARD_MARGIN);
(padding, margin)
}
}
impl<Msg> Widget<Msg> for Card<Msg> {
fn style(&self) -> Style {
let (padding, margin) = self.spacing(None);
Style {
padding: Insets::uniform(padding),
margin: Insets::uniform(margin),
..Default::default()
}
}
fn style_themed(&self, theme: &Theme) -> Style {
let (padding, margin) = self.spacing(Some(theme));
Style {
padding: Insets::uniform(padding),
margin: Insets::uniform(margin),
..Default::default()
}
}
fn children(&self) -> &[Box<dyn Widget<Msg>>] {
&self.children
}
fn paint(&self, bounds: Rect, status: Status, theme: &Theme, scene: &mut Scene) {
let o = status.opacity;
let shape = crate::resolve_shape(
self.shape,
theme.widgets.card.shape,
theme.widgets.card.radius,
ShapeBorder::rounded(theme.radius),
);
// The shadow is a rectangle whatever the card is, so it takes the corners the
// shape resolves to and none from one with no rounded form.
let radius = shape
.as_rounded(bounds)
.map(|(_, radius)| radius)
.unwrap_or(BorderRadius::ZERO);
let depth = self.depth(theme);
// The shadow, when the card is off the surface at all. The blur grows with the
// depth and the drop is half of it: a card 1 px up casts a tight shadow under
// its own edge, one 6 px up casts a wide soft one below it.
if depth > 0.0 {
// The reference's shadows for this height (milestone 606).
frus_core::paint_elevation(scene, bounds, radius, depth, theme.scheme.shadow.fade(o));
}
// The outline belongs to exactly one of the three. A shadow *and* a hairline is
// the mash-up this widget used to be.
let border = if self.kind(Some(theme)) == CardVariant::Outlined {
(1.0, theme.scheme.outline_variant.fade(o))
} else {
(0.0, Color::TRANSPARENT)
};
scene.draw_shape(
bounds,
shape.with_side(frus_core::BorderSide::new(border.1, border.0)),
self.background(theme).fade(o),
);
}
fn on_click(&self) -> Option<Msg> {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use frus_core::Primitive;
#[derive(Clone, Debug, PartialEq)]
enum Msg {}
/// **A card takes a whole shape** — which milestone 451 built the field and the
/// resolution for, announced in the CHANGELOG, and never gave a builder. A caller
/// could still only ask for a corner.
#[test]
fn a_card_takes_a_whole_shape_and_not_only_a_corner() {
let corners = |card: &Card<Msg>| {
let mut scene = Scene::new();
Widget::<Msg>::paint(
card,
Rect::new(0.0, 0.0, 200.0, 100.0),
Status::default(),
&Theme::default(),
&mut scene,
);
scene.primitives().iter().find_map(|p| match p {
Primitive::Rect {
rect, radius, blur, ..
} if *blur == 0.0 && rect.width == 200.0 => Some(*radius),
_ => None,
})
};
assert_eq!(
corners(&Card::<Msg>::new().shape(ShapeBorder::stadium())),
Some(BorderRadius::uniform(50.0)),
"half the short side of 200x100"
);
// One field, two builders: the last one called counts.
assert_eq!(
corners(&Card::<Msg>::new().shape(ShapeBorder::stadium()).radius(4.0)),
Some(BorderRadius::uniform(4.0))
);
assert_eq!(
corners(&Card::<Msg>::new().radius(4.0).shape(ShapeBorder::stadium())),
Some(BorderRadius::uniform(50.0))
);
}
/// **A theme can name a card's shape**, and it outranks the plain radius beside it
/// (`card.dart`). Until milestone 451 a card could only be given a corner.
#[test]
fn a_theme_shapes_a_card_over_its_radius() {
let corners = |card: &Card<Msg>, theme: &Theme| {
let mut scene = Scene::new();
Widget::<Msg>::paint(
card,
Rect::new(0.0, 0.0, 200.0, 100.0),
Status::default(),
theme,
&mut scene,
);
scene.primitives().iter().find_map(|p| match p {
Primitive::Rect {
rect, radius, blur, ..
} if *blur == 0.0 && rect.width == 200.0 => Some(*radius),
_ => None,
})
};
let mut theme = Theme::default();
theme.widgets.card.radius = Some(BorderRadius::uniform(2.0));
let card = Card::<Msg>::new();
assert_eq!(
corners(&card, &theme),
Some(BorderRadius::uniform(2.0)),
"a plain radius still speaks"
);
theme.widgets.card.shape = Some(frus_core::ShapeBorder::stadium());
assert_eq!(
corners(&card, &theme),
Some(BorderRadius::uniform(50.0)),
"and a shape beside it outranks it: half the short side of 200x100"
);
assert_eq!(
corners(&Card::<Msg>::new().radius(6.0), &theme),
Some(BorderRadius::uniform(6.0)),
"and the card's own word outranks the theme"
);
}
fn primitives(card: &Card<Msg>) -> Vec<Primitive> {
let mut scene = Scene::new();
Widget::<Msg>::paint(
card,
Rect::new(0.0, 0.0, 200.0, 100.0),
Status::default(),
&Theme::default(),
&mut scene,
);
scene.primitives().to_vec()
}
/// How many surfaces cast a shadow: the card's, or none.
fn shadows(card: &Card<Msg>) -> usize {
crate::shadowprobe::casts(&primitives(card))
}
fn border_width(card: &Card<Msg>) -> f32 {
primitives(card)
.iter()
.filter_map(|p| match p {
Primitive::Rect {
blur, border_width, ..
} if *blur == 0.0 => Some(*border_width),
_ => None,
})
.next()
.expect("the card paints its own surface")
}
#[test]
fn the_three_cards_are_three_different_things() {
// This used to be one card drawing a shadow *and* an outline, which is neither
// of the reference's three. Each now says one thing.
let elevated = Card::<Msg>::new();
assert_eq!(shadows(&elevated), 1, "elevated: a shadow");
assert_eq!(border_width(&elevated), 0.0, "elevated: and no outline");
let filled = Card::<Msg>::new().filled();
assert_eq!(shadows(&filled), 0, "filled: neither");
assert_eq!(border_width(&filled), 0.0);
let outlined = Card::<Msg>::new().outlined();
assert_eq!(shadows(&outlined), 0, "outlined: no shadow");
assert!(border_width(&outlined) > 0.0, "outlined: an outline");
}
#[test]
fn the_three_cards_sit_on_three_different_tones() {
let theme = Theme::default();
let fill = |card: &Card<Msg>| {
primitives(card).iter().find_map(|p| match p {
Primitive::Rect { blur, color, .. } if *blur == 0.0 => Some(*color),
_ => None,
})
};
assert_eq!(
fill(&Card::new()),
Some(theme.scheme.surface_container_low),
"elevated"
);
assert_eq!(
fill(&Card::new().filled()),
Some(theme.scheme.surface_container_highest),
"filled"
);
assert_eq!(fill(&Card::new().outlined()), Some(theme.scheme.surface));
}
#[test]
fn elevation_is_a_height_and_zero_removes_the_shadow() {
assert_eq!(shadows(&Card::<Msg>::new().elevation(0.0)), 0);
assert_eq!(shadows(&Card::<Msg>::new().filled().elevation(3.0)), 1);
// The height it is given is the height its shadows are cast from (milestone 606).
let height = |depth: f32| {
crate::shadowprobe::height(&primitives(&Card::<Msg>::new().elevation(depth)))
};
assert_eq!(height(1.0), 1.0);
assert_eq!(height(6.0), 6.0);
}
#[test]
fn a_card_leaves_room_around_itself_unless_told_not_to() {
// The reference's card carries its own margin; two flush against each other
// read as one surface.
assert_eq!(
Widget::<Msg>::style(&Card::new()).margin,
Insets::uniform(CARD_MARGIN)
);
assert_eq!(
Widget::<Msg>::style(&Card::<Msg>::new().margin(0.0)).margin,
Insets::uniform(0.0)
);
}
#[test]
fn the_colour_and_the_rounding_are_the_callers() {
let mine = Color::rgb8(10, 200, 90);
let card = Card::<Msg>::new().color(mine).radius(20.0);
let found = primitives(&card).iter().find_map(|p| match p {
Primitive::Rect {
blur,
color,
radius,
..
} if *blur == 0.0 => Some((*color, *radius)),
_ => None,
});
assert_eq!(found, Some((mine, BorderRadius::uniform(20.0))));
}
}