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
//! A callout: a note set apart inside prose or a form.

use std::sync::Arc;

use super::{
  AlertVariant,
  alert::{IconChoice, shown_icon, wrapping},
  names,
  part_style::Length,
  recipe::{Case, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
  shared::glyph,
  theme::{Themed, current_breakpoint, current_theme},
};
use crate::{
  app::theme::{IconSize, PaletteColor, RadiusSize, Theme, TypographyStyle},
  components::{Column, Row},
  layout::{Alignment, text_style::FontWeight},
  node::{Element, border::Border, dimension::Dimension},
};

/// The parts of a callout a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CalloutPart {
  /// The box: its fill, its corners, its bar, and the room inside it.
  Root,
  /// The icon of its variant: at the start, or before the title where it
  /// has a bar.
  Icon,
  /// The icon and the title side by side, over the text, where it has a bar
  /// and a title.
  Header,
  /// The title, what it says and what the app put in it, one over the other.
  Text,
  /// What it is, in a word: "Note", "Tip".
  Title,
  /// What it says.
  Label,
}

names!(CalloutPart {
  Root => "root",
  Icon => "icon",
  Header => "header",
  Text => "text",
  Title => "title",
  Label => "label",
});

/// The states of a callout a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CalloutState {
  /// It has a bar along its start, as a note of a document has.
  Bar,
  /// It has a title.
  Title,
}

names!(CalloutState {
  Bar => "bar",
  Title => "title",
});

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

/// A callout: a note set apart inside prose or a form. A hint beside a
/// setting, a caution in a page of documentation.
///
/// ```
/// use lurq::ui::{AlertVariant, Callout, icons};
///
/// let note = Callout::new("Theme changes rerender only the components that read the theme.")
///   .variant(AlertVariant::Info);
/// // A note of a document: a bar along its start, the icon before its title.
/// let tip = Callout::new("Use backdrop blur for panels over busy content.")
///   .title("Tip")
///   .variant(AlertVariant::Success)
///   .icon(icons::LIGHTBULB)
///   .bar(true);
/// ```
///
/// It is read, and is no stop of Tab: a `note` to tooling that reads the
/// tree, called by its label, or by its title where it has one.
///
/// What it says is its one sentence, given to [`Callout::new`], and its title
/// is the word over it: "Tip", "Note". An alert and a toast are the other way
/// round, a title and a description under it, as a message about something
/// that happened is.
pub struct Callout {
  text: Arc<str>,
  title: Option<Arc<str>>,
  body: Vec<Element>,
  variant: Name,
  icon: Option<IconChoice>,
  bar: bool,
  role: Option<Arc<str>>,
  label: Option<Arc<str>>,
  states: Vec<Name>,
  rules: Recipe,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl Callout {
  /// A callout that says `text`. An empty one says nothing, for a callout of
  /// a title and elements alone.
  pub fn new(text: &str) -> Self {
    Self {
      text: Arc::from(text),
      title: None,
      body: Vec::new(),
      variant: AlertVariant::Neutral.into(),
      icon: None,
      bar: false,
      role: None,
      label: None,
      states: Vec::new(),
      rules: Recipe::new(),
      id: None,
      key: None,
    }
  }

  /// What it is, in a word, over its text: "Note", "Tip", "Warning".
  pub fn title(mut self, title: &str) -> Self {
    self.title = Some(Arc::from(title));
    self
  }

  /// Adds an element under the text: a link, a list, a row of code.
  pub fn child(mut self, child: impl Into<Element>) -> Self {
    self.body.push(child.into());
    self
  }

  /// Adds elements under the text.
  pub fn children(mut self, children: impl IntoIterator<Item = impl Into<Element>>) -> Self {
    self.body.extend(children.into_iter().map(Into::into));
    self
  }

  /// Its tone: an [`AlertVariant`], or a variant a theme adds, which has the
  /// neutral one's icon.
  pub fn variant(mut self, variant: impl Into<Name>) -> Self {
    self.variant = variant.into();
    self
  }

  /// An icon of the theme's set in place of the variant's, or none: `icon(None)`.
  pub fn icon(mut self, icon: impl Into<IconChoice>) -> Self {
    self.icon = Some(icon.into());
    self
  }

  /// Whether it has a bar along its start in the variant's color, its title
  /// in that color with the icon before it, as a note of a document has.
  pub fn bar(mut self, bar: bool) -> Self {
    self.bar = bar;
    self
  }

  /// What it is called to tooling that reads the tree, in place of its title.
  pub fn label(mut self, label: &str) -> Self {
    self.label = Some(Arc::from(label));
    self
  }

  /// What it is to tooling that reads the tree, in place of a `note`.
  pub fn role(mut self, role: &str) -> Self {
    self.role = Some(Arc::from(role));
    self
  }

  /// Puts the callout 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 callout 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 callout.
  pub fn rules(mut self, rules: &Recipe) -> Self {
    self.rules = self.rules.extend(rules);
    self
  }

  /// The id of the box.
  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 callout in `theme`. Converting a callout into an element
  /// does this in the theme of what is being rendered.
  pub fn build(self, theme: &Theme) -> Element {
    // A variant a theme adds has the neutral one's icon.
    let tone = AlertVariant::named(self.variant).unwrap_or_default();
    let case = Case {
      variant: Some(self.variant),
      size: None,
      density: None,
      breakpoint: current_breakpoint(),
      states: self.states.clone(),
    }
    .state(CalloutState::Bar, self.bar)
    .state(CalloutState::Title, self.title.is_some());
    let view = CalloutView {
      text: self.text,
      title: self.title,
      body: self.body,
      variant: self.variant,
      icon: shown_icon(self.icon, tone.icon()),
      bar: self.bar,
      role: self.role.unwrap_or_else(|| Arc::from("note")),
      label: self.label,
      recipe: theme
        .resolve::<Callout>(&case, Some(&self.rules))
        .owned_by(self.id.as_ref()),
      id: self.id,
      key: self.key,
    };
    match theme.renderer::<Callout>() {
      Some(renderer) => renderer(view),
      None => view.render(),
    }
  }
}

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

/// A callout as a renderer sees it: what it was given and the style of its
/// parts.
pub struct CalloutView {
  pub text: Arc<str>,
  pub title: Option<Arc<str>>,
  /// What the app put under the text.
  pub body: Vec<Element>,
  /// Its tone: an [`AlertVariant`]'s name, or a theme's.
  pub variant: Name,
  /// The icon it shows, by its name in the theme's set: the variant's, the one it was given, or none.
  pub icon: Option<Name>,
  pub bar: bool,
  /// What it is to tooling that reads the tree: a `note`, or what the app said.
  pub role: Arc<str>,
  /// What it is called to tooling, where that is not its title.
  pub label: Option<Arc<str>>,
  /// The style of each part of this callout.
  pub recipe: ResolvedRecipe,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl CalloutView {
  /// The style of a part, as this callout 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 icon in the style of its part, if the callout has one.
  pub fn icon(&self) -> Option<Element> {
    self.icon.map(|icon| glyph(&self.part(CalloutPart::Icon), icon, false))
  }

  /// The title in the style of its part, as wide as the room it has.
  pub fn title(&self) -> Option<Column> {
    let title = self.title.as_ref()?;
    Some(wrapping(&self.part(CalloutPart::Title), title))
  }

  /// The icon and the title side by side: what a callout with a bar and a
  /// title has over its text.
  pub fn header(&self) -> Option<Row> {
    let title = self.title()?;
    let mut header = Row::new()
      .width(Dimension::Pct(100.0))
      .align_items(Alignment::Center)
      .part(&self.part(CalloutPart::Header));
    if let Some(icon) = self.icon() {
      header = header.child(icon);
    }
    Some(header.child(title.flex(1.0).min_width(Dimension::Px(0.0))))
  }

  /// What it says, and what the app put under it, one over the other: with
  /// the title over them where `titled`.
  pub fn text(&mut self, titled: bool) -> Column {
    let mut text = Column::new()
      .flex(1.0)
      .min_width(Dimension::Px(0.0))
      .part(&self.part(CalloutPart::Text));
    if titled && let Some(title) = self.title() {
      text = text.child(title);
    }
    if !self.text.is_empty() {
      text = text.child(wrapping(&self.part(CalloutPart::Label), &self.text));
    }
    text.with_children(std::mem::take(&mut self.body))
  }

  /// How the default renderer builds a callout: the icon at the start and
  /// the text beside it, or, with a bar and a title, the header over the
  /// text. It is what its role says to what reads the tree, called by its
  /// label or its title.
  pub fn render(mut self) -> Element {
    // The root is a row or a column: each is given the root's style, role, name, id and key alike.
    macro_rules! dressed {
      ($root:expr) => {{
        let mut root = $root
          .part(&self.part(CalloutPart::Root))
          .describe("a11y_role", self.role.clone());
        if let Some(name) = self.label.as_ref().or(self.title.as_ref()) {
          root = root.describe("a11y_name", name.clone());
        }
        if let Some(id) = &self.id {
          root = root.id(id.clone());
        }
        if let Some(key) = &self.key {
          root = root.key(key.clone());
        }
        Element::from(root)
      }};
    }
    // The header is built only where it is drawn: a part built and dropped would take an id from the next.
    let header = if self.bar { self.header() } else { None };
    match header {
      Some(header) => {
        let text = self.text(false).flex(0.0).width(Dimension::Pct(100.0));
        dressed!(Column::new().child(header).child(text))
      }
      None => {
        let mut row = Row::new().align_items(Alignment::Start);
        if let Some(icon) = self.icon() {
          row = row.child(icon);
        }
        let text = self.text(true);
        dressed!(row.child(text))
      }
    }
  }
}

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

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

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

  /// The design's callout (`pencil/lurq-design-system.pen`, Callout): a box
  /// as wide as the room it is given in the muted form of the variant's
  /// color (the muted fill for a neutral one), corners of `radius-md`,
  /// padded 12 and 14. The icon of 16 in the variant's color is 10 from the
  /// text, 13 in the foreground's and 1.5 high; a title over it is semibold.
  /// With a bar it is the board's note of a document (Markdown/Admonition):
  /// a bar of 3 along its start in the variant's color and square corners on
  /// that side, the icon 8 before a title of 14, semibold, in the variant's
  /// color, the text of 14 4 under them.
  fn recipe() -> Recipe {
    use CalloutPart as P;
    use CalloutState::{Bar, Title};
    let mut recipe = Recipe::new()
      .base(P::Root, |s| {
        s.width(Length::Fill)
          .background(PaletteColor::Muted)
          .foreground(PaletteColor::Foreground)
          .radius(RadiusSize::Md)
          .padding_x(14.0)
          .padding_y(12.0)
          .gap(10.0)
      })
      .base(P::Icon, |s| {
        s.square(Length::Icon(IconSize::Md))
          .foreground(PaletteColor::Foreground)
      })
      .base(P::Header, |s| s.gap(8.0))
      .base(P::Text, |s| s.gap(4.0))
      .base(P::Title, |s| {
        s.typography(TypographyStyle::Body)
          .font_size(13.0)
          .weight(FontWeight::SemiBold)
          .foreground(PaletteColor::Foreground)
      })
      .base(P::Label, |s| {
        s.typography(TypographyStyle::Body)
          .font_size(13.0)
          .line_height(1.5)
          .foreground(PaletteColor::Foreground)
      })
      .state(Bar, P::Root, |s| s.corners(0.0, RadiusSize::Md, RadiusSize::Md, 0.0))
      .when(Selector::new().state(Bar).state(Title), P::Root, |s| s.gap(4.0))
      .state(Bar, P::Title, |s| s.font_size(14.0))
      .state(Bar, P::Label, |s| s.font_size(14.0));
    for variant in AlertVariant::all().iter().copied() {
      let barred = || Selector::new().variant(variant).state(Bar);
      recipe = recipe
        .variant(variant, P::Root, |s| s.background(variant.tint()))
        .variant(variant, P::Icon, |s| s.foreground(variant.accent()))
        .when(barred(), P::Root, |s| {
          s.start_line(Border::inside(3.0, variant.accent()))
        })
        .when(barred(), P::Title, |s| s.foreground(variant.accent()));
    }
    recipe
  }
}