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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
//! An avatar: who a person is, at a glance; a group of them laid over one another; and the dot that says whether a
//! person is there, on an avatar or on its own.
use std::sync::Arc;
use super::{
icons, names,
part_style::Length,
recipe::{Case, Name, Recipe, ResolvedPart, ResolvedRecipe},
shared::{IconChoice, glyph},
theme::{Themed, current_theme},
};
use crate::{
app::theme::{PaletteColor, RadiusSize, Theme, TypographyStyle},
components::{Row, Stack},
layout::{Alignment, layout_kind::Justify, stack_alignment::StackAlignment, text_style::FontWeight},
node::{Element, border::Border},
};
/// The sizes of an avatar: the side of its square, from 20 to 56.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum AvatarSize {
/// 20: beside a line of small text.
Xs,
/// 24: in a list of suggestions, a header.
Sm,
/// 32: in a row of a list, a bar.
#[default]
Md,
/// 40: an account in a drawer, a notification.
Lg,
/// 56: a profile.
Xl,
}
names!(AvatarSize {
Xs => "xs",
Sm => "sm",
Md => "md",
Lg => "lg",
Xl => "xl",
});
/// The shape of an avatar.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum AvatarShape {
/// A circle: a person.
#[default]
Circle,
/// A square with the corners of a control: a team, a workspace, a bot.
Square,
}
/// Whether the person an avatar shows is there: the dot at its corner.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AvatarPresence {
/// There, and free to answer.
Online,
/// There, but away from the keyboard.
Away,
/// There, and not to be disturbed.
Busy,
/// Not there.
Offline,
}
names!(AvatarPresence {
Online => "online",
Away => "away",
Busy => "busy",
Offline => "offline",
});
/// The parts of an avatar a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AvatarPart {
/// The avatar with its dot of presence: as large as its face, which the dot stands over.
Root,
/// The shape: its side, its corners, its fill, and the ring it has in a group. What it holds is clipped to it.
Face,
/// The letters of the name, on the face's fill.
Initials,
/// The icon in place of the letters: for what is not a person, or a name that has none.
Icon,
/// The picture, which fills the face.
Image,
/// The dot at the bottom end of the face that says whether the person is there.
Presence,
}
names!(AvatarPart {
Root => "root",
Face => "face",
Initials => "initials",
Icon => "icon",
Image => "image",
Presence => "presence",
});
/// The states of an avatar a recipe styles. The [`AvatarPresence`] it has is
/// one too, under its own name: `.state(AvatarPresence::Away, AvatarPart::Presence, ..)`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AvatarState {
/// Its shape is [`AvatarShape::Square`].
Square,
}
names!(AvatarState {
Square => "square",
});
/// What builds an avatar's nodes: a theme's in place of the default one.
pub type AvatarRenderer = Arc<dyn Fn(AvatarView) -> Element + Send + Sync>;
/// The letters an avatar shows for `name`: the first of its first word and the first of its last, in capitals.
/// "Ivan Zaida" is "IZ", "Ivan" is "I", and a name with no letter or digit has none.
fn initials(name: &str) -> String {
let first = |word: &str| word.chars().find(|char| char.is_alphanumeric());
let words: Vec<&str> = name.split_whitespace().filter(|word| first(word).is_some()).collect();
let picked = match words.as_slice() {
[] => Vec::new(),
[one] => vec![*one],
[first_word, .., last_word] => vec![*first_word, *last_word],
};
picked
.into_iter()
.filter_map(first)
.flat_map(char::to_uppercase)
.collect()
}
/// An avatar: who a person is, at a glance. The initials of the name on a
/// fill, a picture in their place, or an icon for what is not a person.
///
/// ```
/// use lurq::ui::{Avatar, AvatarPresence, AvatarShape, AvatarSize, icons};
///
/// let ivan = Avatar::new("Ivan Zaida").presence(AvatarPresence::Online);
/// let profile = Avatar::new("Ivy Chen").size(AvatarSize::Xl);
/// let bot = Avatar::new("Build bot").icon(icons::TERMINAL).shape(AvatarShape::Square);
/// ```
///
/// With [`picture`](Self::picture) it shows a picture, clipped to its shape; the
/// initials stay in its place while the picture loads and when it fails. An
/// avatar is read, not operated: to tooling that reads the tree it is an image
/// called by the name.
pub struct Avatar {
name: Arc<str>,
/// What the face shows in place of the initials: the count at the end of a group.
text: Option<Arc<str>>,
icon: Option<IconChoice>,
picture: Option<super::Picture>,
size: Name,
shape: AvatarShape,
presence: Option<AvatarPresence>,
presence_label: Option<Arc<str>>,
states: Vec<Name>,
rules: Recipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl Avatar {
/// The avatar of `name`: its initials on a fill. A name with no letters shows the icon of a person.
pub fn new(name: &str) -> Self {
Self {
name: Arc::from(name),
text: None,
icon: None,
picture: None,
size: AvatarSize::default().into(),
shape: AvatarShape::default(),
presence: None,
presence_label: None,
states: Vec::new(),
rules: Recipe::new(),
id: None,
key: None,
}
}
/// The face of a group's count: "+3", called "3 more".
pub(crate) fn count(hidden: usize) -> Self {
let locale = super::current_locale();
let mut avatar = Self::new(&locale.count(&locale.common.more_count, hidden));
avatar.text = Some(Arc::from(format!("+{hidden}")));
avatar
}
/// The letters the face shows, in place of the initials it takes from the name: the app's own way of making
/// them ("Ada Lovelace" as "AL" where the first two words give them, a project's one letter). The name stays
/// what tooling that reads the tree calls the avatar. Empty letters show the icon of a person, as a name with no
/// letters does.
///
/// ```
/// use lurq::ui::Avatar;
///
/// let ada = Avatar::new("Ada King Lovelace").initials("AK");
/// ```
pub fn initials(mut self, letters: &str) -> Self {
self.text = Some(Arc::from(letters));
self
}
/// A picture of the person in place of the initials, which fills the avatar and is clipped to its shape:
/// a [`Picture`](super::Picture) of pixels the app has, of a file or bytes it decodes, of a resource or an
/// address the app's loader reads, with a cache key and a size to decode to where it wants them. While the
/// picture is on its way, and when it did not come, the avatar shows its initials or its icon, and they go
/// out over the picture when it is there.
///
/// ```
/// use lurq::ui::{Avatar, Picture};
///
/// let ivan = Avatar::new("Ivan Zaida").picture(Picture::from_file("ivan.jpg").downscale_to(112, 112));
/// ```
///
/// The picture is a component as every picture is: the avatar is laid in a tree that a component renders.
pub fn picture(mut self, picture: impl Into<super::Picture>) -> Self {
self.picture = Some(picture.into());
self
}
/// An icon in place of the initials, by its name in the theme: for what is not a person, a bot or a team.
/// `None` is no icon at all, not even the person a name with no letters has.
pub fn icon(mut self, icon: impl Into<IconChoice>) -> Self {
self.icon = Some(icon.into());
self
}
/// An [`AvatarSize`], or a size the theme's recipe names.
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.size = size.into();
self
}
pub fn shape(mut self, shape: AvatarShape) -> Self {
self.shape = shape;
self
}
/// The dot at its corner that says whether the person is there; `None` for no dot.
pub fn presence(mut self, presence: impl Into<Option<AvatarPresence>>) -> Self {
self.presence = presence.into();
self
}
/// What the dot says to tooling that reads the tree, after the name, in place of the presence's own word
/// ("online", "away", "busy", "offline"): the app's word for it, or the word in another language.
pub fn presence_label(mut self, label: &str) -> Self {
self.presence_label = Some(Arc::from(label));
self
}
/// Puts the avatar in a state the theme's recipe names, or takes it out.
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
/// Styles one part of this avatar over what the theme gives it.
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(super::PartStyle) -> super::PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
/// Lays rules over the theme's recipe for this avatar: what the component
/// it is in says of it in this place, as a group gives its avatars a ring.
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
/// The id of the avatar's root.
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
/// Builds the avatar in `theme`. Converting an avatar into an element does
/// this in the theme of what is being rendered.
pub fn build(self, theme: &Theme) -> Element {
let mut case = Case {
variant: None,
size: Some(self.size),
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(AvatarState::Square, self.shape == AvatarShape::Square);
if let Some(presence) = self.presence {
case = case.state(presence, true);
}
let view = AvatarView {
initials: self.text.as_deref().map_or_else(|| initials(&self.name), str::to_owned),
name: self.name,
icon: self.icon,
picture: self.picture,
size: self.size,
shape: self.shape,
presence: self.presence,
presence_label: self.presence_label,
recipe: theme
.resolve::<Avatar>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
id: self.id,
key: self.key,
};
match theme.renderer::<Avatar>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<Avatar> for Element {
fn from(avatar: Avatar) -> Self {
avatar.build(¤t_theme())
}
}
/// An avatar as a renderer sees it: what it was given and the style of its parts.
pub struct AvatarView {
/// Who it is: what tooling that reads the tree calls it.
pub name: Arc<str>,
/// The letters it shows: the initials of the name, or the count at the end of a group.
pub initials: String,
/// The icon it was given in place of its initials: a name, or `None` for no icon at all.
pub icon: Option<IconChoice>,
/// The picture it shows in place of its initials.
pub picture: Option<super::Picture>,
pub size: Name,
pub shape: AvatarShape,
pub presence: Option<AvatarPresence>,
/// What the dot says to tooling in place of the presence's own word.
pub presence_label: Option<Arc<str>>,
/// The style of each part of this avatar.
pub recipe: ResolvedRecipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl AvatarView {
/// The style of a part, as this avatar is to be drawn.
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
/// What tooling that reads the tree calls the avatar: its name, and whether the person is there.
pub fn label(&self) -> String {
match self.presence {
Some(presence) => format!(
"{}, {}",
self.name,
self.presence_label.as_deref().unwrap_or(presence.as_str())
),
None => self.name.to_string(),
}
}
/// What the face shows where it has no picture, and while its picture
/// loads or once it failed: the icon it was given, its initials, or the
/// icon of a person for a name with no letters.
pub fn fallback(&self) -> Element {
self.fallback_maker()()
}
/// What builds [`fallback`](Self::fallback), again for each time it is shown: an element is built for one place.
fn fallback_maker(&self) -> impl Fn() -> Element + Send + Sync + 'static {
let icon = match (self.icon, self.initials.is_empty()) {
(Some(IconChoice(icon)), _) => icon,
(None, true) => Some(Name::from(icons::USER)),
(None, false) => None,
};
// Its id is taken once here, so that each time it is built again it is the same.
let (part, id) = match icon {
Some(_) => (AvatarPart::Icon, self.recipe.part_id(AvatarPart::Icon)),
None => (AvatarPart::Initials, self.recipe.part_id(AvatarPart::Initials)),
};
let part = self.part(part).unnamed();
let initials = self.initials.clone();
move || {
let element = match icon {
Some(icon) => glyph(&part, icon, false),
None => Row::new().part(&part).child(part.text(&initials).nowrap()).into(),
};
match &id {
Some(id) => element.id(id.clone()),
None => element,
}
}
}
/// The face: the shape in its fill, with what it shows centered in it and clipped to it.
pub fn face(&self) -> Row {
Row::new()
.align_items(Alignment::Center)
.justify(Justify::Center)
.part(&self.part(AvatarPart::Face))
.clip()
}
/// The picture, filling the face in the style of its part, with the fallback in its place while it is on
/// its way, once it did not come, and where it has no source.
fn picture_in_face(&self, picture: super::Picture) -> Element {
use super::{PictureFit, PicturePart, PictureSize};
let fallback = self.fallback_maker();
picture
.size(PictureSize::Xs)
.width(Length::Fill)
.height(Length::Fill)
.fit(PictureFit::Cover)
.bare(true)
// The avatar is what tooling reads; its picture says nothing of its own.
.decorative(true)
.rules(&self.recipe.rules_for(AvatarPart::Image, PicturePart::Image))
.fallback(fallback)
.into()
}
/// The dot of presence in the style of its part, or nothing where the avatar has none.
pub fn presence_dot(&self) -> Option<Row> {
self.presence.map(|_| Row::new().part(&self.part(AvatarPart::Presence)))
}
/// How the default renderer builds an avatar: the face with its picture or
/// its fallback, and the dot of presence over its bottom end corner.
pub fn render(self) -> Element {
let mut this = self;
let face = this.face();
let face = match this.picture.take() {
Some(picture) => face.child(this.picture_in_face(picture)),
None => face.child(this.fallback()),
};
// The dot and the ring of a group stand outside the face: nothing of the avatar clips them.
let mut root = Stack::new()
.stack_align(StackAlignment::BottomEnd)
.part(&this.part(AvatarPart::Root))
.overflow_visible()
.describe("a11y_role", "img")
.describe("a11y_name", this.label())
.child(face);
if let Some(dot) = this.presence_dot() {
root = root.child(dot);
}
if let Some(id) = this.id {
root = root.id(id);
}
if let Some(key) = this.key {
root = root.key(key);
}
root.into()
}
}
impl crate::ui::Styled for Avatar {
type Component = Self;
fn rules(self, rules: &crate::ui::Recipe) -> Self {
Self::rules(self, rules)
}
fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
Self::state(self, state, on)
}
}
impl Themed for Avatar {
const NAME: &'static str = "avatar";
type Renderer = AvatarRenderer;
fn parts() -> crate::ui::Declared {
AvatarPart::declared()
}
fn states() -> crate::ui::Declared {
AvatarState::declared()
}
/// The design's avatar (`pencil/lurq-design-system.pen`, Avatar, Presence and
/// Avatar sizes): a circle of 32 in the muted fill with the initials in the
/// foreground, 12 and medium; 20, 24, 40 and 56 with initials of 9, 10, 14
/// and 18; a square one with the corners of a control; the icon of a person,
/// half the side, in the muted foreground where there are no initials. The
/// dot of presence is 10 at the bottom end of a 32, ringed 2 in the
/// background's color, in the success color while the person is online.
fn recipe() -> Recipe {
use AvatarPart::{Face, Icon, Image, Initials, Presence};
use PaletteColor::{Background, Destructive, Foreground, Muted, MutedForeground, Success, Warning};
let recipe = Recipe::new()
.base(Face, |s| {
s.square(32.0)
.radius(RadiusSize::Full)
.background(Muted)
.foreground(Foreground)
})
.base(Initials, |s| {
s.typography(TypographyStyle::Label)
.font_size(12.0)
.weight(FontWeight::Medium)
.line_height(1.0)
.foreground(Foreground)
})
.base(Icon, |s| s.width(16.0).foreground(MutedForeground))
.base(Image, |s| s.square(Length::Fill).radius(RadiusSize::Full))
.base(Presence, |s| {
s.square(10.0)
.radius(RadiusSize::Full)
.border(Border::outside(2.0, Background))
.background(Success)
})
.state(AvatarState::Square, Face, |s| s.radius(RadiusSize::Md))
.state(AvatarState::Square, Image, |s| s.radius(RadiusSize::Md))
.state(AvatarPresence::Online, Presence, |s| s.background(Success))
.state(AvatarPresence::Away, Presence, |s| s.background(Warning))
.state(AvatarPresence::Busy, Presence, |s| s.background(Destructive))
.state(AvatarPresence::Offline, Presence, |s| s.background(MutedForeground));
// The side, the letters, the icon at half the side, and a dot that keeps to the corner of the face.
[
(AvatarSize::Xs, 20.0, 9.0, 6.0),
(AvatarSize::Sm, 24.0, 10.0, 8.0),
(AvatarSize::Lg, 40.0, 14.0, 12.0),
(AvatarSize::Xl, 56.0, 18.0, 14.0),
]
.into_iter()
.fold(recipe, |recipe, (size, side, letters, dot)| {
recipe
.size(size, Face, |s| s.square(side))
.size(size, Initials, |s| s.font_size(letters))
.size(size, Icon, |s| s.width(side / 2.0))
.size(size, Presence, |s| s.square(dot))
})
}
}
/// Whether a person is there, on its own: the dot of an avatar with no avatar under it, beside a name in a list
/// or in a line of text.
///
/// ```
/// use lurq::ui::{AvatarPresence, AvatarSize, Presence};
///
/// let online = Presence::new(AvatarPresence::Online);
/// // The dot of a large avatar, called as the app calls it.
/// let away = Presence::new(AvatarPresence::Away).size(AvatarSize::Lg).label("Away until 15:00");
/// ```
///
/// It is the [`AvatarPart::Presence`] of the theme's recipe for an avatar, in the color of its
/// [`AvatarPresence`] and at the side of the dot of an avatar of its size (10 unless told): a theme that restyles
/// an avatar's dot restyles this one. It has no ring, since there is no face to part it from. To tooling that
/// reads the tree it is an image called by the presence's word, "online", or by its label. The dot on an avatar
/// is [`Avatar::presence`].
pub struct Presence {
presence: AvatarPresence,
size: Name,
label: Option<Arc<str>>,
states: Vec<Name>,
rules: Recipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl Presence {
/// The dot of `presence`, as large as on an avatar of 32.
pub fn new(presence: AvatarPresence) -> Self {
Self {
presence,
size: AvatarSize::default().into(),
label: None,
states: Vec::new(),
rules: Recipe::new(),
id: None,
key: None,
}
}
/// The size of the avatar whose dot this is: an [`AvatarSize`], or a size the theme's recipe for an avatar
/// names. The dots are 6, 8, 10, 12 and 14.
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.size = size.into();
self
}
/// What the dot is called to tooling that reads the tree, in place of the presence's own word.
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
/// Puts the dot in a state the theme's recipe for an avatar names, or takes it out.
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
/// Styles a part of the avatar's recipe for this dot over what the theme gives it: [`AvatarPart::Presence`]
/// is the dot.
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(super::PartStyle) -> super::PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
/// Lays rules over the theme's recipe for an avatar, for this dot.
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
/// Builds the dot in `theme`. Converting it into an element does this in the theme of what is being rendered.
pub fn build(self, theme: &Theme) -> Element {
let mut case = Case::new()
.size(self.size)
.breakpoint(super::current_breakpoint())
.state(self.presence, true);
for state in &self.states {
case = case.state(state.clone(), true);
}
// No ring: it parts the dot from a face, and here there is none. What the app says of the dot comes after.
let rules = Recipe::new()
.base(AvatarPart::Presence, |s| {
s.border(Border::outside(0.0, PaletteColor::Background))
})
.extend(&self.rules);
let part = theme
.resolve::<Avatar>(&case, Some(&rules))
.owned_by(self.id.as_ref())
.part(AvatarPart::Presence);
let label = self.label.unwrap_or_else(|| Arc::from(self.presence.as_str()));
let mut dot = Row::new()
.part(&part)
.flex_shrink(0.0)
.describe("a11y_role", "img")
.describe("a11y_name", label);
if let Some(id) = self.id {
dot = dot.id(id);
}
if let Some(key) = self.key {
dot = dot.key(key);
}
dot.into()
}
}
impl From<Presence> for Element {
fn from(presence: Presence) -> Self {
presence.build(¤t_theme())
}
}
/// The parts of a group of avatars a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AvatarGroupPart {
/// The row of avatars: how far each lies over the one before it, as a gap below nothing.
Root,
/// What the group says of the face of each avatar in it: laid over the theme's recipe for an avatar's face.
Item,
/// What the group says of the face of the count at its end, over what it says of an item.
More,
}
names!(AvatarGroupPart {
Root => "root",
Item => "item",
More => "more",
});
/// What builds a group of avatars' nodes: a theme's in place of the default one.
pub type AvatarGroupRenderer = Arc<dyn Fn(AvatarGroupView) -> Element + Send + Sync>;
/// The sizes of a group's avatars: an avatar's.
pub type AvatarGroupSize = AvatarSize;
/// Avatars laid over one another: who is in a document, who reviews a change.
///
/// ```
/// use lurq::ui::{Avatar, AvatarGroup};
///
/// let reviewers = AvatarGroup::new(
/// ["Ivan Zaida", "Anna K.", "Mark R.", "Ivy Chen", "Ivo Kovac", "Lena Q."].map(Avatar::new),
/// )
/// .max_shown(3)
/// .label("Reviewers");
/// ```
///
/// Each avatar lies over the end of the one before it, with a ring of the
/// surface behind the group around it. With [`max_shown`](Self::max_shown) the group
/// shows that many and then how many it leaves out, "+3". The group gives its
/// avatars its size; each keeps everything else it was given. To tooling that
/// reads the tree it is a group called by its label.
pub struct AvatarGroup {
avatars: Vec<Avatar>,
max_shown: Option<usize>,
size: Name,
label: Option<Arc<str>>,
states: Vec<Name>,
rules: Recipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl AvatarGroup {
pub fn new(avatars: impl IntoIterator<Item = Avatar>) -> Self {
Self {
avatars: avatars.into_iter().collect(),
max_shown: None,
size: AvatarSize::default().into(),
label: None,
states: Vec::new(),
rules: Recipe::new(),
id: None,
key: None,
}
}
/// The most avatars the group shows; after them it shows how many it leaves out.
pub fn max_shown(mut self, max_shown: usize) -> Self {
self.max_shown = Some(max_shown);
self
}
/// The size of every avatar in the group: an [`AvatarSize`], or a size the theme's recipe names.
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.size = size.into();
self
}
/// What the group is called to tooling that reads the tree: "Reviewers". Without one it is called by the
/// names of the avatars it shows and how many it leaves out.
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
/// Puts the group in a state the theme's recipe names, or takes it out.
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
/// Lays rules over the theme's recipe for this group: what the component
/// it is in says of it in this place.
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
/// Styles one part of this group over what the theme gives it: on a card, the ring is the card's color.
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(super::PartStyle) -> super::PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
/// Builds the group in `theme`. Converting a group into an element does
/// this in the theme of what is being rendered.
pub fn build(self, theme: &Theme) -> Element {
let mut case = Case::new().size(self.size).breakpoint(super::current_breakpoint());
for state in &self.states {
case = case.state(state.clone(), true);
}
let recipe = theme
.resolve::<AvatarGroup>(&case, Some(&self.rules))
.owned_by(self.id.as_ref());
let shown = self.max_shown.unwrap_or(usize::MAX).min(self.avatars.len());
let hidden = self.avatars.len() - shown;
let label = self.label.map_or_else(
|| {
let names: Vec<&str> = self.avatars[..shown].iter().map(|avatar| &*avatar.name).collect();
match hidden {
0 => names.join(", "),
more => {
let locale = super::current_locale();
crate::core::fill(
locale.form(&locale.common.and_more, more),
&[("names", &names.join(", ")), ("count", &more.to_string())],
)
}
}
},
|label| label.to_string(),
);
let item = recipe.rules_for(AvatarGroupPart::Item, AvatarPart::Face);
let avatars = self
.avatars
.into_iter()
.take(shown)
.map(|avatar| avatar.size(self.size).rules(&item))
.collect();
let view = AvatarGroupView {
avatars,
hidden,
size: self.size,
label,
recipe,
id: self.id,
key: self.key,
};
match theme.renderer::<AvatarGroup>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<AvatarGroup> for Element {
fn from(group: AvatarGroup) -> Self {
group.build(¤t_theme())
}
}
/// A group of avatars as a renderer sees it.
pub struct AvatarGroupView {
/// The avatars it shows, with its size and what it says of an item laid over them.
pub avatars: Vec<Avatar>,
/// How many it leaves out.
pub hidden: usize,
pub size: Name,
/// What tooling that reads the tree calls it.
pub label: String,
/// The style of each part of this group.
pub recipe: ResolvedRecipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl AvatarGroupView {
/// The style of a part, as this group is to be drawn.
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
/// The count at the end of the group, "+3", in the style of an item and of its own part; `None` where the
/// group leaves nobody out.
pub fn more(&self) -> Option<Avatar> {
(self.hidden > 0).then(|| {
let rules = self
.recipe
.rules_for(AvatarGroupPart::Item, AvatarPart::Face)
.extend(&self.recipe.rules_for(AvatarGroupPart::More, AvatarPart::Face))
// It stands for the count, not for one more item.
.extend(&self.recipe.lend(AvatarGroupPart::More));
Avatar::count(self.hidden).size(self.size).rules(&rules)
})
}
/// How the default renderer builds a group: its avatars in a row, each over the end of the one before, and the
/// count after them.
pub fn render(self) -> Element {
let theme = self.theme().clone();
let more = self.more();
// The rings stand outside the faces: the row does not clip them.
let mut root = Row::new()
.align_items(Alignment::Center)
.part(&self.part(AvatarGroupPart::Root))
.overflow_visible()
.describe("a11y_role", "group")
.describe("a11y_name", self.label);
for avatar in self.avatars.into_iter().chain(more) {
root = root.child(avatar.build(&theme));
}
if let Some(id) = self.id {
root = root.id(id);
}
if let Some(key) = self.key {
root = root.key(key);
}
root.into()
}
}
impl crate::ui::Styled for AvatarGroup {
type Component = Self;
fn rules(self, rules: &crate::ui::Recipe) -> Self {
Self::rules(self, rules)
}
fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
Self::state(self, state, on)
}
}
impl Themed for AvatarGroup {
const NAME: &'static str = "avatar_group";
type Renderer = AvatarGroupRenderer;
fn parts() -> crate::ui::Declared {
AvatarGroupPart::declared()
}
/// The design's group (`pencil/lurq-design-system.pen`, Avatar Group): avatars
/// of 32 that lie 8 over one another, each ringed 2 outside its face in the
/// background's color, and the count in the secondary fill. A smaller or a
/// larger avatar lies over the next by a quarter of its side.
fn recipe() -> Recipe {
use AvatarGroupPart::{Item, More, Root};
let recipe = Recipe::new()
.base(Root, |s| s.gap(-8.0))
.base(Item, |s| s.border(Border::outside(2.0, PaletteColor::Background)))
.base(More, |s| s.background(PaletteColor::Secondary));
[
(AvatarSize::Xs, 20.0),
(AvatarSize::Sm, 24.0),
(AvatarSize::Lg, 40.0),
(AvatarSize::Xl, 56.0),
]
.into_iter()
.fold(recipe, |recipe, (size, side)| {
recipe.size(size, Root, |s| s.gap(-side / 4.0))
})
}
}
#[cfg(test)]
mod tests {
use super::initials;
#[test]
fn the_initials_are_the_first_letters_of_the_first_and_the_last_word() {
assert_eq!(initials("Ivan Zaida"), "IZ");
assert_eq!(initials("Ivan"), "I");
assert_eq!(initials("ivan van der berg"), "IB");
assert_eq!(initials(" Anna K. "), "AK");
assert_eq!(initials("(Mark) Rossi"), "MR");
assert_eq!(initials(""), "");
assert_eq!(initials("— · —"), "");
}
}