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
//! A collapsible: a header that is pressed, and what it shows while it is open.

use std::sync::Arc;

use super::{
  icon::Icon,
  icons, names,
  part_style::{Length, PartAnimation, PartTransition},
  recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
  shared::{FADE_IN, FADE_OUT, IconChoice, fading, pressable, shown_icon},
  theme::{Themed, current_theme},
};
use crate::{
  animation::Transition,
  app::theme::{
    IconSize, MotionDuration, MotionEasing, OpacityLevel, PaletteColor, RadiusSize, Theme, TypographyStyle,
  },
  components::{self, Column, Row},
  core::Signal,
  layout::{Alignment, layout_kind::Justify},
  node::{CursorIcon, Element, FocusGroup, color::Color},
};

/// The parts of a collapsible a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CollapsiblePart {
  /// The header and the panel, one over the other.
  Root,
  /// What is pressed: the header, with the label and the chevron.
  Trigger,
  /// What the header says.
  Label,
  /// The icon at the end of the header that says it opens.
  Chevron,
  /// What opens and closes: as high as what it holds while the collapsible is open, of no height while it is
  /// closed, and clipped on the way between them.
  Panel,
  /// What the panel holds, in its padding: the app's content.
  Body,
}

names!(CollapsiblePart {
  Root => "root",
  Trigger => "trigger",
  Label => "label",
  Chevron => "chevron",
  Panel => "panel",
  Body => "body",
});

/// The states of a collapsible a recipe styles, besides what the pointer and
/// the keyboard do to it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CollapsibleState {
  /// It is open.
  Open,
  /// It takes no input.
  Disabled,
}

names!(CollapsibleState {
  Open => "open",
  Disabled => "disabled",
});

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

/// What a collapsible shows while it is open: the app's element, or a text in the body's type.
pub(crate) enum Content {
  Element(Element),
  Text(Arc<str>),
}

/// A header that shows or hides what is under it: the crates of a
/// workspace, the details of an order, the options a person rarely needs.
///
/// ```
/// use lurq::{components::Column, ui::Collapsible};
///
/// let crates = Collapsible::new("3 crates in this workspace", Column::new())
///   .open(true)
///   .on_open_change(|open| println!("open: {open}"));
/// // A text in the body's type.
/// let note = Collapsible::text("Why is this here?", "Because the build needs it.");
/// # fn bound(details: lurq::core::Signal<bool>) {
/// // Open while the signal is true, which a press turns.
/// let bound = Collapsible::text("Details", "What it holds.").bind(details);
/// # }
/// ```
///
/// A collapsible does not keep whether it is open: the app says so with
/// [`Collapsible::open`], or binds it to a signal with [`Collapsible::bind`],
/// and is told of a press of the header with [`Collapsible::on_open_change`].
/// What it holds opens and closes with its height
/// over the theme's duration, at once where motion is reduced; while it is
/// closed it is not there, and the controls in it are not stops of Tab.
pub struct Collapsible {
  label: Arc<str>,
  body: Content,
  open: bool,
  disabled: bool,
  icon: Option<IconChoice>,
  open_icon: Option<IconChoice>,
  states: Vec<Name>,
  rules: Recipe,
  forced: Option<Interaction>,
  on_open_change: Vec<Arc<dyn Fn(bool) + Send + Sync>>,
  bound: Option<Signal<bool>>,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl Collapsible {
  /// A collapsible whose header says `label`, and that shows `content` while it is open.
  pub fn new(label: &str, content: impl Into<Element>) -> Self {
    Self::of(label, Content::Element(content.into()))
  }

  /// A collapsible whose header says `label`, and that shows the text `body` while it is open.
  pub fn text(label: &str, body: &str) -> Self {
    Self::of(label, Content::Text(Arc::from(body)))
  }

  fn of(label: &str, body: Content) -> Self {
    Self {
      label: Arc::from(label),
      body,
      open: false,
      disabled: false,
      icon: None,
      open_icon: None,
      states: Vec::new(),
      rules: Recipe::new(),
      forced: None,
      on_open_change: Vec::new(),
      bound: None,
      id: None,
      key: None,
    }
  }

  /// Whether what it holds is shown.
  pub fn open(mut self, open: bool) -> Self {
    self.open = open;
    self
  }

  /// Open while `open` is true, which a press of the header turns. The handlers of
  /// [`on_open_change`](Self::on_open_change) are told of a press after the signal is set; a value the app sets is told
  /// to none of them.
  pub fn bind(mut self, open: Signal<bool>) -> Self {
    self.open = open.get();
    self.bound = Some(open);
    self
  }

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

  /// The icon of the chevron, by its name in the theme's set, in place of `chevrons-vertical`; or none,
  /// `icon(None)`, and the header has no chevron.
  pub fn icon(mut self, icon: impl Into<IconChoice>) -> Self {
    self.icon = Some(icon.into());
    self
  }

  /// The icon of the chevron while the collapsible is open, in place of its [`icon`](Self::icon); or none,
  /// `open_icon(None)`.
  pub fn open_icon(mut self, icon: impl Into<IconChoice>) -> Self {
    self.open_icon = Some(icon.into());
    self
  }

  /// Puts the collapsible 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 of the header, with what the collapsible is to be: open if it was closed.
  pub fn on_open_change(mut self, handler: impl Fn(bool) + Send + Sync + 'static) -> Self {
    self.on_open_change.push(Arc::new(handler));
    self
  }

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

  /// Draws the header 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 header: what is pressed.
  pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
    self.id = Some(id.into());
    self
  }

  /// The key of the header, among what is beside it.
  pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
    self.key = Some(key.into());
    self
  }

  /// Builds the collapsible in `theme`. Converting a collapsible 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(CollapsibleState::Open, self.open)
    .state(CollapsibleState::Disabled, self.disabled);
    let closed = shown_icon(self.icon, icons::CHEVRONS_VERTICAL);
    let icon = match self.open_icon {
      Some(IconChoice(opened)) if self.open => opened,
      _ => closed,
    };
    // A bound collapsible sets its signal first: its handlers are told of a press once it is so.
    let mut on_open_change = self.on_open_change;
    if let Some(bound) = self.bound {
      on_open_change.insert(0, Arc::new(move |next| bound.set(next)));
    }
    let view = CollapsibleView {
      label: self.label,
      open: self.open,
      disabled: self.disabled,
      icon,
      recipe: theme
        .resolve::<Collapsible>(&case, Some(&self.rules))
        .owned_by(self.id.as_ref()),
      root: CollapsiblePart::Root.into(),
      body: Some(self.body),
      forced: self.forced,
      on_open_change,
      id: self.id,
      key: self.key,
    };
    match theme.renderer::<Collapsible>() {
      Some(renderer) => renderer(view),
      None => view.render(),
    }
  }
}

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

/// A collapsible as a renderer sees it: what it was given, the style of its
/// parts, and its behavior ready to be dressed. An item of an
/// [`Accordion`](super::Accordion) is one too, in the accordion's recipe.
pub struct CollapsibleView {
  pub label: Arc<str>,
  pub open: bool,
  pub disabled: bool,
  /// The icon of the chevron as the collapsible is now, open or closed: none where it has no chevron.
  pub icon: Option<Name>,
  /// The style of each part of this collapsible.
  pub recipe: ResolvedRecipe,
  /// The part that holds the header and the panel: the root of a collapsible, an item of an accordion.
  pub(crate) root: Name,
  body: Option<Content>,
  forced: Option<Interaction>,
  on_open_change: Vec<Arc<dyn Fn(bool) + Send + Sync>>,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl CollapsibleView {
  /// A view of an item of a group, in the group's `recipe`, whose `root` is the group's part for an item.
  #[allow(clippy::too_many_arguments)]
  pub(crate) fn item(
    label: Arc<str>,
    body: Content,
    open: bool,
    disabled: bool,
    icon: Name,
    recipe: ResolvedRecipe,
    root: Name,
    press: Arc<dyn Fn(bool) + Send + Sync>,
    forced: Option<Interaction>,
    id: Option<Arc<str>>,
    key: Option<Arc<str>>,
  ) -> Self {
    Self {
      label,
      open,
      disabled,
      icon: Some(icon),
      recipe,
      root,
      body: Some(body),
      forced,
      on_open_change: vec![press],
      id,
      key,
    }
  }

  /// The style of a part, as this collapsible 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 collapsible is to be.
  fn press(&self) -> Option<impl Fn() + Send + Sync + Clone + 'static> {
    let (handlers, next) = (self.on_open_change.clone(), !self.open);
    (!handlers.is_empty() && !self.disabled).then(|| {
      move || {
        for handler in &handlers {
          handler(next);
        }
      }
    })
  }

  /// The collapsible's behavior with the style of its header: the element
  /// that is pressed, focused and disabled, with nothing in it yet. It is a
  /// button to what reads the tree, called by its label, and says whether
  /// what it opens is open.
  pub fn trigger(&self) -> components::Button {
    let mut trigger = pressable(&self.part(CollapsiblePart::Trigger), self.disabled)
      .justify(Justify::Start)
      .align_items(Alignment::Center)
      .describe("a11y_role", "button")
      .describe("a11y_name", self.label.clone())
      .describe("a11y_expanded", if self.open { "true" } else { "false" });
    if let Some(press) = self.press() {
      trigger = trigger.on_click(move |_| press());
    }
    if let Some(id) = &self.id {
      trigger = trigger.id(id.clone());
    }
    if let Some(key) = &self.key {
      trigger = trigger.key(key.clone());
    }
    trigger
  }

  /// The label in the style of its part, taking the room of the header the chevron does not.
  pub fn label(&self) -> Row {
    let part = self.part(CollapsiblePart::Label);
    Row::new().flex(1.0).part(&part).child(part.text(&self.label))
  }

  /// The chevron: the icon of the collapsible as it is now, an icon of the theme's middle size in the middle of
  /// its part. None where the collapsible has no icon.
  pub fn chevron(&self) -> Option<Row> {
    let part = self.part(CollapsiblePart::Chevron);
    let icon = Icon::new(self.icon?)
      .size(Length::Icon(IconSize::Md))
      .build(self.theme());
    Some(
      Row::new()
        .justify(Justify::Center)
        .align_items(Alignment::Center)
        .part(&part)
        .child(icon),
    )
  }

  /// What opens and closes, with what it holds while the collapsible is open. Its height is the recipe's: of
  /// none while it is closed and its content's while it is open, with a transition between the two. What it
  /// held stays while the panel closes over it, only painted, and is gone with the body's exit animation.
  pub fn panel(&mut self) -> Column {
    let mut panel = Column::new()
      .align_items(Alignment::Stretch)
      .clip()
      .presence()
      .part(&self.part(CollapsiblePart::Panel));
    if self.open
      && let Some(body) = self.body.take()
    {
      let part = self.part(CollapsiblePart::Body);
      let content: Element = match body {
        Content::Element(element) => element,
        Content::Text(text) => part.text(&text).into(),
      };
      // Keyed, so that what the panel held is told apart from what it holds next, and kept as it leaves.
      // What it holds is in no group of the arrow keys: an accordion's move between its headers, past it.
      panel = panel.child(
        Column::new()
          .key("content")
          .focus_group(FocusGroup::none())
          .align_items(Alignment::Stretch)
          .part(&part)
          .child(content),
      );
    }
    panel
  }

  /// How the default renderer builds a collapsible: the header with its label and chevron, and the panel under
  /// it.
  pub fn render(mut self) -> Element {
    let mut trigger = self.trigger().child(self.label());
    if let Some(chevron) = self.chevron() {
      trigger = trigger.child(chevron);
    }
    let panel = self.panel();
    Column::new()
      .align_items(Alignment::Stretch)
      // The ring of the focus is drawn around the header, outside it.
      .overflow_visible()
      .part(&self.part(self.root))
      .child(trigger)
      .child(panel)
      .into()
  }
}

/// What opens and closes in the design's collapsible and accordion: a panel
/// of no height while closed and of its content's while open, over the
/// theme's base duration; the body fades in as it opens and out as it
/// closes.
pub(crate) fn opening(recipe: Recipe, open: Name, panel: Name, body: Name) -> Recipe {
  recipe
    .base(panel, |s| {
      s.height(0.0)
        .transition(PartTransition::new(Transition::height(), MotionDuration::Base))
    })
    .state(open, panel, |s| s.height(Length::Auto))
    .base(body, |s| {
      s.enter(PartAnimation::new(
        FADE_IN,
        MotionDuration::Base,
        MotionEasing::Standard,
      ))
      .exit(PartAnimation::new(
        FADE_OUT,
        MotionDuration::Base,
        MotionEasing::Standard,
      ))
    })
}

impl crate::ui::Styled for Collapsible {
  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 Collapsible {
  const NAME: &'static str = "collapsible";
  type Renderer = CollapsibleRenderer;

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

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

  /// The design's collapsible (`pencil/lurq-design-system.pen`, Collapsible):
  /// a header with its label in the label's type and, at its end, the
  /// `chevrons-vertical` icon of 16 in a ghost button of 32, which the
  /// highlight fills under the pointer; what it opens is 8 under it.
  fn recipe() -> Recipe {
    use CollapsiblePart::{Body, Chevron, Label, Panel, Root, Trigger};
    use PaletteColor::*;
    let recipe = Recipe::new()
      .base(Root, |s| s.foreground(Foreground))
      .base(Trigger, |s| {
        fading(s.gap(8.0).radius(RadiusSize::Md).cursor(CursorIcon::Pointer))
      })
      .base(Label, |s| s.typography(TypographyStyle::Label))
      .base(Chevron, |s| {
        fading(s.square(32.0).radius(RadiusSize::Md))
      })
      .base(Body, |s| s.padding_top(8.0).typography(TypographyStyle::Body))
      .hovered(Chevron, |s| s.background(Highlight).foreground(HighlightForeground))
      .focus_visible(Trigger, |s| s.focus_ring())
      // The header is dimmed, not what it opens: that is the app's, with controls of its own.
      .state(CollapsibleState::Disabled, Trigger, |s| {
        s.opacity(OpacityLevel::Disabled).cursor(CursorIcon::Default)
      })
      // A disabled one does not light its button under the pointer.
      .when(Selector::new().state(CollapsibleState::Disabled).hovered(), Chevron, |s| {
        s.background(Color::new(0, 0, 0, 0)).foreground(Foreground)
      });
    opening(recipe, CollapsibleState::Open.into(), Panel.into(), Body.into())
  }
}