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
//! A search field: an input with the search icon before its text, a button that empties it, and the hint of the key
//! that reaches it.

use std::sync::Arc;

use super::{
  field::{FieldControl, InField},
  icon::Icon,
  icons,
  input::{Input, InputPart, InputView},
  names,
  part_style::{FontFamily, Length, PartStyle},
  recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
  shared::{IconChoice, fading},
  theme::{Themed, current_theme},
};
use crate::{
  app::{
    events::{KeyboardEvent, TextInputEvent},
    theme::{BorderSize, IconSize, PaletteColor, RadiusSize, Theme},
  },
  components::{self, Row},
  core::Signal,
  layout::Alignment,
  node::{CursorIcon, Element, border::Border, dimension::Dimension, node_kind::TextOverflow},
};

/// The widest the hint of a search field's key is: 40% of the board's field.
const SHORTCUT_MAX: f32 = 112.0;

/// The parts of a search field a recipe styles. The box, its text, its placeholder and its icon are an
/// [`Input`]'s: what the field says of them is laid over the theme's recipe for an input.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SearchFieldPart {
  /// What the field says of the input's root: its width.
  Root,
  /// What the field says of the input's box: its padding.
  Control,
  /// What is at the end of the box: the clear button or the hint.
  Trailing,
  /// The button that empties the field, while it holds something.
  Clear,
  /// The key that reaches the field, while it is empty.
  Shortcut,
}

names!(SearchFieldPart {
  Root => "root",
  Control => "control",
  Trailing => "trailing",
  Clear => "clear",
  Shortcut => "shortcut",
});

/// The states of a search field a recipe styles, besides an input's.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SearchFieldState {
  /// It holds something: the clear button is shown.
  Filled,
  /// It is as wide as what holds it.
  FullWidth,
  /// It is in a fluid field ([`Field::fluid`](super::Field::fluid)): the field's label is inside its box, over
  /// what it holds.
  Fluid,
}

names!(SearchFieldState {
  Filled => "filled",
  FullWidth => "full_width",
  Fluid => "fluid",
});

/// The sizes of a search field: an input's.
pub type SearchFieldSize = super::TextBoxSize;

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

/// A search field: an input with the search icon before its text, a button
/// at its end that empties it while it holds something, and the hint of the
/// key that reaches it while it is empty.
///
/// ```
/// use lurq::{core::Signal, ui::SearchField};
///
/// let query = Signal::new(String::new());
/// let search = SearchField::new(query.clone())
///   .placeholder("Search components")
///   .shortcut("/")
///   .on_submit(|query| println!("search for {query}"));
/// ```
///
/// What is typed goes into the signal, which the app filters by as it
/// changes. Escape empties the field while it holds something, and Enter
/// calls [`on_submit`](Self::on_submit) with what it holds. The clear button
/// ([`clearable`](Self::clearable), on unless the app says otherwise) is
/// pressed with the pointer and takes no focus, so the caret stays in the field; from
/// the keyboard, Escape does what it does, so it is no stop of Tab. The hint
/// says the key: the app binds it, and focuses the field on it. To tooling
/// the field is a `searchbox`, and its button "Clear search".
pub struct SearchField {
  input: Input,
  value: Signal<String>,
  shortcut: Option<Arc<str>>,
  clear_label: Arc<str>,
  clearable: bool,
  read_only: bool,
  disabled: bool,
  full_width: bool,
  states: Vec<Name>,
  rules: Recipe,
  input_rules: Recipe,
  forced: Option<Interaction>,
  element_ref: Option<crate::core::ElementRef>,
}

impl SearchField {
  /// A search field bound to `value`: it shows what the signal holds, and what is typed is set on it.
  pub fn new(value: Signal<String>) -> Self {
    let mut input = Input::new(value.clone()).icon(icons::SEARCH);
    input.boxed.role = Some("searchbox");
    Self {
      input,
      value,
      shortcut: None,
      clear_label: super::current_locale().fields.clear_search.clone(),
      clearable: true,
      read_only: false,
      disabled: false,
      full_width: false,
      states: Vec::new(),
      rules: Recipe::new(),
      input_rules: Recipe::new(),
      forced: None,
      element_ref: None,
    }
  }

  /// What the field says while it is empty.
  pub fn placeholder(mut self, placeholder: &str) -> Self {
    self.input = self.input.placeholder(placeholder);
    self
  }

  /// The key that reaches the field, shown at its end while it is empty: `/`, `Ctrl K`. The app binds the key.
  pub fn shortcut(mut self, key: &str) -> Self {
    self.shortcut = Some(Arc::from(key));
    self
  }

  /// What the clear button is called to tooling, in place of "Clear search": in another language.
  pub fn clear_label(mut self, label: &str) -> Self {
    self.clear_label = Arc::from(label);
    self
  }

  /// Whether the field has its clear button while it holds something, and Escape empties it: on unless the app
  /// says otherwise, a search field being what is emptied to search again.
  pub fn clearable(mut self, clearable: bool) -> Self {
    self.clearable = clearable;
    self
  }

  /// The icon before the text, in place of the search icon, or none: `icon(None)`.
  pub fn icon(mut self, icon: impl Into<IconChoice>) -> Self {
    self.input = self.input.with_icon(icon.into().0);
    self
  }

  /// The ref of the field's text input: what the app focuses on the key the hint shows (`ctx.focus`).
  pub fn ref_element(mut self, element: crate::core::ElementRef) -> Self {
    self.element_ref = Some(element);
    self
  }

  /// Called on Enter with what the field holds. The focus stays in the field. A second handler is called after
  /// the first.
  pub fn on_submit(mut self, handler: impl Fn(&str) + Send + Sync + 'static) -> Self {
    self.input = self.input.on_submit(handler);
    self
  }

  /// Called before an edit is made, with what the field will hold: a handler may refuse it.
  pub fn on_input(mut self, handler: impl Fn(&TextInputEvent) + Send + Sync + 'static) -> Self {
    self.input = self.input.on_input(handler);
    self
  }

  /// An [`InputSize`](super::InputSize), or a size the theme's recipe names.
  pub fn size(mut self, size: impl Into<Name>) -> Self {
    self.input = self.input.size(size);
    self
  }

  /// Whether what the field holds is wrong.
  pub fn invalid(mut self, invalid: bool) -> Self {
    self.input = self.input.invalid(invalid);
    self
  }

  /// Whether what the field holds is allowed with a caveat.
  pub fn warning(mut self, warning: bool) -> Self {
    self.input = self.input.warning(warning);
    self
  }

  /// Whether what the field holds was checked and is right.
  pub fn valid(mut self, valid: bool) -> Self {
    self.input = self.input.valid(valid);
    self
  }

  /// Whether the field can be read and not changed: it has no clear button, and Escape does not empty it.
  pub fn read_only(mut self, read_only: bool) -> Self {
    self.read_only = read_only;
    self.input = self.input.read_only(read_only);
    self
  }

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

  /// What the field is called, to what reads the tree. A field gives it its label.
  pub fn label(mut self, label: &str) -> Self {
    self.input = self.input.label(label);
    self
  }

  /// Whether the field is as wide as what holds it, in place of the design's 280.
  pub fn full_width(mut self, full_width: bool) -> Self {
    self.full_width = full_width;
    self.input = self.input.full_width(full_width);
    self
  }

  /// The name the query has in the form it is in.
  #[cfg(feature = "form")]
  pub fn name(mut self, name: impl Into<Arc<str>>) -> Self {
    self.input = self.input.name(name);
    self
  }

  /// Puts the search field 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 search field over what the theme gives it.
  pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
    self.rules = self.rules.base(part, style);
    self
  }

  /// Lays rules over the theme's recipe for this search field.
  pub fn rules(mut self, rules: &Recipe) -> Self {
    self.rules = self.rules.extend(rules);
    self
  }

  /// Lays rules over the theme's recipe for the input it is made of, and over what the field says of it.
  pub fn input_rules(mut self, rules: &Recipe) -> Self {
    self.input_rules = self.input_rules.extend(rules);
    self
  }

  /// Draws the field as it is under the pointer or focused, with nothing pointing at it.
  pub fn force(mut self, interaction: Option<Interaction>) -> Self {
    self.forced = interaction;
    self.input = self.input.force(interaction);
    self
  }

  /// The id of the control: what is typed in and focused.
  pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
    self.input = self.input.id(id);
    self
  }

  pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
    self.input = self.input.key(key);
    self
  }

  /// Builds the search field in `theme`. Converting it into an element does this in the theme of what is being
  /// rendered, which renders again as the field fills and empties.
  pub fn build(self, theme: &Theme) -> Element {
    let filled = !self.value.get().is_empty();
    let case: Case = self
      .input
      .boxed
      .case(self.states.clone())
      .state(SearchFieldState::Filled, filled)
      .state(SearchFieldState::FullWidth, self.full_width);
    // The id is the input's: a part lent to the field is lent on to it, and the field's own parts are counted
    // with the input's.
    let recipe = theme.resolve::<SearchField>(&case, Some(&self.rules)).owned_by(None);
    let of_input = recipe
      .rules_for(SearchFieldPart::Root, InputPart::Root)
      .extend(&recipe.rules_for(SearchFieldPart::Control, InputPart::Control));
    let input = self.input.rules(&of_input).rules(&self.input_rules).view(theme);
    let recipe = recipe.owned_like(&input.recipe);
    let view = SearchFieldView {
      filled,
      shortcut: self.shortcut,
      clear_label: self.clear_label,
      clearable: self.clearable,
      editable: !self.read_only && !self.disabled,
      recipe,
      forced: self.forced,
      element_ref: self.element_ref,
      input,
    };
    match theme.renderer::<SearchField>() {
      Some(renderer) => renderer(view),
      None => view.render(),
    }
  }
}

impl FieldControl for SearchField {
  /// Called by the field's label unless it has a name of its own, judged as the field is unless the app judged the
  /// search field itself, and disabled where the field is.
  fn in_field(mut self, field: &InField) -> Element {
    self.input.boxed.in_field(field);
    self.disabled = self.input.boxed.disabled;
    self.into()
  }

  fn has_fluid_form(&self) -> bool {
    true
  }
}

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

/// A search field as a renderer sees it: the input it is made of, the style of its own parts, and its behavior.
pub struct SearchFieldView {
  /// The input the query is typed in: its box, its text, its placeholder, its icon.
  pub input: InputView,
  /// Whether the field holds something: its clear button is shown in place of the hint.
  pub filled: bool,
  pub shortcut: Option<Arc<str>>,
  pub clear_label: Arc<str>,
  /// Whether the field has its clear button, and Escape empties it.
  pub clearable: bool,
  /// Whether what the field holds can be changed: it is neither read only nor disabled.
  pub editable: bool,
  /// The style of each of the search field's own parts.
  pub recipe: ResolvedRecipe,
  forced: Option<Interaction>,
  element_ref: Option<crate::core::ElementRef>,
}

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

  fn px(&self, length: Option<Length>) -> f32 {
    match length.and_then(|length| length.resolve(self.theme())) {
      Some(Dimension::Px(px)) => px,
      _ => 0.0,
    }
  }

  /// Whether the clear button is shown: the field holds something that can be taken away.
  fn clears(&self) -> bool {
    self.filled && self.editable && self.clearable
  }

  /// How wide the hint is: its padding and a cell of the mono type for each of its characters. It is laid over
  /// the end of the box before it is laid out, so the box keeps room for it by this.
  fn shortcut_width(&self, key: &str) -> f32 {
    // A cell of a mono type is about 0.6 of its size.
    const CELL: f32 = 0.6;
    let style = self.part(SearchFieldPart::Shortcut).rest();
    let padding = style
      .padding_x
      .map(|padding| padding.resolve(&self.theme().spacing(), 0.0))
      .unwrap_or(0.0);
    let size = style.text.resolve(self.theme()).font_size;
    (2.0 * padding + key.chars().count() as f32 * size * CELL).min(SHORTCUT_MAX)
  }

  /// The input's text input: a stop of Tab, a `searchbox` to tooling, where Escape empties what it holds and Enter
  /// submits it, keeping room at its end for the clear button or the hint.
  pub fn control(&self) -> components::TextInput {
    let mut control = self.input.control();
    let end = if self.clears() {
      Some(self.px(self.part(SearchFieldPart::Clear).rest().width))
    } else if let Some(key) = self.shortcut.as_deref().filter(|_| !self.filled) {
      Some(self.shortcut_width(key))
    } else {
      None
    };
    if let Some(end) = end {
      control = control.padding_right(self.input.end_room(end));
    }
    if let Some(element) = &self.element_ref {
      control = control.ref_element(element.clone());
    }
    let (value, empties) = (self.input.value.clone(), self.editable && self.clearable);
    // A key reaches every node: this acts only while the focus is in the field, and leaves a composition's keys to
    // it. Enter is the input's (`on_submit`).
    control.on_key_down(move |event: KeyboardEvent| {
      if !event.focus_within || event.composing || event.ctrl || event.alt || event.meta {
        return;
      }
      if event.key == "Escape" && empties && !value.get_untracked().is_empty() {
        event.prevent_default();
        value.set(String::new());
      }
    })
  }

  /// The button that empties the field, while it holds something. A press of it leaves the focus where it is.
  pub fn clear(&self) -> Option<Row> {
    if !self.clears() {
      return None;
    }
    let part = self.part(SearchFieldPart::Clear);
    let side = part.rest().width.unwrap_or(Length::Icon(IconSize::Md));
    let value = self.input.value.clone();
    Some(
      Row::new()
        .part(&part)
        .describe("a11y_role", "button")
        .describe("a11y_name", self.clear_label.clone())
        // A press of it takes no focus and leaves it where it is: in the field, where the text was typed.
        .focusable(false)
        .on_click(move |_| value.set(String::new()))
        .child(Icon::new(icons::CLOSE_CIRCLE).size(side).build(self.theme())),
    )
  }

  /// The hint of the key that reaches the field, while it is empty. The pointer passes through it. It is never
  /// wider than 112: a longer one is cut with an ellipsis, and the field keeps its icon and its text.
  pub fn shortcut(&self) -> Option<Row> {
    let key = self.shortcut.as_ref().filter(|_| !self.filled)?;
    let part = self.part(SearchFieldPart::Shortcut);
    Some(
      Row::new()
        .align_items(Alignment::Center)
        .pointer_events_none()
        .max_width(Dimension::Px(SHORTCUT_MAX))
        .part(&part)
        .child(part.text(key).nowrap().text_overflow(TextOverflow::Elipsis)),
    )
  }

  /// How the default renderer builds a search field: the input, with the clear button or the hint over the end
  /// of its box.
  pub fn render(self) -> Element {
    let end = match (self.clear(), self.shortcut()) {
      (Some(clear), _) => Some(clear),
      (None, Some(shortcut)) => Some(shortcut),
      (None, None) => None,
    }
    .map(|item| Row::new().part(&self.part(SearchFieldPart::Trailing)).child(item));
    self.input.render_with_end(self.control(), end).into()
  }
}

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

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

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

  /// The design's search field (`pencil/lurq-design-system.pen`, Search Field): an input 280 wide whose box is
  /// padded 10 at its start and 8 at its end, the search icon of 16 in the muted foreground 8 before the text.
  /// While it holds something a clear button of 16 in the muted foreground is at its end, in the foreground under
  /// the pointer; while it is empty, the hint of its key: 20 high, padded 6, 4 round on the muted fill in an edge
  /// of 1 in the border's color, in the mono type of 11 in the muted foreground. In a fluid field the box is the
  /// input's fluid one, as wide as the field and padded 12 at its start, where the field's label starts; the icon, the
  /// clear button and the hint are on the line of the query.
  fn recipe() -> Recipe {
    use PaletteColor::{Foreground, Muted, MutedForeground};
    use SearchFieldPart::{Clear, Control, Root, Shortcut, Trailing};
    Recipe::new()
      .base(Root, |s| s.width(280.0).max_width(Length::Fill))
      .state(SearchFieldState::FullWidth, Root, |s| s.width(Length::Fill))
      .state(SearchFieldState::Fluid, Root, |s| s.width(Length::Fill))
      .base(Control, |s| s.padding_start(10.0).padding_end(8.0))
      .state(SearchFieldState::Fluid, Control, |s| s.padding_start(12.0))
      .base(Trailing, |s| s.gap(8.0))
      .base(Clear, |s| {
        fading(
          s.square(IconSize::Md)
            .radius(RadiusSize::Sm)
            .foreground(MutedForeground)
            .cursor(CursorIcon::Pointer),
        )
      })
      .hovered(Clear, |s| s.foreground(Foreground))
      .base(Shortcut, |s| {
        s.height(20.0)
          .padding_x(6.0)
          .radius(RadiusSize::Sm)
          .background(Muted)
          .border(Border::inside(BorderSize::Sm, PaletteColor::Border))
          .font_family(FontFamily::Mono)
          .font_size(11.0)
          .foreground(MutedForeground)
      })
  }
}