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
//! A button: an action a press starts.
use std::sync::Arc;
use super::{
icon::Icon,
names,
part_style::Length,
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
shared::{opens_aside, pressable, tab_stop},
theme::{Themed, current_theme},
};
use crate::{
animation::Transition,
app::theme::{
BorderSize, ControlSize, Density, IconSize, MotionDuration, OpacityLevel, PaletteColor, RadiusSize, Theme,
TypographyStyle,
},
components::{self, Row},
node::{Element, EventHandler, IntoMouseEventHandler},
ui::PartTransition,
};
/// How much a button stands out.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ButtonVariant {
/// The main action of a view.
#[default]
Primary,
/// An alternative beside the primary one.
Secondary,
/// A lesser action: dismiss, go back.
Outline,
/// An action in a toolbar or in a line of text.
Ghost,
/// An action that removes or cannot be undone.
Destructive,
}
names!(ButtonVariant {
Primary => "primary",
Secondary => "secondary",
Outline => "outline",
Ghost => "ghost",
Destructive => "destructive",
});
/// How tall a button is. `Sm`, `Md` and `Lg` are the steps of the theme's
/// control sizes (32, 36, 40); `Xs` is as high as a row of a compact tool
/// (28) and `Xl` as one with room to breathe (44).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ButtonSize {
Xs,
Sm,
#[default]
Md,
Lg,
Xl,
}
names!(ButtonSize {
Xs => "xs",
Sm => "sm",
Md => "md",
Lg => "lg",
Xl => "xl",
});
/// The shape of a button's corners.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ButtonShape {
/// The theme's radius for a control.
#[default]
Default,
/// Rounded all the way: a pill, and a circle for a button that is an icon alone.
Pill,
}
/// The parts of a button a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ButtonPart {
/// The button itself: what is pressed.
Root,
/// Its text.
Label,
/// An icon the button was given by name, before or after the text: its side, and a color of its own.
Icon,
/// What turns while the button is loading, in the place of its icon.
Spinner,
/// A second line under the label, which says more of what the button does.
Description,
/// An element put before the text.
Leading,
/// An element put after the text.
Trailing,
}
names!(ButtonPart {
Root => "root",
Label => "label",
Icon => "icon",
Spinner => "spinner",
Description => "description",
Leading => "leading",
Trailing => "trailing",
});
/// The states of a button a recipe styles, besides what the pointer and the
/// keyboard do to it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ButtonState {
/// It takes no input.
Disabled,
/// It is as wide as what it is in.
FullWidth,
/// What it started is under way: it shows a spinner and is not pressed again.
Loading,
/// It is an icon alone, as wide as it is high.
IconOnly,
/// Its corners are rounded all the way ([`ButtonShape::Pill`]).
Pill,
/// It has a description under its label, and is as high as the two lines are.
Description,
/// Its label takes the room it has: its content starts at its start, and what is after the label at its end.
FillLabel,
/// Its description goes on to the next lines, in place of one line cut short.
DescriptionWraps,
}
names!(ButtonState {
Disabled => "disabled",
FullWidth => "full_width",
Loading => "loading",
IconOnly => "icon_only",
Pill => "pill",
Description => "description",
FillLabel => "fill_label",
DescriptionWraps => "description_wraps",
});
/// What a button runs as it takes the focus.
type FocusHandler = Arc<dyn Fn() + Send + Sync>;
/// How much of a button shows while it is loading, in the design's recipe.
const LOADING_OPACITY: f32 = 0.75;
/// What builds a button's nodes: a theme's in place of the default one.
pub type ButtonRenderer = Arc<dyn Fn(ButtonView) -> Element + Send + Sync>;
/// What builds one part of a button: a theme's, for [`ButtonPart::Label`],
/// [`ButtonPart::Icon`] or [`ButtonPart::Spinner`].
pub type ButtonPartRenderer = Arc<dyn Fn(&ButtonView) -> Element + Send + Sync>;
/// A button.
///
/// ```
/// use lurq::{components::Row, ui::{Button, ButtonVariant}};
///
/// let actions = Row::new()
/// .spacing(8.0)
/// .child(Button::new("Cancel").variant(ButtonVariant::Outline))
/// .child(Button::new("Save").on_click(|_| println!("saved")));
/// ```
///
/// It is pressed by a click, and by Enter or Space while it is focused. What
/// it looks like is the theme's: its recipe has the parts of [`ButtonPart`],
/// the variants of [`ButtonVariant`], the sizes of [`ButtonSize`] and the
/// states of [`ButtonState`], and a theme may add variants, sizes and states
/// of its own by name.
///
/// An icon is given by its name in the theme's set, and is drawn in the
/// color of the label at the size the button's size has for it:
///
/// ```
/// use lurq::ui::{Button, ButtonShape, ButtonVariant, icons};
///
/// let new_window = Button::new("New window").variant(ButtonVariant::Outline).icon(icons::PLUS);
/// // An icon alone: a square, or a circle. Its label is still what it is called.
/// let settings = Button::new("Settings").variant(ButtonVariant::Ghost).icon(icons::SETTINGS).icon_only(true);
/// let add = Button::new("Add").icon(icons::PLUS).icon_only(true).shape(ButtonShape::Pill);
/// // While what it started is under way.
/// let saving = Button::new("Saving…").loading(true);
/// ```
#[derive(Clone)]
pub struct Button {
label: Arc<str>,
description: Option<Arc<str>>,
variant: Name,
size: Name,
shape: ButtonShape,
icon: Option<Name>,
trailing_icon: Option<Name>,
icon_only: bool,
loading: bool,
leading: Option<Element>,
trailing: Option<Element>,
disabled: bool,
full_width: bool,
fill_label: bool,
description_wraps: bool,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
on_click: Vec<EventHandler<crate::app::events::MouseEvent>>,
on_open_aside: Vec<EventHandler<crate::app::events::MouseEvent>>,
on_focus: Vec<FocusHandler>,
tab_stop: bool,
autofocus: bool,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
element_ref: Option<crate::core::ElementRef>,
focuses: Option<crate::core::ElementRef>,
tooltip: Option<Box<super::Tooltip>>,
#[cfg(feature = "form")]
submit: bool,
}
impl Button {
pub fn new(label: &str) -> Self {
Self {
label: Arc::from(label),
description: None,
variant: ButtonVariant::default().into(),
size: ButtonSize::default().into(),
shape: ButtonShape::default(),
icon: None,
trailing_icon: None,
icon_only: false,
loading: false,
leading: None,
trailing: None,
disabled: false,
full_width: false,
fill_label: false,
description_wraps: false,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
on_click: Vec::new(),
on_open_aside: Vec::new(),
on_focus: Vec::new(),
tab_stop: true,
autofocus: false,
id: None,
key: None,
element_ref: None,
focuses: None,
tooltip: None,
#[cfg(feature = "form")]
submit: false,
}
}
/// A [`ButtonVariant`], or a variant the theme's recipe names.
pub fn variant(mut self, variant: impl Into<Name>) -> Self {
self.variant = variant.into();
self
}
/// A [`ButtonSize`], or a size the theme's recipe names.
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.size = size.into();
self
}
/// A second line under the label that says more of what the button does:
/// "Schedule", and under it "Pick a date and time". The button is then as
/// high as the two lines, with a larger icon beside them.
pub fn description(mut self, description: &str) -> Self {
self.description = Some(Arc::from(description));
self
}
/// Whether the description goes on to the next lines in the room the button has, in place of one line cut with an
/// ellipsis: an answer that says what a press of it leads to. The button is as high as its lines.
pub fn description_wraps(mut self, wraps: bool) -> Self {
self.description_wraps = wraps;
self
}
/// The shape of the button's corners.
pub fn shape(mut self, shape: ButtonShape) -> Self {
self.shape = shape;
self
}
/// An icon before the label, by its name in the theme's set
/// ([`icons`](super::icons)). It is drawn in the color of the label, at the
/// size the recipe gives [`ButtonPart::Icon`] for the button's size.
pub fn icon(mut self, name: impl Into<Name>) -> Self {
self.icon = Some(name.into());
self
}
/// An icon after the label: a chevron, an arrow.
pub fn trailing_icon(mut self, name: impl Into<Name>) -> Self {
self.trailing_icon = Some(name.into());
self
}
/// Whether the button is its icon alone: a square as wide as it is high,
/// or a circle with [`ButtonShape::Pill`]. Its label is not drawn, and
/// stays what the button is called.
pub fn icon_only(mut self, icon_only: bool) -> Self {
self.icon_only = icon_only;
self
}
/// Whether what the button started is under way: a spinner turns in the
/// place of its icon, or before its label, and a click, Enter and Space do
/// nothing until it is over. The label is the app's to change: "Saving…".
pub fn loading(mut self, loading: bool) -> Self {
self.loading = loading;
self
}
/// An element before the label, where an icon by name is not enough.
pub fn leading(mut self, element: impl Into<Element>) -> Self {
self.leading = Some(element.into());
self
}
/// An element after the label.
pub fn trailing(mut self, element: impl Into<Element>) -> Self {
self.trailing = Some(element.into());
self
}
/// Whether the button takes no input: it is not pressed, hovered or
/// focused, and Tab passes it by.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Whether the button is as wide as what it is in.
pub fn full_width(mut self, full_width: bool) -> Self {
self.full_width = full_width;
self
}
/// Whether the label takes the room the button has: what is before it stands at the button's start, and what is
/// after it (a [`trailing_icon`](Self::trailing_icon), a [`trailing`](Self::trailing) element) at its end, as a
/// select's chevron does. Its description, where it has one, takes that room too. A button as wide as its content
/// looks the same; one that is wider (`full_width`, or a width of the app's) puts its room between the label and
/// what is after it.
pub fn fill_label(mut self, fill: bool) -> Self {
self.fill_label = fill;
self
}
/// Puts the button 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
}
/// Called on a click, and on Enter and Space while the button is focused.
pub fn on_click(mut self, handler: impl IntoMouseEventHandler) -> Self {
self.on_click.push(handler.into_event_handler());
self
}
/// Called when a person asks for what the button opens beside what is open, in place of pressing it: a press of
/// the middle button, or a press with Ctrl held (Cmd on macOS), and Enter with it while the button is focused. An
/// app with tabs opens the place in a new one. Such a press is the handler's alone: the button's
/// [`on_click`](Self::on_click) is not called, it takes no focus, submits no form and does not reach what is
/// around it. It is given the press, whose `shift` asks for a tab that is switched to. A second handler is called
/// after the first.
pub fn on_open_aside(mut self, handler: impl IntoMouseEventHandler) -> Self {
self.on_open_aside.push(handler.into_event_handler());
self
}
/// Called when the button takes the focus: from Tab, from the arrows of a group it is in, or from the app. A press
/// of a button that is a stop of Tab focuses it too; one that is not ([`tab_stop`](Self::tab_stop)) is focused by
/// no press. What it says beside it may follow the button the keyboard is on. A second handler is called after
/// the first.
pub fn on_focus(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_focus.push(Arc::new(handler));
self
}
/// Whether Tab stops at the button; it does unless told otherwise. `false` is a button the pointer and the
/// app's own shortcuts reach, as a toolbar's or a list's are in many desktop apps: Tab passes it by, and a
/// press of it leaves the focus where it was. Focused by the app, it is pressed by Enter and Space as before,
/// and it is the same button to what reads the tree.
pub fn tab_stop(mut self, stops: bool) -> Self {
self.tab_stop = stops;
self
}
/// Whether the focus goes to the button as the dialog, the popover or the menu it is in opens, in place of their
/// first stop of Tab: a dialog's main action, so that Enter does it. It is a stop of Tab as it was, in its place.
/// Off unless told.
pub fn autofocus(mut self, autofocus: bool) -> Self {
self.autofocus = autofocus;
self
}
/// Styles one part of this button 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 button: what the component
/// it is in says of the button in this place.
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
/// Draws the button as it is under the pointer, held down or focused from
/// the keyboard, with nothing pointing at it: for a gallery or a test.
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
/// The ref of the button's element: what an app focuses or measures.
pub fn ref_element(mut self, element: crate::core::ElementRef) -> Self {
self.element_ref = Some(element);
self
}
/// What a press of the button gives the focus to, in place of taking it itself: the text a button of an
/// editor's bar works on, which goes on being typed in. The button is still a stop of Tab, and a press of it
/// from the keyboard gives the focus on too.
pub fn focuses(mut self, target: &crate::core::ElementRef) -> Self {
self.focuses = Some(target.clone());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
/// The tooltip [`mount`](Self::mount) puts on the button, in place of the one an icon alone has of its label:
/// its label with the keys of a shortcut, on another side, or a tooltip for a button with words.
pub fn tooltip(mut self, tooltip: super::Tooltip) -> Self {
self.tooltip = Some(Box::new(tooltip));
self
}
/// The button with its tooltip, which a tooltip keeps between renders in `ctx`: the one
/// [`tooltip`](Self::tooltip) gave it, or, for a button that is its icon alone, its label, as a
/// [`Toolbar`](super::Toolbar) gives the icons in it. A button with neither is built as it is. Inside a toolbar
/// the button is given to the toolbar as it is, which puts its tooltip on it.
pub fn mount(mut self, ctx: &mut crate::app::ctx::Ctx) -> Element {
let tooltip = self
.tooltip
.take()
.map(|tooltip| *tooltip)
.or_else(|| (self.icon_only && !self.label.is_empty()).then(|| super::Tooltip::new(&self.label)));
match tooltip {
Some(tooltip) => tooltip.mount(ctx, self),
None => self.into(),
}
}
/// Whether the button is the one that submits the form it is in.
#[cfg(feature = "form")]
pub fn submit(mut self, submit: bool) -> Self {
self.submit = submit;
self
}
/// What an item of a menu that stands for this button takes from it: a
/// toolbar moves a button that does not fit into its menu with this. Its
/// press is the button's, as Enter would make it.
pub(crate) fn command(&self) -> super::toolbar::ToolbarCommand {
let handlers = self.on_click.clone();
super::toolbar::ToolbarCommand {
label: self.label.clone(),
icon: self.icon,
icon_only: self.icon_only,
disabled: self.disabled || self.loading,
checked: None,
run: Arc::new(move || {
let click = super::toolbar::keyboard_click();
for handler in &handlers {
handler.call(&click);
}
}),
id: self.id.clone(),
key: None,
}
}
/// Builds the button in `theme`. Converting a button into an element does
/// this in the theme of what is being rendered.
pub fn build(mut self, theme: &Theme) -> Element {
// An icon with an empty label and nothing else beside it is an icon alone: no gap and no padding for a label.
self.icon_only = self.icon_only
|| self.label.is_empty()
&& self.icon.is_some()
&& self.description.is_none()
&& self.leading.is_none()
&& self.trailing.is_none()
&& self.trailing_icon.is_none();
let case = Case {
variant: Some(self.variant),
size: Some(self.size),
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(ButtonState::Disabled, self.disabled)
.state(ButtonState::FullWidth, self.full_width)
.state(ButtonState::Loading, self.loading)
.state(ButtonState::IconOnly, self.icon_only)
.state(ButtonState::Pill, self.shape == ButtonShape::Pill)
.state(ButtonState::Description, self.description.is_some())
.state(ButtonState::FillLabel, self.fill_label && !self.icon_only)
.state(
ButtonState::DescriptionWraps,
self.description_wraps && self.description.is_some(),
);
let recipe = theme
.resolve::<Button>(&case, Some(&self.rules))
.owned_by(self.id.as_ref());
let view = ButtonView {
label: self.label,
description: self.description,
variant: self.variant,
size: self.size,
shape: self.shape,
icon: self.icon,
trailing_icon: self.trailing_icon,
icon_only: self.icon_only,
loading: self.loading,
disabled: self.disabled,
full_width: self.full_width,
fill_label: self.fill_label && !self.icon_only,
description_wraps: self.description_wraps,
leading: self.leading,
trailing: self.trailing,
recipe,
forced: self.forced,
on_click: self.on_click,
on_open_aside: self.on_open_aside,
on_focus: self.on_focus,
tab_stop: self.tab_stop,
autofocus: self.autofocus,
id: self.id,
key: self.key,
element_ref: self.element_ref,
focuses: self.focuses,
#[cfg(feature = "form")]
submit: self.submit,
};
match theme.renderer::<Button>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<Button> for Element {
fn from(button: Button) -> Self {
button.build(¤t_theme())
}
}
/// A button as a renderer sees it: what it was given, the style of its
/// parts, and its behavior ready to be dressed.
pub struct ButtonView {
pub label: Arc<str>,
/// The line under the label, if the button has one.
pub description: Option<Arc<str>>,
pub variant: Name,
pub size: Name,
pub shape: ButtonShape,
/// The name of the icon before the label, if the button has one.
pub icon: Option<Name>,
/// The name of the icon after the label, if the button has one.
pub trailing_icon: Option<Name>,
/// Whether the button is its icon alone.
pub icon_only: bool,
/// Whether what the button started is under way.
pub loading: bool,
pub disabled: bool,
pub full_width: bool,
/// Whether the label takes the room the button has, what is after it at the end.
pub fill_label: bool,
/// Whether the description goes on to the next lines in place of one line cut short.
pub description_wraps: bool,
/// The element before the label, if the button has one.
pub leading: Option<Element>,
/// The element after the label, if the button has one.
pub trailing: Option<Element>,
/// The style of each part of this button.
pub recipe: ResolvedRecipe,
forced: Option<Interaction>,
on_click: Vec<EventHandler<crate::app::events::MouseEvent>>,
on_open_aside: Vec<EventHandler<crate::app::events::MouseEvent>>,
on_focus: Vec<FocusHandler>,
tab_stop: bool,
autofocus: bool,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
element_ref: Option<crate::core::ElementRef>,
focuses: Option<crate::core::ElementRef>,
#[cfg(feature = "form")]
submit: bool,
}
impl ButtonView {
/// The style of a part, as this button is to be drawn.
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part).forced(self.forced)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
/// The button's behavior with the style of its root: the element that is
/// pressed, focused and disabled, with nothing in it yet. A renderer puts
/// the button's content in it.
pub fn root(&self) -> components::Button {
let mut root = tab_stop(pressable(&self.part(ButtonPart::Root), self.disabled), self.tab_stop);
if self.autofocus {
root = root.autofocus(true);
}
// A button that is loading is not pressed again: it is there, and focused if it was, and does nothing.
#[cfg(feature = "form")]
if self.submit && !self.loading {
root = root.submit();
}
if !self.loading {
// Ahead of the press, which a press that asks for it aside does not reach.
root = opens_aside(root, &self.on_open_aside);
for handler in &self.on_click {
root = root.on_click(handler.clone());
}
}
// A room narrower than the button: it gives way down to its padding, its icon and the gap, and its label is
// cut. It is never wider than what holds it, a line of a row that wraps included, where nothing shrinks. An
// icon alone keeps its square.
if !self.icon_only {
root = root
.flex_shrink(1.0)
.shrink_limit(crate::layout::layout_kind::ShrinkLimit::Content)
.max_width(crate::node::dimension::Dimension::Pct(100.0));
}
for handler in &self.on_focus {
let handler = handler.clone();
root = root.on_focus(move || handler());
}
if self.fill_label {
root = root.justify(crate::layout::layout_kind::Justify::Start);
}
// A button that is an icon alone draws no label, and is still called by it.
if self.icon_only && !self.label.is_empty() {
root = root.describe("a11y_name", self.label.clone());
}
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
if let Some(element) = &self.element_ref {
root = root.ref_element(element.clone());
}
if let Some(target) = &self.focuses {
root = root.focuses(target);
}
root
}
/// The line under the label, in the typography of the description, if the button has one: one line cut with an
/// ellipsis, or the lines it takes in the room the button has where it wraps.
pub fn description(&self) -> Option<Element> {
let description = self.description.as_ref()?;
let part = self.part(ButtonPart::Description);
if self.description_wraps {
let fill = crate::node::dimension::Dimension::Pct(100.0);
return Some(
crate::components::Column::new()
.width(fill)
.min_width(0.0)
.child(part.text(description).width(fill).part(&part))
.into(),
);
}
Some(super::shared::one_line(&part, description))
}
/// The button's text, in the typography of its label. A theme's renderer
/// for [`ButtonPart::Label`] builds it in place of the default one.
pub fn label(&self) -> Element {
if let Some(renderer) = self
.theme()
.part_renderer::<Button, ButtonPartRenderer>(ButtonPart::Label)
{
return renderer(self);
}
// Where the button is narrower than its label, the label gives way and is cut: the padding and the icon stay.
let part = self.part(ButtonPart::Label);
super::shared::one_line(&part, &self.label)
}
/// An icon of the theme's set as this button draws one: in the style of
/// `part`, at the side the recipe gives that part for the button's size.
fn glyph(&self, part: ButtonPart, name: Name) -> Element {
if let Some(renderer) = self.theme().part_renderer::<Button, ButtonPartRenderer>(part) {
return renderer(self);
}
let part = self.part(part);
let side = part.rest().width.unwrap_or(Length::Icon(IconSize::Md));
Row::new()
.part(&part)
.child(Icon::new(name).size(side).build(self.theme()))
.into()
}
/// The button's icon before its label, if it has one. A theme's renderer
/// for [`ButtonPart::Icon`] builds it in place of the default one.
pub fn icon(&self) -> Option<Element> {
self.icon.map(|name| self.glyph(ButtonPart::Icon, name))
}
/// The button's icon after its label, if it has one.
pub fn trailing_icon(&self) -> Option<Element> {
self.trailing_icon.map(|name| self.glyph(ButtonPart::Icon, name))
}
/// What turns while the button is loading: a [`Spinner`](super::Spinner)
/// at the side the recipe gives [`ButtonPart::Spinner`], in the color of the
/// label, and no status of its own, since the label says what is under way.
/// A theme's renderer for [`ButtonPart::Spinner`] builds it in place of the
/// default one.
pub fn spinner(&self) -> Element {
if let Some(renderer) = self
.theme()
.part_renderer::<Button, ButtonPartRenderer>(ButtonPart::Spinner)
{
return renderer(self);
}
let part = self.part(ButtonPart::Spinner);
let side = part.rest().width.unwrap_or(Length::Icon(IconSize::Md));
let spinner = super::Spinner::new()
.decorative(true)
.rules(&self.recipe.lend(ButtonPart::Spinner))
.style(super::SpinnerPart::Indicator, |s| s.square(side));
// The spinner stands for the part, and has its id.
Row::new()
.part(&part.unnamed())
.child(spinner.build(self.theme()))
.into()
}
/// How the default renderer builds a button: the root, with what is before
/// the label, the label, and what is after it. While the button is loading
/// the spinner stands where its icon was, or before the label; a button
/// that is an icon alone draws that icon, or the spinner, and nothing else.
pub fn render(mut self) -> Element {
let mut root = self.root();
let before = if self.loading {
Some(self.spinner())
} else {
self.icon()
};
if let Some(before) = before {
root = root.child(before);
}
if self.icon_only {
return root.into();
}
if let Some(leading) = self.leading.take() {
root = root.child(Row::new().part(&self.part(ButtonPart::Leading)).child(leading));
}
// A label that takes the room grows into it, and gives way where there is less; so does a description that
// wraps, whose column is as wide as the room.
let grows = self.fill_label || (self.description_wraps && self.description.is_some());
root = match self.description() {
// The label with its description under it, both at the start of their column.
Some(description) => {
let column = crate::components::Column::new()
.spacing(2.0)
.child(self.label())
.child(description);
root.child(if grows {
column.flex_full(1.0, 1.0, None).min_width(0.0)
} else {
column
})
}
None if grows => root.child(Row::new().flex_full(1.0, 1.0, None).min_width(0.0).child(self.label())),
None => root.child(self.label()),
};
if let Some(trailing) = self.trailing.take() {
root = root.child(Row::new().part(&self.part(ButtonPart::Trailing)).child(trailing));
}
if let Some(after) = self.trailing_icon() {
root = root.child(after);
}
root.into()
}
}
impl crate::ui::Styled for Button {
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 Button {
const NAME: &'static str = "button";
type Renderer = ButtonRenderer;
fn parts() -> crate::ui::Declared {
ButtonPart::declared()
}
fn states() -> crate::ui::Declared {
ButtonState::declared()
}
/// The design's button (`pencil/lurq-design-system.pen`, Buttons): 36 tall,
/// padded 16, its corners `radius-md`, its label 13/500 and its icon 16,
/// and a fill for each variant with its fill under the pointer. Five
/// sizes, from 28 to 44, each with its padding, and the smallest and the
/// largest with a label and an icon of their own size.
fn recipe() -> Recipe {
use ButtonPart::{Description, Icon, Label, Root, Spinner};
use PaletteColor::*;
let paint = |style: super::PartStyle| {
[
Transition::background_color(),
Transition::foreground(),
Transition::box_shadow(),
Transition::outline(),
]
.into_iter()
.fold(style, |style, what| {
style.transition(PartTransition::new(what, MotionDuration::Fast))
})
};
let filled =
|recipe: Recipe, variant: ButtonVariant, fill: PaletteColor, ink: PaletteColor, hover: PaletteColor| {
recipe
.variant(variant, Root, |s| s.background(fill).foreground(ink))
.when(Selector::new().variant(variant).hovered(), Root, |s| {
s.background(hover)
})
};
let quiet = |recipe: Recipe, variant: ButtonVariant| {
recipe.variant(variant, Root, |s| s.foreground(Foreground)).when(
Selector::new().variant(variant).hovered(),
Root,
|s| s.background(Highlight).foreground(HighlightForeground),
)
};
let recipe = Recipe::new()
.base(Root, |s| {
paint(
s.height(ControlSize::Md)
.padding_x(16.0)
.gap(8.0)
.radius(RadiusSize::Md),
)
})
.base(Label, |s| s.typography(TypographyStyle::Button))
.pressed(Root, |s| s.veil(StatePressed))
.focus_visible(Root, |s| s.focus_ring())
.base(Icon, |s| s.square(IconSize::Md))
.base(Spinner, |s| s.square(IconSize::Md))
.size(ButtonSize::Xs, Root, |s| s.height(Density::Compact).padding_x(10.0))
.size(ButtonSize::Xs, Label, |s| s.font_size(12.0))
.size(ButtonSize::Sm, Root, |s| s.height(ControlSize::Sm).padding_x(12.0))
.size(ButtonSize::Lg, Root, |s| s.height(ControlSize::Lg).padding_x(20.0))
.size(ButtonSize::Xl, Root, |s| s.height(Density::Comfortable).padding_x(24.0))
.size(ButtonSize::Xl, Label, |s| s.font_size(15.0))
.state(ButtonState::Disabled, Root, |s| s.opacity(OpacityLevel::Disabled))
.state(ButtonState::Loading, Root, |s| s.opacity(LOADING_OPACITY))
.state(ButtonState::FullWidth, Root, |s| s.width(Length::Fill))
.state(ButtonState::Pill, Root, |s| s.radius(RadiusSize::Full))
// Two lines: as high as they are, with 10 above and below, and a larger icon 12 before them.
.base(Description, |s| {
s.typography(TypographyStyle::Caption).opacity(OpacityLevel::Muted)
})
.state(ButtonState::Description, Root, |s| {
s.height(Length::Auto).padding_x(16.0).padding_y(10.0).gap(12.0)
})
.state(ButtonState::Description, Label, |s| s.font_size(14.0))
.state(ButtonState::Description, Icon, |s| s.square(IconSize::Lg))
.state(ButtonState::Description, Spinner, |s| s.square(IconSize::Lg))
// An icon alone: no padding, and as wide as the button of its size is high.
.state(ButtonState::IconOnly, Root, |s| s.padding_x(0.0).width(ControlSize::Md));
// The icon of a size, and the width of a button of that size that is an icon alone.
let sized = |recipe: Recipe, size: ButtonSize, icon: Length, side: Length| {
recipe
.size(size, Icon, |s| s.square(icon))
.size(size, Spinner, |s| s.square(icon))
.when(Selector::new().size(size).state(ButtonState::IconOnly), Root, |s| {
s.width(side)
})
};
let recipe = sized(recipe, ButtonSize::Xs, IconSize::Sm.into(), Density::Compact.into());
let recipe = sized(recipe, ButtonSize::Sm, IconSize::Md.into(), ControlSize::Sm.into());
let recipe = sized(recipe, ButtonSize::Lg, Length::Px(18.0), ControlSize::Lg.into());
let recipe = sized(recipe, ButtonSize::Xl, IconSize::Lg.into(), Density::Comfortable.into());
let recipe = filled(recipe, ButtonVariant::Primary, Primary, PrimaryForeground, PrimaryHover)
// The board presses a button in its hover fill, under which the pressed veil is lost: black over the near
// black of the light theme, white over the near white of the dark. Pressed, it goes back to its fill under the
// veil, so that a press is seen.
.when(Selector::new().variant(ButtonVariant::Primary).pressed(), Root, |s| {
s.background(Primary)
});
let recipe = filled(
recipe,
ButtonVariant::Secondary,
Secondary,
SecondaryForeground,
SecondaryHover,
);
let recipe = filled(
recipe,
ButtonVariant::Destructive,
Destructive,
DestructiveForeground,
DestructiveHover,
);
let recipe = quiet(recipe, ButtonVariant::Ghost);
quiet(recipe, ButtonVariant::Outline).variant(ButtonVariant::Outline, Root, |s| {
s.background(Background)
.border(crate::node::border::Border::inside(BorderSize::Sm, Input))
})
}
}