lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
Documentation
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
//! A switch: a setting that is on or off, and takes effect at once.

use std::sync::Arc;

use super::{
  names,
  part_style::{Length, PartTransition},
  recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
  shared::{beside_first_line, control_label, label_top, fading, pressable},
  theme::{Themed, current_theme},
};
use crate::{
  animation::Transition,
  app::events::MouseEvent,
  app::theme::{BorderSize, MotionDuration, OpacityLevel, PaletteColor, RadiusSize, Theme, TypographyStyle},
  components::{self, Row},
  core::{ElementRef, Signal},
  layout::{Alignment, layout_kind::Justify},
  node::{CursorIcon, Element, dimension::Dimension},
};

/// The parts of a switch a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SwitchPart {
  /// The switch and its label, side by side.
  Root,
  /// What is pressed: the rail the thumb moves on.
  Track,
  /// What moves: at the start of the track while the switch is off, at its end while it is on.
  Thumb,
  /// Its text, beside the track.
  Label,
}

names!(SwitchPart {
  Root => "root",
  Track => "track",
  Thumb => "thumb",
  Label => "label",
});

/// The states of a switch a recipe styles, besides what the pointer and the
/// keyboard do to it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SwitchState {
  /// It is on.
  On,
  /// What it holds is wrong: a form says so.
  Invalid,
  /// It takes no input.
  Disabled,
  /// It is pressed as a whole: its root is what is pressed and focused, with the track and the label in it.
  Whole,
}

names!(SwitchState {
  On => "on",
  Invalid => "invalid",
  Disabled => "disabled",
  Whole => "whole",
});

/// What builds a switch's nodes: a theme's in place of the default one.
pub type SwitchRenderer = Arc<dyn Fn(SwitchView) -> Element + Send + Sync>;

/// A switch: a setting that is on or off and takes effect at once. Dark
/// mode, sync in the background, notifications paused.
///
/// ```
/// use lurq::ui::Switch;
///
/// let dark = Switch::new("Dark mode").on(true).on_change(|on| println!("dark: {on}"));
/// // The track alone, where a row of settings has the text already: its label is still what it is called.
/// let sync = Switch::new("Sync in background").label_hidden(true);
/// // Bound to the app's signal, which a press turns.
/// # let paused = lurq::core::Signal::new(false);
/// let pause = Switch::new("Pause notifications").bind(paused);
/// ```
///
/// A switch does not keep whether it is on: the app says so with
/// [`Switch::on`], and is told of a press with [`Switch::on_change`], or binds
/// it to a signal with [`Switch::bind`]. A press of its label is a press of
/// the switch, and a press of either is the switch's alone: a row around it
/// that is pressed is not. [`Switch::whole`] makes the switch and its label
/// one control, its id on the whole.
pub struct Switch {
  label: Arc<str>,
  label_hidden: bool,
  label_wraps: bool,
  whole: bool,
  on: bool,
  invalid: bool,
  disabled: bool,
  states: Vec<Name>,
  rules: Recipe,
  forced: Option<Interaction>,
  on_change: Vec<Arc<dyn Fn(bool) + Send + Sync>>,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
  element: Option<ElementRef>,
}

impl Switch {
  /// A switch called `label`, with the label beside it.
  pub fn new(label: &str) -> Self {
    Self {
      label: Arc::from(label),
      label_hidden: false,
      label_wraps: false,
      whole: false,
      on: false,
      invalid: false,
      disabled: false,
      states: Vec::new(),
      rules: Recipe::new(),
      forced: None,
      on_change: Vec::new(),
      id: None,
      key: None,
      element: None,
    }
  }

  /// Whether the switch is its track alone. Its label stays what it is called.
  pub fn label_hidden(mut self, hidden: bool) -> Self {
    self.label_hidden = hidden;
    self
  }

  /// Whether the label goes on to more lines within the width the switch is given, the track beside its first
  /// line and centered on it: a label that may be long. The switch is then no wider than what holds it. Not unless
  /// told: the label is on one line.
  pub fn label_wraps(mut self, wraps: bool) -> Self {
    self.label_wraps = wraps;
    self
  }

  /// Whether the switch and its label are one control: what is pressed,
  /// focused and ringed is the whole of them, one stop of Tab, and its id is
  /// on the whole, the track, the thumb and the label named after it
  /// (`x-track`, `x-thumb`, `x-label`). Not unless told: the track is what is
  /// pressed, and has the id.
  pub fn whole(mut self, whole: bool) -> Self {
    self.whole = whole;
    self
  }

  /// Whether the switch is on.
  pub fn on(mut self, on: bool) -> Self {
    self.on = on;
    self
  }

  /// On while `on` is true, which a press turns. Handlers of [`Switch::on_change`] are told of a press after the
  /// signal is set, and not when the app sets it.
  pub fn bind(self, on: Signal<bool>) -> Self {
    let set = on.clone();
    let mut bound = self.on(on.get());
    bound.on_change.insert(0, Arc::new(move |next| set.set(next)));
    bound
  }

  /// Whether what the switch holds is wrong, where a field says so: its track is edged in the destructive color.
  pub fn invalid(mut self, invalid: bool) -> Self {
    self.invalid = invalid;
    self
  }

  /// Whether the switch takes no input.
  pub fn disabled(mut self, disabled: bool) -> Self {
    self.disabled = disabled;
    self
  }

  /// Puts the switch 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 press, with what the switch is to be: on if it was off. A second handler is called after the
  /// first.
  pub fn on_change(mut self, handler: impl Fn(bool) + Send + Sync + 'static) -> Self {
    self.on_change.push(Arc::new(handler));
    self
  }

  /// Styles one part of this switch 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 switch: what the component
  /// it is in says of the switch in this place.
  pub fn rules(mut self, rules: &Recipe) -> Self {
    self.rules = self.rules.extend(rules);
    self
  }

  /// Draws the switch 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
  }

  /// The id of the track: what is pressed. The id of the whole where it is
  /// [`whole`](Self::whole).
  pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
    self.id = Some(id.into());
    self
  }

  /// Refers to what is pressed and focused once it is laid out: the track, or
  /// the whole where it is [`whole`](Self::whole). What a screen moves the
  /// focus to, or a popup hangs from.
  pub fn element_ref(mut self, element: ElementRef) -> Self {
    self.element = Some(element);
    self
  }

  /// What tells the switch apart from those beside it, where two have one label.
  pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
    self.key = Some(key.into());
    self
  }

  /// Builds the switch in `theme`. Converting a switch 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(SwitchState::On, self.on)
    .state(SwitchState::Invalid, self.invalid)
    .state(SwitchState::Disabled, self.disabled)
    .state(SwitchState::Whole, self.whole);
    let recipe = theme.resolve::<Switch>(&case, Some(&self.rules));
    // Pressed as a whole, the id is on the root, and the track is a part named after it.
    let recipe = if self.whole {
      recipe.rooted_at(SwitchPart::Root)
    } else {
      recipe
    };
    let view = SwitchView {
      label: self.label,
      label_hidden: self.label_hidden,
      label_wraps: self.label_wraps,
      whole: self.whole,
      on: self.on,
      invalid: self.invalid,
      disabled: self.disabled,
      recipe: recipe.owned_by(self.id.as_ref()),
      forced: self.forced,
      on_change: self.on_change,
      id: self.id,
      key: self.key,
      element: self.element,
    };
    match theme.renderer::<Switch>() {
      Some(renderer) => renderer(view),
      None => view.render(),
    }
  }
}

impl From<Switch> for Element {
  fn from(switch: Switch) -> Self {
    switch.build(&current_theme())
  }
}

/// A switch as a renderer sees it: what it was given, the style of its
/// parts, and its behavior ready to be dressed.
pub struct SwitchView {
  pub label: Arc<str>,
  pub label_hidden: bool,
  /// Whether the label goes on to more lines, the track beside its first line.
  pub label_wraps: bool,
  /// Whether the switch and its label are one control, its id on the whole.
  pub whole: bool,
  pub on: bool,
  pub invalid: bool,
  pub disabled: bool,
  /// The style of each part of this switch.
  pub recipe: ResolvedRecipe,
  forced: Option<Interaction>,
  on_change: Vec<Arc<dyn Fn(bool) + Send + Sync>>,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
  element: Option<ElementRef>,
}

impl SwitchView {
  /// The style of a part, as this switch 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()
  }

  /// What a press does: every handler is told what the switch is to be.
  fn press(&self) -> Option<impl Fn() + Send + Sync + Clone + 'static> {
    let (handlers, next) = (self.on_change.clone(), !self.on);
    (!handlers.is_empty() && !self.disabled).then(|| {
      move || {
        for handler in &handlers {
          handler(next);
        }
      }
    })
  }

  /// The switch's behavior with the style of `part`: the element that is
  /// pressed, focused and disabled, with nothing in it yet, its id, its key
  /// and its element ref. It is a switch to what reads the tree, called by its label, and
  /// says whether it is on. A press of it is its own: it does not reach what
  /// is around it.
  fn control(&self, part: SwitchPart) -> components::Button {
    let mut control = pressable(&self.part(part), self.disabled)
      .justify(Justify::Start)
      .describe("a11y_role", "switch")
      .describe("a11y_name", self.label.clone())
      .describe("a11y_checked", if self.on { "true" } else { "false" })
      .on_click(own_press(self.press()));
    if let Some(id) = &self.id {
      control = control.id(id.clone());
    }
    if let Some(key) = &self.key {
      control = control.key(key.clone());
    }
    if let Some(element) = &self.element {
      control = control.ref_element(element.clone());
    }
    control
  }

  /// The switch's behavior with the style of its track: the element that is
  /// pressed, focused and disabled, with nothing in it yet. It is a switch to
  /// what reads the tree, called by its label, and says whether it is on.
  pub fn track(&self) -> components::Button {
    self.control(SwitchPart::Track)
  }

  /// The behavior of a switch pressed as a whole, with the style of its root:
  /// what is pressed, focused and ringed, with nothing in it yet, the track
  /// and the label to go in it. What [`track`](Self::track) is otherwise.
  pub fn whole_root(&self) -> components::Button {
    self.control(SwitchPart::Root).align_items(Alignment::Center)
  }

  /// How far the thumb moves from off to on: the room of the track that the
  /// thumb does not fill. `None` where the recipe gives the track or the
  /// thumb no width in pixels.
  pub fn travel(&self) -> Option<f32> {
    let theme = self.theme();
    let px = |length: Option<Length>| match length?.resolve(theme)? {
      Dimension::Px(px) => Some(px),
      _ => None,
    };
    let (track, thumb) = (self.part(SwitchPart::Track).rest(), self.part(SwitchPart::Thumb).rest());
    let padding = track
      .padding_x
      .map(|padding| padding.resolve(&theme.spacing(), 0.0))
      .unwrap_or(0.0);
    Some((px(track.width)? - 2.0 * padding - px(thumb.width)?).max(0.0))
  }

  /// The thumb in the style of its part, moved to the end of the track while
  /// the switch is on. It is moved, not laid out at the other end, so that a
  /// transition the recipe gives its offset slides it.
  pub fn thumb(&self) -> Row {
    let thumb = Row::new().part(&self.part(SwitchPart::Thumb));
    match self.travel() {
      // Off it has an offset too, of nothing: a transition runs from one offset to another.
      Some(travel) => thumb.offset(if self.on { travel } else { 0.0 }, 0.0),
      None => thumb,
    }
  }

  /// The label in the style of its part: `None` where it is hidden.
  fn label(&self) -> Option<Row> {
    if self.label_hidden {
      return None;
    }
    let part = self.part(SwitchPart::Label);
    let wraps = self.label_wraps.then(|| label_top(&part, &self.part(SwitchPart::Track)));
    Some(control_label(&part, &self.label, wraps))
  }

  /// Whether the label is shown and goes on to more lines.
  fn wraps(&self) -> bool {
    self.label_wraps && !self.label_hidden
  }

  /// The track as it stands beside the label: held at the label's first line where the label wraps.
  fn beside_label(&self, track: impl Into<Element>) -> Element {
    if self.wraps() {
      beside_first_line(&self.part(SwitchPart::Label), track).into()
    } else {
      track.into()
    }
  }

  /// How the default renderer builds a switch: the track with its thumb, and the label beside it; pressed as a whole,
  /// both in what is pressed.
  pub fn render(self) -> Element {
    // A track whose travel the recipe does not say holds its thumb at the end it belongs at.
    let end = self.on && self.travel().is_none();
    if self.whole {
      let mut track = Row::new()
        .align_items(Alignment::Center)
        .part(&self.part(SwitchPart::Track))
        .child(self.thumb());
      if end {
        track = track.justify(Justify::End);
      }
      let root = self
        .whole_root()
        .child(self.beside_label(track))
        .with_children(self.label());
      return if self.wraps() {
        root.align_items(Alignment::Start).max_width(Dimension::Pct(100.0)).into()
      } else {
        root.into()
      };
    }
    let mut track = self.track().child(self.thumb());
    if end {
      track = track.justify(Justify::End);
    }
    let mut root = Row::new()
      .align_items(if self.wraps() { Alignment::Start } else { Alignment::Center })
      .part(&self.part(SwitchPart::Root))
      .child(self.beside_label(track));
    if self.wraps() {
      root = root.max_width(Dimension::Pct(100.0));
    }
    if let Some(label) = self.label() {
      root = root.child(label.on_click(own_press(self.press())));
    }
    root.into()
  }
}

/// What a press of a switch, a checkbox or its label does: `press`, where it has one, and nothing more. It is its
/// own, and does not reach what is around it (a row that is pressed).
pub(crate) fn own_press(press: Option<impl Fn() + Send + Sync + 'static>) -> impl Fn(MouseEvent) + Send + Sync + 'static {
  move |event: MouseEvent| {
    event.stop_propagation();
    if let Some(press) = &press {
      press();
    }
  }
}

impl crate::ui::Styled for Switch {
  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 Switch {
  const NAME: &'static str = "switch";
  const ROOT: &'static str = "track";
  type Renderer = SwitchRenderer;

  fn parts() -> crate::ui::Declared {
    SwitchPart::declared()
  }

  fn states() -> crate::ui::Declared {
    SwitchState::declared()
  }

  /// The design's switch (`pencil/lurq-design-system.pen`, Switch): a track
  /// of 36 by 20, round, in the color of an input's edge, with a thumb of 16
  /// in the background's color 2 from its edge; the track is in the primary
  /// color while it is on. Its label is 8 beside it, in the body's type. The
  /// board draws no invalid switch: an invalid one has the edge of 1 inside
  /// its track in the destructive color, as an invalid checkbox's box has.
  fn recipe() -> Recipe {
    use PaletteColor::*;
    use SwitchPart::{Label, Root, Thumb, Track};
    Recipe::new()
      .base(Root, |s| s.gap(8.0).foreground(Foreground))
      .base(Track, |s| {
        fading(
          s.width(36.0)
            .height(20.0)
            .padding_x(2.0)
            .radius(RadiusSize::Full)
            .background(Input)
            .cursor(CursorIcon::Pointer),
        )
      })
      .base(Thumb, |s| {
        s.square(16.0)
          .radius(RadiusSize::Full)
          .background(Background)
          .transition(PartTransition::new(Transition::offset_x(), MotionDuration::Fast))
      })
      .base(Label, |s| {
        s.typography(TypographyStyle::Body).cursor(CursorIcon::Pointer)
      })
      .focus_visible(Track, |s| s.focus_ring())
      .state(SwitchState::On, Track, |s| s.background(Primary))
      .state(SwitchState::Invalid, Track, |s| {
        s.border(crate::node::border::Border::inside(BorderSize::Sm, Destructive))
      })
      .state(SwitchState::Disabled, Root, |s| s.opacity(OpacityLevel::Disabled))
      .state(SwitchState::Disabled, Track, |s| s.cursor(CursorIcon::Default))
      .state(SwitchState::Disabled, Label, |s| s.cursor(CursorIcon::Default))
      // Pressed as a whole: the root is what the pointer presses and the ring goes round, the track only drawn.
      .state(SwitchState::Whole, Root, |s| s.radius(RadiusSize::Sm).cursor(CursorIcon::Pointer))
      .when(Selector::new().state(SwitchState::Whole).focus_visible(), Root, |s| s.focus_ring())
      .when(Selector::new().state(SwitchState::Whole).state(SwitchState::Disabled), Root, |s| {
        s.cursor(CursorIcon::Default)
      })
  }
}

impl super::FieldControl for Switch {
  /// Called by the field's label where its own is hidden, since the label a person reads is then the field's;
  /// invalid where the field is, and disabled where the field is.
  fn in_field(mut self, field: &super::InField) -> Element {
    if self.label_hidden && !field.label.is_empty() {
      self.label = field.label.clone();
    }
    self.invalid |= field.judgment == Some(super::Judgment::Invalid);
    self.disabled |= field.disabled;
    self.into()
  }
}