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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
//! A spinner: something is being done, and how far it is is not known. And
//! the overlay that lays one over a part of the page while that part loads,
//! and the loader that stands for a whole page while it starts.
use std::{sync::Arc, time::Duration};
use super::{
empty_state::centred,
icon::{Icon, SpinMotion},
icons, names,
part_style::{Length, Opacity, PartAnimation},
recipe::{Case, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
shared::{FADE_IN, FADE_OUT},
theme::{Themed, current_theme},
};
use crate::{
animation::{AnimatableProperty, Animation, Easing, Keyframes, KeyframesId},
app::theme::{IconSize, MotionDuration, MotionEasing, PaletteColor, RadiusSize, Theme, TypographyStyle},
components::{Column, Grid, Row},
layout::{Alignment, grid::GridTrack, layout_kind::Justify, text_style::FontWeight},
node::{BackgroundColor, Element, dimension::Dimension, transform::Decomposed},
};
/// The keyframes of a dot of [`SpinnerKind::Dots`], which every window has:
/// whole, then faint, then whole again. Each dot plays them a little after
/// the one before it, so that a wave runs along them.
pub const SPINNER_DOTS: KeyframesId = KeyframesId::new(0xFF31);
/// The keyframes of a bar of [`SpinnerKind::Bars`], which every window has:
/// its height, then less than half of it about its middle, then its height
/// again. Each bar plays them a little after the one before it.
pub const SPINNER_BARS: KeyframesId = KeyframesId::new(0xFF32);
/// How long the wave of [`SpinnerKind::Dots`] takes to come back to the first dot.
pub const SPINNER_DOTS_PERIOD: Duration = Duration::from_millis(1200);
/// How long a bar of [`SpinnerKind::Bars`] takes to shrink and grow back.
pub const SPINNER_BARS_PERIOD: Duration = Duration::from_millis(1000);
/// How much of each dot shows at rest, from the first: the design's, a wave caught at a moment.
const DOT_OPACITIES: [f32; 3] = [1.0, 0.6, 0.3];
/// How high each bar is at rest, from the first, as a share of the height of the bars: the design's 8, 18,
/// 12, 20 and 10 of 20.
const BAR_HEIGHTS: [f32; 5] = [0.4, 0.9, 0.6, 1.0, 0.5];
/// How faint a dot is at the faintest, and how short a bar is at the shortest.
const LEAST: f32 = 0.3;
/// The spans between the keyframes of the dots and of the bars: there and back.
const WAVE_SPANS: u32 = 2;
/// The keyframes of the dots and the bars. They play in phase, so every spinner on screen moves as one.
pub(crate) fn keyframes() -> [Keyframes; 2] {
let dot = Keyframes::new(SPINNER_DOTS)
.frame(0.0, |frame| {
frame.set(AnimatableProperty::Opacity, 1.0);
})
.frame(0.5, |frame| {
frame.set(AnimatableProperty::Opacity, LEAST);
})
.frame(1.0, |frame| {
frame.set(AnimatableProperty::Opacity, 1.0);
});
let bar = Keyframes::new(SPINNER_BARS)
.frame(0.0, |frame| {
frame.set(AnimatableProperty::Transform, Decomposed::IDENTITY);
})
.frame(0.5, |frame| {
frame.set(
AnimatableProperty::Transform,
Decomposed::IDENTITY.with_scale(1.0, LEAST + 0.1),
);
})
.frame(1.0, |frame| {
frame.set(AnimatableProperty::Transform, Decomposed::IDENTITY);
});
[dot, bar]
}
/// What a spinner draws.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SpinnerKind {
/// A ring with a gap that turns: the design's spinner, and what a button turns while it loads.
#[default]
Ring,
/// Three dots that fade one after another.
Dots,
/// Five bars that shrink and grow one after another.
Bars,
}
/// The color of a spinner.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SpinnerVariant {
/// The color of the text around it: the ring, the dots and the bars are drawn in it, so a spinner in a
/// button is the color of the button's label.
#[default]
Current,
/// The muted foreground: a spinner that says less than the text beside it.
Muted,
/// The primary color.
Primary,
}
names!(SpinnerVariant {
Current => "current",
Muted => "muted",
Primary => "primary",
});
/// How large a spinner is: the design's 16, 24 and 32. A spinner is 16 where
/// nothing says otherwise, the side of an icon beside a line of text.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SpinnerSize {
#[default]
Sm,
Md,
Lg,
}
names!(SpinnerSize {
Sm => "sm",
Md => "md",
Lg => "lg",
});
/// The parts of a spinner a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SpinnerPart {
/// The spinner and its label, side by side.
Root,
/// What moves: the ring, as a square of its side; the row of the dots or of the bars.
Indicator,
/// A dot of [`SpinnerKind::Dots`].
Dot,
/// A bar of [`SpinnerKind::Bars`]: its width, and its height is a share of the indicator's.
Bar,
/// The text beside it, when it is drawn.
Label,
}
names!(SpinnerPart {
Root => "root",
Indicator => "indicator",
Dot => "dot",
Bar => "bar",
Label => "label",
});
/// The states of a spinner a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SpinnerState {
/// It is [`SpinnerKind::Dots`].
Dots,
/// It is [`SpinnerKind::Bars`].
Bars,
}
names!(SpinnerState {
Dots => "dots",
Bars => "bars",
});
/// What builds a spinner's nodes: a theme's in place of the default one.
pub type SpinnerRenderer = Arc<dyn Fn(SpinnerView) -> Element + Send + Sync>;
/// A spinner: something is being done, and how far it is is not known.
///
/// ```
/// use lurq::ui::{Spinner, SpinnerKind, SpinnerSize};
///
/// let plain = Spinner::new();
/// // Beside the text that says what is being done.
/// let inline = Spinner::new().label("Loading results…");
/// let large = Spinner::new().size(SpinnerSize::Lg);
/// let dots = Spinner::new().kind(SpinnerKind::Dots);
/// ```
///
/// It is a status to tooling that reads the tree, called by its label, or
/// "Loading" when it has none. It is drawn in the color of the text around
/// it, the ring, the dots and the bars alike, so a spinner in a button is the
/// color of the button's label.
/// Spinners move whether or not motion is reduced, unless their
/// [`motion`](Self::motion), or the theme's, says to stand still: one that
/// stood still would say nothing. A [`SpinMotion`] moves them in steps too.
#[derive(Clone)]
pub struct Spinner {
kind: SpinnerKind,
variant: Name,
size: Name,
label: Option<Arc<str>>,
label_hidden: bool,
decorative: bool,
motion: Option<SpinMotion>,
states: Vec<Name>,
rules: Recipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl Spinner {
/// A ring of 16 in the color of the text around it, called "Loading".
pub fn new() -> Self {
Self {
kind: SpinnerKind::default(),
variant: SpinnerVariant::default().into(),
size: SpinnerSize::default().into(),
label: None,
label_hidden: false,
decorative: false,
motion: None,
states: Vec::new(),
rules: Recipe::new(),
id: None,
key: None,
}
}
/// How the ring, the dots or the bars move, in place of the theme's motion ([`Theme::spin_motion`]): in steps,
/// still where motion is reduced.
///
/// ```
/// use lurq::ui::{SpinMotion, Spinner, SpinnerKind};
///
/// let typing = Spinner::new()
/// .kind(SpinnerKind::Dots)
/// .motion(SpinMotion::stepped(24).still_when_reduced(true));
/// ```
pub fn motion(mut self, motion: SpinMotion) -> Self {
self.motion = Some(motion);
self
}
/// What the spinner draws: a ring, dots or bars.
pub fn kind(mut self, kind: SpinnerKind) -> Self {
self.kind = kind;
self
}
/// A [`SpinnerVariant`], or a variant the theme's recipe names.
pub fn variant(mut self, variant: impl Into<Name>) -> Self {
self.variant = variant.into();
self
}
/// A [`SpinnerSize`], or a size the theme's recipe names.
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.size = size.into();
self
}
/// What is being done, drawn beside the spinner and what it is called:
/// "Loading results…".
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
/// Whether the label is not drawn. It stays what the spinner is called.
pub fn label_hidden(mut self, hidden: bool) -> Self {
self.label_hidden = hidden;
self
}
/// Whether the spinner is no status of its own, where what it is in says
/// already what is being done: a button that is loading.
pub fn decorative(mut self, decorative: bool) -> Self {
self.decorative = decorative;
self
}
/// Puts the spinner 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 spinner 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 spinner: what the component
/// it is in says of the spinner in this place.
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
/// The id of the root: the spinner with its label.
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 spinner in `theme`. Converting a spinner into an element does
/// this in the theme of what is being rendered.
pub fn build(self, theme: &Theme) -> Element {
let case = Case {
variant: Some(self.variant),
size: Some(self.size),
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(SpinnerState::Dots, self.kind == SpinnerKind::Dots)
.state(SpinnerState::Bars, self.kind == SpinnerKind::Bars);
let view = SpinnerView {
kind: self.kind,
variant: self.variant,
size: self.size,
label: self.label,
label_hidden: self.label_hidden,
decorative: self.decorative,
motion: self.motion.unwrap_or_else(|| theme.spin_motion()),
recipe: theme
.resolve::<Spinner>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
id: self.id,
key: self.key,
};
match theme.renderer::<Spinner>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl Default for Spinner {
fn default() -> Self {
Self::new()
}
}
impl From<Spinner> for Element {
fn from(spinner: Spinner) -> Self {
spinner.build(¤t_theme())
}
}
/// A spinner as a renderer sees it: what it was given and the style of its parts.
pub struct SpinnerView {
pub kind: SpinnerKind,
pub variant: Name,
pub size: Name,
/// The label the app gave it, if any.
pub label: Option<Arc<str>>,
pub label_hidden: bool,
/// Whether it is no status of its own.
pub decorative: bool,
/// How it moves: its own motion, or the theme's.
pub motion: SpinMotion,
/// The style of each part of this spinner.
pub recipe: ResolvedRecipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl SpinnerView {
/// The style of a part, as this spinner 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 the spinner is called: its label, or "Loading".
pub fn name(&self) -> Arc<str> {
self
.label
.clone()
.unwrap_or_else(|| super::current_locale().common.loading.clone())
}
/// A length of the recipe in logical pixels, where it is one.
fn px(&self, length: Option<Length>) -> Option<f32> {
match length?.resolve(self.theme())? {
Dimension::Px(px) => Some(px),
_ => None,
}
}
/// An animation of the dots or the bars: once in `period`, without end, the `index`th a step after the one
/// before it, in the spinner's motion. `None` where the motion stands still.
fn wave(&self, keyframes: KeyframesId, period: Duration, index: usize, count: usize) -> Option<Animation> {
if self.motion.is_still(self.theme()) {
return None;
}
let delay = period / (2 * count as u32) * index as u32;
Some(
Animation::new(keyframes)
.duration(period)
.delay(self.motion.delay(period, WAVE_SPANS, delay))
.easing(self.motion.easing(period, WAVE_SPANS, Easing::EASE_IN_OUT))
.infinite(),
)
}
/// What moves, in the style of its part: the ring, the dots or the bars.
pub fn indicator(&self) -> Element {
let part = self.part(SpinnerPart::Indicator);
match self.kind {
SpinnerKind::Ring => {
let side = part.rest().width.unwrap_or(Length::Icon(IconSize::Md));
Row::new()
.part(&part)
.child(
Icon::new(icons::SPINNER)
.size(side)
.spin(true)
.spin_motion(self.motion)
.build(self.theme()),
)
.into()
}
SpinnerKind::Dots => {
let dot = self.part(SpinnerPart::Dot);
let count = DOT_OPACITIES.len();
let mut row = Row::new().part(&part).align_items(Alignment::Center);
for (index, opacity) in DOT_OPACITIES.into_iter().enumerate() {
let mut dot = Row::new().part(&dot).opacity(opacity);
if let Some(wave) = self.wave(SPINNER_DOTS, SPINNER_DOTS_PERIOD, index, count) {
dot = dot.animation(wave);
}
row = row.child(dot);
}
row.into()
}
SpinnerKind::Bars => {
let bar = self.part(SpinnerPart::Bar);
let height = self.px(part.rest().height).unwrap_or(20.0);
let count = BAR_HEIGHTS.len();
let mut row = Row::new().part(&part).align_items(Alignment::Center);
for (index, share) in BAR_HEIGHTS.into_iter().enumerate() {
let mut bar = Row::new().part(&bar).height(height * share);
if let Some(wave) = self.wave(SPINNER_BARS, SPINNER_BARS_PERIOD, index, count) {
bar = bar.animation(wave);
}
row = row.child(bar);
}
row.into()
}
}
}
/// The label beside the spinner, in its part's typography, if it is drawn.
pub fn label(&self) -> Option<Element> {
let label = self.label.as_ref().filter(|_| !self.label_hidden)?;
let part = self.part(SpinnerPart::Label);
Some(Row::new().part(&part).child(part.text(label).nowrap()).into())
}
/// How the default renderer builds a spinner: what moves, and its label beside it. The root is a status to
/// tooling, called by the label, unless the spinner is decorative.
pub fn render(self) -> Element {
let mut root = Row::new()
.align_items(Alignment::Center)
.part(&self.part(SpinnerPart::Root))
.child(self.indicator());
if let Some(label) = self.label() {
root = root.child(label);
}
if !self.decorative {
root = root.describe("a11y_role", "status").describe("a11y_name", self.name());
}
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
root.into()
}
}
impl crate::ui::Styled for Spinner {
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 Spinner {
const NAME: &'static str = "spinner";
type Renderer = SpinnerRenderer;
fn parts() -> crate::ui::Declared {
SpinnerPart::declared()
}
fn states() -> crate::ui::Declared {
SpinnerState::declared()
}
/// The design's spinner (`pencil/lurq-design-system.pen`, Spinner,
/// Loader/Dots, Loader/Bars, Loader/Inline): a ring of 16, 24 or 32;
/// three dots of 8, 6 apart, in a row 16 high; five bars 3 wide and round,
/// 3 apart, in a row 20 high; all in the color of the text around them,
/// the foreground where nothing names one; and a label
/// 8 beside it, 13 in the muted foreground. The dots and the bars grow with
/// the ring's sizes, by a half and by twice.
fn recipe() -> Recipe {
use PaletteColor::{MutedForeground, Primary};
use SpinnerPart::{Bar, Dot, Indicator, Label, Root};
let recipe = Recipe::new()
.base(Root, |s| s.gap(8.0))
.base(Indicator, |s| s.square(IconSize::Md))
.base(Label, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.foreground(MutedForeground)
})
.base(Dot, |s| {
s.square(8.0)
.radius(RadiusSize::Full)
.background(BackgroundColor::CurrentForeground)
})
.base(Bar, |s| {
s.width(3.0)
.radius(RadiusSize::Full)
.background(BackgroundColor::CurrentForeground)
})
.size(SpinnerSize::Md, Indicator, |s| s.square(IconSize::Xl))
.size(SpinnerSize::Lg, Indicator, |s| s.square(32.0))
.state(SpinnerState::Dots, Indicator, |s| {
s.width(Length::Auto).height(16.0).gap(6.0)
})
.state(SpinnerState::Bars, Indicator, |s| {
s.width(Length::Auto).height(20.0).gap(3.0)
});
// The dots and the bars of a size: the height of their row, the room between them, and the side of a dot
// or the width of a bar.
let sized = |recipe: Recipe, size: SpinnerSize, scale: f32| {
recipe
.when(Selector::new().size(size).state(SpinnerState::Dots), Indicator, |s| {
s.width(Length::Auto).height(16.0 * scale).gap(6.0 * scale)
})
.when(Selector::new().size(size).state(SpinnerState::Dots), Dot, |s| {
s.square(8.0 * scale)
})
.when(Selector::new().size(size).state(SpinnerState::Bars), Indicator, |s| {
s.width(Length::Auto).height(20.0 * scale).gap(3.0 * scale)
})
.when(Selector::new().size(size).state(SpinnerState::Bars), Bar, |s| {
s.width(3.0 * scale)
})
};
let recipe = sized(recipe, SpinnerSize::Md, 1.5);
let recipe = sized(recipe, SpinnerSize::Lg, 2.0);
let colored = |recipe: Recipe, variant: SpinnerVariant, color: PaletteColor| {
recipe
.variant(variant, Indicator, |s| s.foreground(color.clone()))
.variant(variant, Dot, |s| s.background(color.clone()))
.variant(variant, Bar, |s| s.background(color))
};
let recipe = colored(recipe, SpinnerVariant::Muted, MutedForeground);
colored(recipe, SpinnerVariant::Primary, Primary)
}
}
/// The parts of a loading overlay a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LoadingOverlayPart {
/// The content and the veil over it, in one cell: as large as the content. It clips the veil to its corners.
Root,
/// What holds the content: out of input while it loads.
Content,
/// What lies over the content while it loads, with the spinner in its middle: it fades in and out.
Veil,
/// The fill of the veil, through which the content shows faintly: its background and how much of it shows
/// (its opacity), which the veil is filled with.
Scrim,
}
names!(LoadingOverlayPart {
Root => "root",
Content => "content",
Veil => "veil",
Scrim => "scrim",
});
/// The states of a loading overlay a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LoadingOverlayState {
/// The content is loading: the veil is over it.
Loading,
}
names!(LoadingOverlayState {
Loading => "loading",
});
/// What builds a loading overlay's nodes: a theme's in place of the default one.
pub type LoadingOverlayRenderer = Arc<dyn Fn(LoadingOverlayView) -> Element + Send + Sync>;
/// A veil with a spinner over a part of the page while it loads: a panel,
/// a table, a card.
///
/// ```
/// use lurq::{components::Text, ui::{LoadingOverlay, Spinner}};
///
/// let loading = true;
/// let panel = LoadingOverlay::new(loading, Text::new("Recent activity"));
/// // With a spinner of its own, which says what is being done.
/// let saving = LoadingOverlay::new(loading, Text::new("Draft")).spinner(Spinner::new().label("Saving…"));
/// ```
///
/// While it is loading, the content takes no input: no press reaches it and
/// Tab passes it by. The veil fades in as the loading starts and out as it
/// ends. The overlay is as large as its content; the veil is clipped to the
/// root's corners, which a recipe rounds where the content is rounded.
pub struct LoadingOverlay {
loading: bool,
content: Element,
spinner: Option<Spinner>,
states: Vec<Name>,
rules: Recipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl LoadingOverlay {
/// `content`, with the veil over it while `loading` is true.
pub fn new(loading: bool, content: impl Into<Element>) -> Self {
Self {
loading,
content: content.into(),
spinner: None,
states: Vec::new(),
rules: Recipe::new(),
id: None,
key: None,
}
}
/// The spinner in the middle of the veil, in place of a plain one.
pub fn spinner(mut self, spinner: Spinner) -> Self {
self.spinner = Some(spinner);
self
}
/// Puts the overlay 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 overlay 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 overlay.
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
/// The id of the 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 overlay in `theme`. Converting an overlay into an element
/// does this in the theme of what is being rendered.
pub fn build(self, theme: &Theme) -> Element {
let case = Case {
variant: None,
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(LoadingOverlayState::Loading, self.loading);
let view = LoadingOverlayView {
loading: self.loading,
content: Some(self.content),
spinner: self.spinner,
recipe: theme.resolve::<LoadingOverlay>(&case, Some(&self.rules)),
id: self.id,
key: self.key,
};
match theme.renderer::<LoadingOverlay>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<LoadingOverlay> for Element {
fn from(overlay: LoadingOverlay) -> Self {
overlay.build(¤t_theme())
}
}
/// A loading overlay as a renderer sees it.
pub struct LoadingOverlayView {
pub loading: bool,
/// The content, until a renderer takes it.
pub content: Option<Element>,
/// The spinner the app gave it, if any.
pub spinner: Option<Spinner>,
/// The style of each part of this overlay.
pub recipe: ResolvedRecipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl LoadingOverlayView {
/// The style of a part, as this overlay 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 fill of the veil: the scrim's color with as much of it showing as the scrim's opacity says. It is a
/// color and not an opacity of the veil, which its fade from nothing to whole would undo once it ends.
fn scrim(&self) -> Option<BackgroundColor> {
let scrim = self.part(LoadingOverlayPart::Scrim).rest();
let theme = self.theme();
let color = scrim.background?.resolve(&theme.palette())?;
let shown = match scrim.opacity {
Some(Opacity::Value(value)) => value,
Some(Opacity::Level(level)) => theme.opacity_value(level),
None => 1.0,
};
let alpha = (f32::from(color.a()) * shown.clamp(0.0, 1.0)).round() as u8;
Some(BackgroundColor::Color(color.with_alpha(alpha)))
}
/// The veil, while the content is loading: the scrim's fill with the spinner in the middle of it. It has a
/// key, so that the root, which keeps leaving children, keeps it while it fades out.
pub fn veil(&self) -> Option<Element> {
if !self.loading {
return None;
}
let spinner = self.spinner.clone().unwrap_or_default();
// As large as the spinner where the root measures what is in its cell, so that the veil does not widen
// it, and stretched to the cell after.
let mut veil = Row::new()
.key("veil")
.part(&self.part(LoadingOverlayPart::Veil))
.align_items(Alignment::Center)
.justify(Justify::Center)
.grid_column(0)
.grid_row(0)
.child(spinner.build(self.theme()));
if let Some(fill) = self.scrim() {
veil = veil.background(fill);
}
Some(veil.into())
}
/// How the default renderer builds the overlay: the content, out of input while it loads, and the veil
/// over it, both in one cell of the root.
pub fn render(mut self) -> Element {
let content = Column::new()
.part(&self.part(LoadingOverlayPart::Content))
.disabled(self.loading)
.grid_column(0)
.grid_row(0)
.child(self.content.take().unwrap_or_else(|| Row::new().into()));
// A grid of one cell that the content and the veil are both in, stretched to it. The cell is as large as
// the content, whatever room the root is given: the veil covers the content and nothing beside it, and a
// content that fills the room makes it as wide as the room.
let mut root = Grid::new()
.columns([GridTrack::Auto])
.rows([GridTrack::Auto])
.presence()
.part(&self.part(LoadingOverlayPart::Root))
.child(content);
if let Some(veil) = self.veil() {
root = root.child(veil);
}
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
root.into()
}
}
impl crate::ui::Styled for LoadingOverlay {
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 LoadingOverlay {
const NAME: &'static str = "loading_overlay";
type Renderer = LoadingOverlayRenderer;
fn parts() -> crate::ui::Declared {
LoadingOverlayPart::declared()
}
fn states() -> crate::ui::Declared {
LoadingOverlayState::declared()
}
/// The design's loading overlay (`pencil/lurq-design-system.pen`, Loading
/// Overlay): a veil in the background's color at 85 hundredths over the
/// content, a spinner of 16 in its middle. It fades in and out over the
/// theme's base duration.
fn recipe() -> Recipe {
use LoadingOverlayPart::{Scrim, Veil};
Recipe::new()
.base(Veil, |s| {
s.enter(PartAnimation::new(
FADE_IN,
MotionDuration::Base,
MotionEasing::Standard,
))
.exit(PartAnimation::new(
FADE_OUT,
MotionDuration::Base,
MotionEasing::Standard,
))
})
.base(Scrim, |s| s.background(PaletteColor::Background).opacity(0.85))
}
}
/// The parts of a page loader a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PageLoaderPart {
/// The loader: as large as the room it is given, with what it holds in its middle.
Root,
/// What the loader says of the ring it turns, laid over the theme's recipe for a spinner's indicator: its side.
Spinner,
/// The title over the description.
Text,
/// What is starting: "Starting lurq".
Title,
/// What it is doing meanwhile, under the title: "Loading your workspace…".
Description,
}
names!(PageLoaderPart {
Root => "root",
Spinner => "spinner",
Text => "text",
Title => "title",
Description => "description",
});
/// The states of a page loader a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PageLoaderState {
/// It has a description under its title.
Description,
}
names!(PageLoaderState {
Description => "description",
});
/// What builds a page loader's nodes: a theme's in place of the default one.
pub type PageLoaderRenderer = Arc<dyn Fn(PageLoaderView) -> Element + Send + Sync>;
/// A page loader: what stands in the place of a whole page, a window or a
/// pane while it starts. A spinner over a title and a line that says what is
/// being done.
///
/// ```
/// use lurq::ui::{PageLoader, Spinner, SpinnerKind, SpinnerSize};
///
/// let starting = PageLoader::new("Starting lurq").description("Loading your workspace…");
/// // With a spinner of its own in place of the ring.
/// let dots = PageLoader::new("Opening the project")
/// .spinner(Spinner::new().kind(SpinnerKind::Dots).size(SpinnerSize::Md));
/// ```
///
/// It is as large as the room it is given, with what it holds in the middle of
/// it; a title or a description longer than the room goes on to the next
/// line, centred. It paints no surface of its own: it stands on the page's. To
/// tooling that reads the tree it is a status, called by its title and
/// described by its description. Its ring turns whether or not motion is
/// reduced, as a [`Spinner`]'s does. What loads over content that stays in
/// place is a [`LoadingOverlay`]'s.
pub struct PageLoader {
title: Arc<str>,
description: Option<Arc<str>>,
spinner: Option<Spinner>,
states: Vec<Name>,
rules: Recipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl PageLoader {
/// A loader that says `title` under a ring of 28.
pub fn new(title: &str) -> Self {
Self {
title: Arc::from(title),
description: None,
spinner: None,
states: Vec::new(),
rules: Recipe::new(),
id: None,
key: None,
}
}
/// What is being done meanwhile, under the title in the muted color: "Loading your workspace…". It describes
/// the loader to tooling.
pub fn description(mut self, description: &str) -> Self {
self.description = Some(Arc::from(description));
self
}
/// A spinner in place of the ring of 28, as it is given: its kind, its size and its color. It is no status
/// of its own in the loader, which says what is being done.
pub fn spinner(mut self, spinner: Spinner) -> Self {
self.spinner = Some(spinner);
self
}
/// Puts the loader 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 loader 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 loader.
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
/// The id of the 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 loader in `theme`. Converting a loader into an element does
/// this in the theme of what is being rendered.
pub fn build(self, theme: &Theme) -> Element {
let case = Case {
variant: None,
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(PageLoaderState::Description, self.description.is_some());
let view = PageLoaderView {
title: self.title,
description: self.description,
spinner: self.spinner,
recipe: theme.resolve::<PageLoader>(&case, Some(&self.rules)),
id: self.id,
key: self.key,
};
match theme.renderer::<PageLoader>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<PageLoader> for Element {
fn from(loader: PageLoader) -> Self {
loader.build(¤t_theme())
}
}
/// A page loader as a renderer sees it: what it was given and the style of its parts.
pub struct PageLoaderView {
pub title: Arc<str>,
pub description: Option<Arc<str>>,
/// The spinner the app gave it, if any.
pub spinner: Option<Spinner>,
/// The style of each part of this loader.
pub recipe: ResolvedRecipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl PageLoaderView {
/// The style of a part, as this loader 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 root in the style of its part, with nothing in it yet: what it holds is in its middle. A status to
/// tooling, called by the title and described by the description.
pub fn root(&self) -> Column {
let mut root = Column::new()
.align_items(Alignment::Center)
.justify(Justify::Center)
.part(&self.part(PageLoaderPart::Root))
.describe("a11y_role", "status")
.describe("a11y_name", self.title.clone());
if let Some(description) = &self.description {
root = root.describe("a11y_description", description.clone());
}
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
root
}
/// What turns: the app's spinner as it was given, or a ring with what the loader's recipe says of it. No
/// status of its own.
pub fn spinner(&self) -> Element {
let spinner = match &self.spinner {
Some(spinner) => spinner.clone(),
None => Spinner::new().rules(&self.recipe.rules_for(PageLoaderPart::Spinner, SpinnerPart::Indicator)),
};
spinner.decorative(true).build(self.theme())
}
/// The title over the description, each centred and wrapping in the width it has.
pub fn text(&self) -> Column {
let mut text = Column::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Center)
.part(&self.part(PageLoaderPart::Text))
.child(centred(&self.part(PageLoaderPart::Title), &self.title));
if let Some(description) = &self.description {
text = text.child(centred(&self.part(PageLoaderPart::Description), description));
}
text
}
/// How the default renderer builds a page loader: the spinner over the text, in the middle of the root.
pub fn render(self) -> Element {
self.root().child(self.spinner()).child(self.text()).into()
}
}
impl crate::ui::Styled for PageLoader {
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 PageLoader {
const NAME: &'static str = "page_loader";
type Renderer = PageLoaderRenderer;
fn parts() -> crate::ui::Declared {
PageLoaderPart::declared()
}
fn states() -> crate::ui::Declared {
PageLoaderState::declared()
}
/// The design's page loader (`pencil/lurq-design-system.pen`, Loader/Page):
/// a ring of 28 in the foreground, 14 over the text; the title in 14 at 500
/// in the foreground with the description 4 under it in 13 of the muted
/// foreground, all in the middle of the room. The board's box of 280 by 180
/// with an edge is the page it is drawn on. It keeps 24 from the sides of a
/// room narrower than its text.
fn recipe() -> Recipe {
use PageLoaderPart::{Description, Root, Spinner, Text, Title};
use PaletteColor::{Foreground, MutedForeground};
Recipe::new()
.base(Root, |s| {
s.width(Length::Fill)
.height(Length::Fill)
.padding_x(24.0)
.padding_y(24.0)
.gap(14.0)
.foreground(Foreground)
})
.base(Spinner, |s| s.square(28.0))
.base(Text, |s| s.gap(4.0))
.base(Title, |s| {
s.typography(TypographyStyle::Body)
.font_size(14.0)
.weight(FontWeight::Medium)
.foreground(Foreground)
})
.base(Description, |s| {
s.typography(TypographyStyle::Description)
.font_size(13.0)
.foreground(MutedForeground)
})
}
}