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
//! The open `Select` menu: building its overlay each pass and the keyboard
//! defaults of a focused select.

use std::sync::Arc;

use super::{Tree, clamp_overlay_position, find_node_by_id, overlay_position, resolve_overlay_collision};
use crate::{
  app::{
    ctx::{CollisionStrategy, Placement},
    events::{MouseButton, MouseEvent},
  },
  core::ElementRect,
  layout::{Alignment, Size, layout_kind::Justify, layout_result::LayoutResult},
  node::{
    EventHandler, Node, NodeUpdate, SelectAdornmentState, SelectCheckmarkPosition, SelectPartStyle, SelectStyle,
    SpacingValue, Style, SyntheticNodeRole,
    border::ThemedBorderRadius,
    dimension::Dimension,
    node_kind::{NodeKind, SelectState, TextOverflow},
    radius_value::RadiusValue,
    select_style::SelectOptionState,
  },
  time::Instant,
};

/// Minimum option row height when the option part sets none.
const SELECT_OPTION_ROW_HEIGHT: f32 = 34.0;

/// Builds the menu of an open select below (or, without room, above) the
/// trigger at `bounds`. `measure` lays the menu out so its real height places
/// it and the option the state asks to reveal is scrolled into view.
pub(super) fn build_select_menu(
  state: &SelectState,
  bounds: ElementRect,
  viewport: Size,
  measure: &mut dyn FnMut(&Node) -> LayoutResult,
) -> Node {
  let style = state.style();
  let labels = state.labels();
  // A group's separator and label are rows of their own: where each option's row is among them.
  let mut rows = Vec::with_capacity(labels.len());
  let mut positions = Vec::with_capacity(labels.len());
  for (index, label) in labels.iter().enumerate() {
    if let Some(group) = state.group(index) {
      if !rows.is_empty() {
        rows.push(separator_row(&style));
      }
      if !group.is_empty() {
        rows.push(group_label_row(&style, &group));
      }
    }
    positions.push(rows.len());
    rows.push(option_row(state, &style, index, label, labels.len(), false, measure));
  }
  // A list as wide as its longest option: each option as wide as what it holds, with the room of a mark, in the
  // menu's own padding and border.
  let fitted = style.menu_fits_options.then(|| {
    let options = labels
      .iter()
      .enumerate()
      .map(|(index, label)| option_row(state, &style, index, label, labels.len(), true, measure))
      .collect();
    let probe = Node::column(0.0, Alignment::Start, options).apply_select_part(&style.menu);
    measure(&probe).size.width.ceil()
  });
  // What the list says of itself, after its options: that it has none, or that more are loading.
  if let Some(status) = state.status() {
    let mut row = Node::row(0.0, Alignment::Center, vec![status.into_node()]).width(Dimension::Pct(100.0));
    row.set_tag_name("SelectStatus");
    rows.push(row);
  }

  // The menu's padding goes on the scrolled list, so it scrolls with the
  // options like CSS padding on a scroll container.
  let mut menu_part = style.menu.clone();
  let mut list = Node::column(0.0, Alignment::Start, rows).width(Dimension::Pct(100.0));
  if let Some(padding) = menu_part.padding.take() {
    list = list.padding_custom(padding);
  }
  let width = fitted
    .unwrap_or(bounds.width)
    .max(style.min_menu_width)
    .min(viewport.width.max(0.0));
  let mut menu = crate::node::dsl::scroll_vertical(list)
    .with_scroll_state(state.menu_scroll())
    .apply_select_part(&menu_part)
    .width(Dimension::Px(width))
    .max_height(Dimension::Px(style.max_menu_height));
  if let Some(scrollbar) = &style.menu_scrollbar {
    menu = menu.scrollbar(scrollbar.clone());
  }
  menu.set_tag_name("SelectMenu");
  menu.set_synthetic_role(SyntheticNodeRole::SelectMenu);
  // To what reads the tree, a listbox, which says which of its options the keys are on.
  NodeUpdate::describe(&mut menu, Arc::from("a11y_role"), Arc::from("listbox"));
  if let Some(label) = state.highlighted().and_then(|index| labels.get(index)) {
    NodeUpdate::describe(&mut menu, Arc::from("a11y_activedescendant"), label.clone());
  }

  let measured = measure(&menu);
  if let Some(index) = state.take_reveal()
    && let Some((start, end)) = positions.get(index).and_then(|row| option_extent(&measured, *row))
  {
    state.menu_scroll().reveal_y_pending(start, end);
  }

  let overlay_size = Size::new(width, measured.size.height);
  let placement = resolve_overlay_collision(
    Placement::BottomStart,
    bounds,
    overlay_size,
    viewport,
    0.0,
    style.menu_gap,
    CollisionStrategy::FlipThenClamp,
  );
  let (x, y) = overlay_position(bounds, overlay_size, placement, 0.0, style.menu_gap);
  let (x, y) = clamp_overlay_position(x, y, overlay_size, viewport);
  menu.absolute_positioned(x, y, Some(Dimension::Px(width)), None)
}

/// The vertical extent of the menu's row `index` in its scroll content.
fn option_extent(menu: &LayoutResult, index: usize) -> Option<(f32, f32)> {
  let list = menu.children.first()?;
  let row = list.result.children.get(index)?;
  Some((row.offset.y, row.offset.y + row.result.size.height))
}

/// The line above a group that is not the first row of the menu.
fn separator_row(style: &SelectStyle) -> Node {
  let mut part = style.separator.clone();
  let thickness = part.min_height.take().unwrap_or(1.0);
  let padding = part.padding.take();
  let line_color = part.background.take();
  let mut line = Node::row(0.0, Alignment::Start, Vec::new())
    .width(Dimension::Pct(100.0))
    .height(Dimension::Px(thickness));
  if let Some(color) = line_color {
    line = line.background(color);
  }
  let mut row = Node::row(0.0, Alignment::Start, vec![line])
    .width(Dimension::Pct(100.0))
    .apply_select_part(&part);
  if let Some(padding) = padding {
    row = row.padding_custom(padding);
  }
  row.set_tag_name("SelectSeparator");
  row
}

/// The label over a group.
fn group_label_row(style: &SelectStyle, label: &str) -> Node {
  let part = &style.group_label;
  let text = part
    .text_node(label)
    .text_wrap(false)
    .text_overflow(TextOverflow::Elipsis)
    .min_width(0.0)
    .flex(1.0);
  let mut row = Node::row(0.0, Alignment::Center, vec![text])
    .width(Dimension::Pct(100.0))
    .apply_select_part(part);
  row.set_tag_name("SelectGroupLabel");
  row
}

fn option_row(
  state: &SelectState,
  style: &SelectStyle,
  index: usize,
  label: &str,
  count: usize,
  // The row as wide as what it holds and with the room of a mark, to be measured: not one of the menu's rows.
  probe: bool,
  measure: &mut dyn FnMut(&Node) -> LayoutResult,
) -> Node {
  let option = SelectOptionState {
    hovered: false,
    highlighted: state.highlighted() == Some(index),
    selected: state.is_selected(index),
    disabled: state.is_disabled(index),
  };
  let mut part = style.resolved_option(option);
  apply_select_menu_edge_radius(&mut part, &style.menu, index, count);

  let adornment = SelectAdornmentState {
    selected: option.selected,
    highlighted: option.highlighted && !option.disabled,
    disabled: option.disabled,
    in_field: false,
    text_color: part.text_color.clone(),
  };
  let (leading, trailing) = state.adornments(index);
  let [leading, trailing] =
    [leading, trailing].map(|build| build.map(|build| build(&adornment).into_node().flex_shrink(0.0)));
  // The hint goes at the end, after the trailing element, in its own style over the row's.
  let hint = state.hint(index).map(|hint| {
    let mut hint_part = part.clone();
    hint_part.merge_from(&style.option_hint);
    hint_part.text_node(&hint).text_wrap(false).flex_shrink(0.0)
  });
  let trailing = match (trailing, hint) {
    (Some(element), Some(hint)) => {
      Some(Node::row(style.option_adornment_gap, Alignment::Center, vec![element, hint]).flex_shrink(0.0))
    }
    (element, hint) => element.or(hint),
  };
  let slots = [leading, trailing];
  let content = option_content(&part, style, label, state.detail(index), slots, !probe, measure);
  let multiple = state.multiple();
  // A slot keeps the labels in line where the mark is before them. After them, in a single-select, only the chosen
  // row needs it: the others' labels may run to the row's end.
  let slot_kept =
    probe || !matches!(style.checkmark_position, SelectCheckmarkPosition::Trailing) || multiple || option.selected;
  let (gap, children) = if style.shows_checkmark(multiple) && slot_kept {
    let slot = checkmark_slot(style, &part, option.selected);
    let children = match style.checkmark_position {
      SelectCheckmarkPosition::Leading => vec![slot, content],
      SelectCheckmarkPosition::Trailing => vec![content, slot],
    };
    (style.checkmark_gap, children)
  } else {
    (SpacingValue::from(0.0), vec![content])
  };

  let mut row = Node::row(gap, Alignment::Center, children).apply_select_part(&part);
  if probe {
    return row;
  }
  row = row.width(Dimension::Pct(100.0));
  if part.min_height.is_none() {
    row = row.min_height(SELECT_OPTION_ROW_HEIGHT);
  }
  row.set_tag_name("SelectOption");
  let yes_no = |on: bool| Arc::from(if on { "true" } else { "false" });
  NodeUpdate::describe(&mut row, Arc::from("a11y_role"), Arc::from("option"));
  NodeUpdate::describe(&mut row, Arc::from("a11y_name"), Arc::from(label));
  NodeUpdate::describe(&mut row, Arc::from("a11y_selected"), yes_no(option.selected));
  if option.disabled {
    NodeUpdate::describe(&mut row, Arc::from("a11y_disabled"), yes_no(true));
    return row;
  }

  let commit_state = state.clone();
  row
    .events
    .on_mouse_down
    .push(EventHandler::new(move |event: &MouseEvent| {
      if event.button == MouseButton::Left {
        commit_state.commit(index);
      }
    }));
  let hovered = style.resolved_option(SelectOptionState {
    hovered: true,
    ..option
  });
  row.hovered_style(hover_style(&hovered))
}

/// An option's content: the label between its leading and trailing elements,
/// and the detail line under the label when the option has one.
///
/// The elements are centred on the label's line. Beside a detail line that
/// takes two rows: the elements with the label, then the detail between
/// spacers as wide as the elements, which `measure` sizes, so the detail
/// starts and ends where the label does.
fn option_content(
  part: &SelectPartStyle,
  style: &SelectStyle,
  label: &str,
  detail: Option<Arc<str>>,
  [leading, trailing]: [Option<Node>; 2],
  // Whether the text takes the room of its row; a row measured for its natural width does not grow.
  grows: bool,
  measure: &mut dyn FnMut(&Node) -> LayoutResult,
) -> Node {
  let grow = |node: Node| if grows { node.flex(1.0) } else { node };
  let full = |node: Node| if grows { node.width(Dimension::Pct(100.0)) } else { node };
  let line = |node: Node| {
    node
      .text_wrap(false)
      .text_overflow(TextOverflow::Elipsis)
      .min_width(0.0)
  };
  let label = line(part.text_node(label));
  let detail = detail.map(|detail| {
    let mut detail_part = part.clone();
    detail_part.merge_from(&style.option_detail);
    line(detail_part.text_node(&detail))
  });
  let adorned = leading.is_some() || trailing.is_some();
  let gap = style.option_adornment_gap;
  let around = |before: Option<Node>, text: Node, after: Option<Node>, align: Alignment| {
    let children = before.into_iter().chain([grow(text)]).chain(after).collect();
    Node::row(gap, align, children)
  };

  match (detail, adorned) {
    (None, false) => grow(label),
    (None, true) => grow(around(leading, label, trailing, Alignment::Center).min_width(0.0)),
    (Some(detail), false) => grow(Node::column(0.0, Alignment::Start, vec![full(label), full(detail)]).min_width(0.0)),
    (Some(detail), true) => {
      let mut spacer = |slot: &Option<Node>| {
        slot.as_ref().map(|element| {
          Node::row(0.0, Alignment::Start, Vec::new())
            .width(Dimension::Px(measure(element).size.width))
            .flex_shrink(0.0)
        })
      };
      let (before, after) = (spacer(&leading), spacer(&trailing));
      grow(
        Node::column(
          0.0,
          Alignment::Start,
          vec![
            full(around(leading, label, trailing, Alignment::Center)),
            full(around(before, detail, after, Alignment::Start)),
          ],
        )
        .min_width(0.0),
      )
    }
  }
}

/// The checkmark slot every option reserves, so labels line up whether or not
/// the option is selected.
fn checkmark_slot(style: &SelectStyle, part: &SelectPartStyle, selected: bool) -> Node {
  let mark = if selected {
    Some(&style.checkmark)
  } else {
    style.checkmark_unchecked.as_ref()
  };
  let icon = mark.map(|mark| {
    mark.build(
      part.text_style(),
      style.checkmark_size,
      style.checkmark_color.as_ref().or(part.text_color.as_ref()),
    )
  });
  let justify = match style.checkmark_position {
    SelectCheckmarkPosition::Leading => Justify::Start,
    SelectCheckmarkPosition::Trailing => Justify::End,
  };
  Node::row(0.0, Alignment::Center, icon.into_iter().collect())
    .justify(justify)
    .width(Dimension::Px(style.checkmark_slot_width()))
    .flex_shrink(0.0)
}

/// The pointer-hover paint of a row: fill, border and box shadow.
fn hover_style(hovered: &SelectPartStyle) -> Style {
  let mut style = Style::new();
  if let Some(background) = &hovered.background {
    style = style.background(background.clone());
  }
  if let Some(border) = &hovered.border {
    style = style.border_custom(border.clone());
  }
  if let Some(shadow) = &hovered.box_shadow {
    style = style.box_shadow(shadow.clone());
  }
  style
}

fn apply_select_menu_edge_radius(part: &mut SelectPartStyle, menu: &SelectPartStyle, index: usize, count: usize) {
  if count == 0 || part.border_radius.is_some() {
    return;
  }
  let Some(menu_radius) = menu.border_radius else {
    return;
  };
  let zero = RadiusValue::Px(0.0);
  let first = index == 0;
  let last = index + 1 == count;
  part.border_radius = Some(ThemedBorderRadius::new(
    if first { menu_radius.top_left } else { zero },
    if first { menu_radius.top_right } else { zero },
    if last { menu_radius.bottom_right } else { zero },
    if last { menu_radius.bottom_left } else { zero },
  ));
}

/// A key press on the focused element, as the select defaults read it.
#[derive(Clone, Copy)]
pub(super) struct SelectKey<'a> {
  pub(super) key: &'a str,
  pub(super) code: &'a str,
  pub(super) alt: bool,
  pub(super) ctrl: bool,
  pub(super) meta: bool,
}

impl SelectKey<'_> {
  fn is(&self, name: &str) -> bool {
    self.key == name || self.code == name
  }

  /// The character a printable key types, for type-ahead.
  fn typed_char(&self) -> Option<char> {
    if self.ctrl || self.alt || self.meta {
      return None;
    }
    let mut chars = self.key.chars();
    let ch = chars.next()?;
    (chars.next().is_none() && !ch.is_control()).then_some(ch)
  }
}

impl Tree {
  /// Keyboard defaults of a focused select. Closed: ArrowDown, ArrowUp
  /// (with or without Alt), Enter and Space open it with the selected option
  /// highlighted. Open: arrows move the highlight over enabled options,
  /// Home/End jump to the first/last one, typing jumps by label prefix, Enter
  /// or Space commits, and Escape or Tab close without a change. Focus stays
  /// on the select throughout, but for Tab, which goes on from it as it does
  /// from a closed select, as Tab in an open menu goes on from its trigger.
  pub(super) fn dispatch_select_key(&mut self, key: SelectKey<'_>) -> bool {
    let Some(focused) = self.focused_node else {
      return false;
    };
    let Some(root) = &self.root else {
      return false;
    };
    let Some(node) = find_node_by_id(root, focused) else {
      return false;
    };
    let NodeKind::Select { state } = node.node_kind() else {
      return false;
    };
    if state.is_open() && key.is("Tab") {
      // Closed, and the Tab is not taken: it goes on from the select, which is drawn closed whether or not it
      // moves the focus.
      state.set_open(false);
      self.needs_redraw = true;
      return false;
    }
    if state.is_open() {
      handle_open_select_key(state, key)
    } else {
      handle_closed_select_key(state, key)
    }
  }
}

fn handle_closed_select_key(state: &SelectState, key: SelectKey<'_>) -> bool {
  let opens = key.is("ArrowDown") || key.is("ArrowUp") || key.is("Enter") || key.key == " " || key.code == "Space";
  if opens {
    state.open_with_highlight();
  }
  opens
}

fn handle_open_select_key(state: &SelectState, key: SelectKey<'_>) -> bool {
  let now = Instant::now();
  if key.is("Escape") {
    state.set_open(false);
  } else if key.is("ArrowDown") {
    state.move_highlight(1);
  } else if key.is("ArrowUp") {
    state.move_highlight(-1);
  } else if key.is("Home") {
    state.highlight_edge(false);
  } else if key.is("End") {
    state.highlight_edge(true);
  } else if key.is("Enter") {
    state.activate();
  } else if key.key == " " || key.code == "Space" {
    if state.is_typing_ahead(now) {
      state.type_ahead(' ', now);
    } else {
      state.activate();
    }
  } else if let Some(ch) = key.typed_char() {
    state.type_ahead(ch, now);
  } else {
    return false;
  }
  true
}