forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

kit.rs1379 lines, 49.5 KiBHistoryRawDownload
1//! REDESIGN §1.5 / §6 -- the component kit every redesigned region is built
2//! from: one set of hover / pressed / focus / disabled rules (§1.5), three
3//! button styles, toggle, segmented control, switch, scrub-number field,
4//! section head and keycap.
5//!
6//! These sit beside the legacy helpers in `ui::widgets` (`control`, `tip_*`,
7//! `focus_ring`), which stay for the existing call sites; later phases move
8//! regions over to this module and then retire the legacy ones.
9//!
10//! Rules every component here keeps:
11//! * **No layout shift.** Sizes are fixed by the style; hover, press, focus
12//! and "on" change colour only (the one border a component has is always
13//! there, only its colour changes).
14//! * **Colours come from [`theme::tokens`]**, never a literal.
15//! * **State is overridable.** Each builder takes an optional [`Look`] that
16//! forces a visual state, which is how the component gallery paints every
17//! state at once and how a keyboard-focused control (whose handle the
18//! caller owns) is drawn.
19//! * Builders return a plain `Stateful<Div>`: chain `.on_click(..)`,
20//! `.tooltip(..)`, drag handlers on the result. A disabled component draws
21//! dimmed with a not-allowed cursor and should be given no handler.
22
23use crate::layout::redesign as r;
24use crate::ui::icons::{Icon, IconSize};
25use crate::ui::theme::{self, tokens};
26use crate::ui::type_scale::{self, Typeset};
27use crate::*;
28use gpui::{BoxShadow, Hsla, ScrollHandle, SharedString, Stateful, hsla};
29use std::cell::RefCell;
30use std::rc::Rc;
31use std::sync::atomic::{AtomicBool, Ordering};
32
33fn c(x: u32) -> Hsla {
34 rgb(x).into()
35}
36
37fn ca(x: u32) -> Hsla {
38 rgba(x).into()
39}
40
41/// A forced visual state (see the module doc); `None` means live (pointer-driven).
42/// `Focus` keeps the rest fill and adds the accent ring; the others pin the
43/// fill hover or press would give.
44#[derive(Clone, Copy, PartialEq, Eq, Debug)]
45pub enum Look {
46 Hover,
47 Pressed,
48 Focus,
49}
50
51/// A control's three fills: at rest, under the pointer, pressed.
52#[derive(Clone, Copy, Debug)]
53pub struct Fills {
54 pub rest: Hsla,
55 pub hover: Hsla,
56 pub press: Hsla,
57}
58
59impl Fills {
60 /// Transparent at rest, a white wash (6% / 10%) on hover / press: ghost
61 /// buttons, toolbar buttons, menu rows, dock tabs.
62 pub fn ghost() -> Self {
63 Self {
64 rest: hsla(0., 0., 0., 0.),
65 hover: ca(theme::WASH_HOVER),
66 press: ca(theme::WASH_PRESS),
67 }
68 }
69
70 /// `e2` at rest, `e3` hover, `e4` pressed: secondary buttons, fields.
71 pub fn solid() -> Self {
72 let t = tokens();
73 Self { rest: c(t.e2), hover: c(t.e3), press: c(t.e4) }
74 }
75
76 /// A toggle that is on: `e3`, one step up under the pointer.
77 pub fn on() -> Self {
78 let t = tokens();
79 Self { rest: c(t.e3), hover: c(t.e4), press: c(theme::mix(t.e4, t.ink1, 0.06)) }
80 }
81
82 /// The primary button: `accent_fill`, darker on press.
83 pub fn primary() -> Self {
84 let t = tokens();
85 Self {
86 rest: c(t.accent_fill),
87 hover: c(t.accent_press),
88 press: c(theme::mix(t.accent_fill, 0x000000, 0.15)),
89 }
90 }
91}
92
93/// The keyboard-focus ring (§1.5): the control's own 1px border turns `accent`.
94/// Every component here carries a 1px border that is transparent at rest, so
95/// focus never moves a neighbour. (A spread shadow was tried first: gpui
96/// paints it *under* the element, so a transparent ghost button filled solid
97/// accent; and the spec's 2px/1px-offset needs the parent surface colour.)
98/// Needs the element to hold a gpui focus handle to show live; `Look::Focus`
99/// forces it.
100pub fn focus_ring_accent<E: InteractiveElement + Styled>(el: E) -> E {
101 // The ring is for the keyboard: a click also focuses a control, and must not light it.
102 el.focus(|s| if KBD_RING.load(Ordering::Relaxed) { s.border_color(c(tokens().accent)) } else { s })
103}
104
105/// Whether the last input was the keyboard (Tab in a dialog). Set on Tab, cleared by any
106/// mouse press, read when a focused control paints its ring.
107static KBD_RING: AtomicBool = AtomicBool::new(false);
108
109pub fn set_kbd_ring(on: bool) {
110 KBD_RING.store(on, Ordering::Relaxed);
111}
112
113thread_local! {
114 /// The focus handles a dialog's controls take while it is being built, and how many are used.
115 static TAB_POOL: RefCell<(Option<Vec<FocusHandle>>, usize)> = const { RefCell::new((None, 0)) };
116}
117
118/// The open [`choice_list`] of the last frame, for the arrow keys: which one, how many rows,
119/// the highlighted row, and the pick handler.
120type PickFn = Rc<dyn Fn(usize, &mut Window, &mut App)>;
121
122#[derive(Default)]
123struct OpenList {
124 id: &'static str,
125 len: usize,
126 hi: usize,
127 pick: Option<PickFn>,
128}
129
130thread_local! {
131 static OPEN_LIST: RefCell<OpenList> = RefCell::new(OpenList::default());
132 /// The scroll position of each choice list by its id, so the arrow keys can bring the
133 /// highlighted row into view.
134 static LIST_SCROLL: RefCell<std::collections::HashMap<&'static str, ScrollHandle>> = RefCell::new(Default::default());
135}
136
137/// The tallest a [`choice_list`] gets before it scrolls: a long list (a font list, say) stays on
138/// the window and its rows are reached with the wheel or the arrow keys.
139pub const LIST_MAX_H: f32 = 320.;
140
141/// How tall a [`choice_list`] of `rows` rows is: its rows and padding, capped at [`LIST_MAX_H`].
142pub fn list_height(rows: usize) -> f32 {
143 (rows as f32 * crate::layout::MENU_ROW_H + 2. * crate::layout::MENU_PAD).min(LIST_MAX_H)
144}
145
146/// Whether the list of `rows` rows for the dropdown field `field` opens above the field, because
147/// there is no room for it below on the window. Only the `top` or `bottom` offset of the list
148/// changes: the list stays 2px clear of the field, below it or above it.
149pub fn list_opens_above(field: &'static str, rows: usize) -> bool {
150 crate::ui::anchor::opens_above(field, list_height(rows))
151}
152
153/// The scroll handle of the list `id`.
154fn list_scroll(id: &'static str) -> ScrollHandle {
155 LIST_SCROLL.with(|m| m.borrow_mut().entry(id).or_default().clone())
156}
157
158/// Start a frame: no handle is used yet, and no list is known to be open until one draws.
159/// Call once before any [`tab_scope`].
160pub fn tab_frame_reset() {
161 TAB_POOL.with(|p| p.borrow_mut().1 = 0);
162 OPEN_LIST.with(|l| {
163 let mut l = l.borrow_mut();
164 if l.pick.take().is_none() {
165 l.id = "";
166 }
167 });
168}
169
170/// Up, Down and Enter for the [`choice_list`] that is open: Up and Down move its highlighted
171/// row (wrapping), Enter picks it. `true` when the key was the list's (the caller repaints).
172pub fn list_nav(key: &str, window: &mut Window, cx: &mut App) -> bool {
173 let (id, len, hi, pick) = OPEN_LIST.with(|l| {
174 let l = l.borrow();
175 (l.id, l.len, l.hi, l.pick.clone())
176 });
177 let Some(pick) = pick else { return false };
178 if len == 0 {
179 return false;
180 }
181 match key {
182 "up" | "down" => {
183 let to = if key == "down" { (hi + 1) % len } else { (hi + len - 1) % len };
184 OPEN_LIST.with(|l| l.borrow_mut().hi = to);
185 list_scroll(id).scroll_to_item(to);
186 true
187 }
188 "enter" => {
189 pick(hi, window, cx);
190 true
191 }
192 _ => false,
193 }
194}
195
196/// Runs `build`, giving every kit control made inside it (`states`) a tab stop from `pool`, in
197/// build order. Controls built outside a scope stay out of the Tab order, so a dialog's Tab
198/// never walks the window behind it.
199pub fn tab_scope<R>(pool: &[FocusHandle], build: impl FnOnce() -> R) -> R {
200 TAB_POOL.with(|p| p.borrow_mut().0 = Some(pool.to_vec()));
201 let out = build();
202 TAB_POOL.with(|p| p.borrow_mut().0 = None);
203 out
204}
205
206/// A row-like control that is not a kit button (a settings row, a chip, a swatch): a tab stop
207/// inside a [`tab_scope`], lit with an accent wash while the keyboard is on it.
208pub fn kbd_stop<E: InteractiveElement + Styled>(el: E) -> E {
209 tab_stop(el).focus(|s| if KBD_RING.load(Ordering::Relaxed) { s.bg(c(tokens().accent).opacity(0.22)) } else { s })
210}
211
212fn tab_stop<E: InteractiveElement>(el: E) -> E {
213 let h = TAB_POOL.with(|p| {
214 let mut p = p.borrow_mut();
215 let at = p.1;
216 let h = p.0.as_ref().and_then(|pool| pool.get(at).cloned());
217 if h.is_some() {
218 p.1 += 1;
219 }
220 h
221 });
222 match h {
223 Some(h) => el.track_focus(&h),
224 None => el,
225 }
226}
227
228/// Applies the §1.5 state table to an element (which must carry a 1px border,
229/// see [`focus_ring_accent`]): the fill for each state, the focus border, the
230/// pointer, and the disabled dimming. `forced` pins a state instead of
231/// waiting for the pointer.
232pub fn states<E>(el: E, fills: Fills, enabled: bool, forced: Option<Look>) -> E
233where
234 E: StatefulInteractiveElement + Styled,
235{
236 if !enabled {
237 // Dimmed but still legible: a disabled label must stay readable (it often carries the reason).
238 return el.bg(fills.rest).opacity(0.6).cursor_not_allowed();
239 }
240 match forced {
241 Some(Look::Hover) => el.bg(fills.hover).cursor_pointer(),
242 Some(Look::Pressed) => el.bg(fills.press).cursor_pointer(),
243 Some(Look::Focus) => el.bg(fills.rest).border_color(c(tokens().accent)).cursor_pointer(),
244 None => focus_ring_accent(
245 tab_stop(el).bg(fills.rest)
246 .cursor_pointer()
247 .hover(move |s| s.bg(fills.hover))
248 .active(move |s| s.bg(fills.press)),
249 ),
250 }
251}
252
253/// The three button styles (§1.5). Exactly these.
254#[derive(Clone, Copy, PartialEq, Eq, Debug)]
255pub enum ButtonStyle {
256 /// `accent_fill`, dark `on_accent` text; one per surface (Export, Apply, Import).
257 Primary,
258 /// `e2` fill, `line` border, `ink1` text.
259 Secondary,
260 /// Transparent: toolbars, inspector header actions.
261 Ghost,
262}
263
264/// Control heights (§1.2): 24 small, 28 default, 32 toolbar / primary, 36 hero.
265#[derive(Clone, Copy, PartialEq, Eq, Debug)]
266pub enum ButtonSize {
267 Small,
268 Default,
269 Large,
270 Hero,
271}
272
273impl ButtonSize {
274 pub const fn height(self) -> f32 {
275 match self {
276 ButtonSize::Small => r::CONTROL_S,
277 ButtonSize::Default => r::CONTROL_M,
278 ButtonSize::Large => r::CONTROL_L,
279 ButtonSize::Hero => r::CONTROL_XL,
280 }
281 }
282
283 fn pad(self) -> f32 {
284 match self {
285 ButtonSize::Small => 8.,
286 ButtonSize::Default => 12.,
287 ButtonSize::Large => 14.,
288 ButtonSize::Hero => 16.,
289 }
290 }
291
292 fn icon(self) -> IconSize {
293 match self {
294 ButtonSize::Small | ButtonSize::Default => IconSize::Inline,
295 ButtonSize::Large | ButtonSize::Hero => IconSize::Toolbar,
296 }
297 }
298
299 fn text(self) -> type_scale::TypeStyle {
300 match self {
301 ButtonSize::Small => type_scale::caption_strong(),
302 ButtonSize::Default | ButtonSize::Large => type_scale::body_strong(),
303 ButtonSize::Hero => type_scale::emph(),
304 }
305 }
306}
307
308/// A button, icon button or toggle, depending on what it is given:
309/// a label, an icon, both, and (for the ghost style) `.on(true)`.
310///
311/// ```ignore
312/// Button::new("export").label("Export").style(ButtonStyle::Primary).build()
313/// .on_click(|_, _, cx| ..)
314/// Button::new("snap").icon(Icon::Magnet).label("Snap").size(ButtonSize::Large).on(snap).build()
315/// Button::new("play").icon(Icon::Play).size(ButtonSize::Large).build() // icon-only: square
316/// ```
317pub struct Button {
318 id: &'static str,
319 label: Option<SharedString>,
320 icon: Option<Icon>,
321 style: ButtonStyle,
322 size: ButtonSize,
323 on: bool,
324 enabled: bool,
325 look: Option<Look>,
326 min_w: f32,
327}
328
329impl Button {
330 pub fn new(id: &'static str) -> Self {
331 Self {
332 id,
333 label: None,
334 icon: None,
335 style: ButtonStyle::Secondary,
336 size: ButtonSize::Default,
337 on: false,
338 enabled: true,
339 look: None,
340 min_w: 0.,
341 }
342 }
343 pub fn label(mut self, label: impl Into<SharedString>) -> Self {
344 self.label = Some(label.into());
345 self
346 }
347 pub fn icon(mut self, icon: Icon) -> Self {
348 self.icon = Some(icon);
349 self
350 }
351 pub fn style(mut self, style: ButtonStyle) -> Self {
352 self.style = style;
353 self
354 }
355 pub fn size(mut self, size: ButtonSize) -> Self {
356 self.size = size;
357 self
358 }
359 /// A toggle that is on: `e3` fill, `accent` icon and label. Ghost style only.
360 pub fn on(mut self, on: bool) -> Self {
361 self.on = on;
362 self
363 }
364 pub fn enabled(mut self, enabled: bool) -> Self {
365 self.enabled = enabled;
366 self
367 }
368 /// Force a visual state (gallery, or a keyboard-focused control).
369 pub fn look(mut self, look: Look) -> Self {
370 self.look = Some(look);
371 self
372 }
373 /// A width floor, for a label that changes ("Export" / "Cancel") so its
374 /// neighbours do not move.
375 pub fn min_w(mut self, w: f32) -> Self {
376 self.min_w = w;
377 self
378 }
379
380 pub fn build(self) -> Stateful<Div> {
381 let t = tokens();
382 let h = self.size.height();
383 let on = self.on && self.style == ButtonStyle::Ghost;
384 let fills = match (self.style, on) {
385 (ButtonStyle::Primary, _) => Fills::primary(),
386 (ButtonStyle::Secondary, _) => Fills::solid(),
387 (ButtonStyle::Ghost, true) => Fills::on(),
388 (ButtonStyle::Ghost, false) => Fills::ghost(),
389 };
390 // Text and icon colour: rest -> hover/press -> on -> disabled.
391 let (rest_ink, hover_ink) = match (self.style, on) {
392 (ButtonStyle::Primary, _) => (t.on_accent, t.on_accent),
393 (ButtonStyle::Secondary, _) => (t.ink1, t.ink1),
394 (_, true) => (t.accent, t.accent),
395 (ButtonStyle::Ghost, false) => (t.ink2, t.ink1),
396 };
397 let forced_ink = match self.look {
398 Some(Look::Hover | Look::Pressed) => hover_ink,
399 _ => rest_ink,
400 };
401 let ink = if self.enabled { forced_ink } else { t.ink3 };
402 let group: SharedString = format!("btn-{}", self.id).into();
403 let square = self.label.is_none();
404 let mut el = div()
405 .id(self.id)
406 .group(group.clone())
407 .flex_none()
408 .h(px(h))
409 .flex()
410 .items_center()
411 .justify_center()
412 .gap(px(6.))
413 .rounded(px(r::R_CONTROL))
414 .border_1()
415 .border_color(match self.style {
416 ButtonStyle::Secondary => ca(t.line),
417 _ => hsla(0., 0., 0., 0.),
418 })
419 .text_color(c(ink))
420 .type_style(self.size.text());
421 el = if square { el.w(px(h)) } else { el.px(px(self.size.pad())) };
422 if self.min_w > 0. {
423 el = el.min_w(px(self.min_w));
424 }
425 if let Some(icon) = self.icon {
426 let mut glyph = icon.el(self.size.icon(), ink);
427 if self.enabled && self.look.is_none() && hover_ink != rest_ink {
428 glyph = glyph.group_hover(group.clone(), move |s| s.text_color(c(hover_ink)));
429 }
430 el = el.child(glyph);
431 }
432 if let Some(label) = self.label {
433 el = el.child(label);
434 }
435 let mut el = states(el, fills, self.enabled, self.look);
436 if self.style == ButtonStyle::Primary && self.enabled && self.look.is_none() {
437 // An accent ring on an accent fill is invisible: the primary's ring is the ink.
438 el = el.focus(|s| if KBD_RING.load(Ordering::Relaxed) { s.border_color(c(t.ink1)) } else { s });
439 }
440 if self.enabled && self.look.is_none() && hover_ink != rest_ink {
441 el = el.hover(move |s| s.text_color(c(hover_ink)));
442 }
443 el
444 }
445}
446
447/// One entry of a [`segmented`] control.
448pub struct Segment {
449 pub label: SharedString,
450 pub icon: Option<Icon>,
451 /// This pill alone cannot be chosen: drawn in `ink3` (still readable), no hover, no click.
452 pub disabled: bool,
453}
454
455impl Segment {
456 /// Marks this pill as unavailable while the others stay live.
457 #[allow(dead_code)] // no pill is disabled today; the look and the guard in `segmented` stay ready
458 pub fn disabled(mut self, disabled: bool) -> Self {
459 self.disabled = disabled;
460 self
461 }
462
463 pub fn text(label: impl Into<SharedString>) -> Self {
464 Self { label: label.into(), icon: None, disabled: false }
465 }
466}
467
468/// The segmented control (§1.5): an `e2` track, the selected pill `e3`.
469/// 28px tall, every pill the same weight so selecting never reflows the row.
470/// `on_select` gets the index of the pill clicked. `forced` pins one pill's
471/// state (gallery). This replaces every "Off On" text row.
472pub fn segmented(
473 id: &'static str,
474 items: &[Segment],
475 selected: usize,
476 enabled: bool,
477 forced: Option<(usize, Look)>,
478 on_select: impl Fn(usize, &mut Window, &mut App) + Clone + 'static,
479) -> Div {
480 segmented_in(SegLayout::Hug, id, items, selected, enabled, forced, on_select)
481}
482
483/// [`segmented`] that fills the width it is given with every pill the same
484/// width (`flex_1`), for rows of a few short options ("Left Centre Right")
485/// where a ragged track looks unfinished. Put it in a parent with a width.
486pub fn segmented_equal(
487 id: &'static str,
488 items: &[Segment],
489 selected: usize,
490 enabled: bool,
491 forced: Option<(usize, Look)>,
492 on_select: impl Fn(usize, &mut Window, &mut App) + Clone + 'static,
493) -> Div {
494 segmented_in(SegLayout::Equal, id, items, selected, enabled, forced, on_select)
495}
496
497/// [`segmented`] for more options than fit one row of a narrow panel: the
498/// track takes the parent's width and the pills wrap onto further lines, so a
499/// label is never clipped. The track grows by a pill row per wrap (so give it
500/// room, or reserve the height of the wrapped case).
501pub fn segmented_wrap(
502 id: &'static str,
503 items: &[Segment],
504 selected: usize,
505 enabled: bool,
506 forced: Option<(usize, Look)>,
507 on_select: impl Fn(usize, &mut Window, &mut App) + Clone + 'static,
508) -> Div {
509 segmented_in(SegLayout::Wrap, id, items, selected, enabled, forced, on_select)
510}
511
512/// How a segmented track sizes itself.
513#[derive(Clone, Copy, PartialEq, Eq)]
514enum SegLayout {
515 /// As wide as its pills.
516 Hug,
517 /// The parent's width, pills of equal width.
518 Equal,
519 /// The parent's width, pills wrap onto more lines.
520 Wrap,
521}
522
523fn segmented_in(
524 layout: SegLayout,
525 id: &'static str,
526 items: &[Segment],
527 selected: usize,
528 enabled: bool,
529 forced: Option<(usize, Look)>,
530 on_select: impl Fn(usize, &mut Window, &mut App) + Clone + 'static,
531) -> Div {
532 let t = tokens();
533 let mut track = div()
534 .flex()
535 .items_center()
536 .p(px(2.))
537 .gap(px(2.))
538 .rounded(px(r::R_CONTROL))
539 .bg(c(t.e2))
540 .when(!enabled, |d| d.opacity(0.4));
541 track = match layout {
542 SegLayout::Hug => track.flex_none().h(px(r::CONTROL_M)),
543 SegLayout::Equal => track.w_full().h(px(r::CONTROL_M)),
544 SegLayout::Wrap => track.w_full().min_h(px(r::CONTROL_M)).flex_wrap(),
545 };
546 for (i, item) in items.iter().enumerate() {
547 let is_sel = i == selected;
548 let look = forced.filter(|(f, _)| *f == i).map(|(_, l)| l);
549 let fills = if is_sel {
550 Fills { rest: c(t.e3), hover: c(t.e3), press: c(t.e4) }
551 } else {
552 Fills::ghost()
553 };
554 let live = enabled && !item.disabled;
555 let ink = match (is_sel, look) {
556 _ if item.disabled => t.ink3,
557 (true, _) => t.ink1,
558 (false, Some(Look::Hover | Look::Pressed)) => t.ink1,
559 (false, _) => t.ink2,
560 };
561 let mut pill = div()
562 .id((id, i))
563 .h(px(r::CONTROL_S))
564 .px(px(10.))
565 .flex()
566 .items_center()
567 .whitespace_nowrap()
568 .gap(px(6.))
569 .rounded(px(r::R_CLIP))
570 .border_1()
571 .border_color(hsla(0., 0., 0., 0.))
572 .type_style(type_scale::body_strong())
573 .text_color(c(if enabled { ink } else { t.ink4 }));
574 pill = match layout {
575 SegLayout::Equal => pill.flex_1().min_w(px(0.)).justify_center(),
576 _ => pill.flex_none(),
577 };
578 if let Some(icon) = item.icon {
579 pill = pill.child(icon.el(IconSize::Inline, if enabled { ink } else { t.ink4 }));
580 }
581 if !item.label.is_empty() {
582 pill = pill.child(item.label.clone());
583 }
584 let mut pill = if item.disabled { pill.cursor_not_allowed() } else { states(pill, fills, enabled, look) };
585 if live && look.is_none() && !is_sel {
586 pill = pill.hover(move |s| s.bg(fills.hover).text_color(c(tokens().ink1)));
587 }
588 if live {
589 let on_select = on_select.clone();
590 pill = pill.on_click(move |_, window, cx| on_select(i, window, cx));
591 }
592 track = track.child(pill);
593 }
594 track
595}
596
597/// The switch (§1.5): a 32x18 track and a 12px knob. On is `accent_fill` with
598/// a dark knob; off is `e3` with an `ink2` knob. The knob is absolutely
599/// placed, so the control's box is the same either way.
600pub fn switch(id: impl Into<gpui::ElementId>, on: bool, enabled: bool, look: Option<Look>) -> Stateful<Div> {
601 let t = tokens();
602 let fills = if on {
603 Fills::primary()
604 } else {
605 Fills { rest: c(t.e3), hover: c(t.e4), press: c(theme::mix(t.e4, t.ink1, 0.06)) }
606 };
607 let knob = div()
608 .absolute()
609 .top(px(2.))
610 .left(px(if on { 16. } else { 2. }))
611 .size(px(12.))
612 .rounded_full()
613 .bg(c(if on { t.on_accent } else { t.ink2 }));
614 states(
615 div()
616 .id(id)
617 .flex_none()
618 .relative()
619 .w(px(32.))
620 .h(px(18.))
621 .rounded_full()
622 .border_1()
623 .border_color(if on { hsla(0., 0., 0., 0.) } else { ca(t.line_hi) })
624 .child(knob),
625 fills,
626 enabled,
627 look,
628 )
629}
630
631/// Which state a [`scrub_field`] is in.
632#[derive(Clone, Copy, PartialEq, Eq, Debug)]
633pub enum ScrubLook {
634 Hover,
635 /// The user is typing a value: 1px `accent` border and a caret.
636 Typing,
637}
638
639/// The scrub-number field (§6): 24px, `e2`; hover `e3` with a `col-resize`
640/// cursor; typing shows a 1px `accent` border and a caret. The value is
641/// `caption` with tabular figures, the unit `ink3`. The 1px border is always
642/// there (transparent unless typing), so focusing never shifts the box.
643/// Dragging and typing are the caller's: attach `on_drag` / `on_click` to the
644/// result.
645pub fn scrub_field(
646 id: &'static str,
647 w: f32,
648 value: impl Into<SharedString>,
649 unit: Option<&'static str>,
650 enabled: bool,
651 look: Option<ScrubLook>,
652) -> Stateful<Div> {
653 let t = tokens();
654 let typing = look == Some(ScrubLook::Typing);
655 let fills = Fills::solid();
656 let mut el = div()
657 .id(id)
658 .flex_none()
659 .w(px(w))
660 .h(px(r::CONTROL_S))
661 .px(px(8.))
662 .flex()
663 .items_center()
664 .gap(px(2.))
665 .rounded(px(r::R_CONTROL))
666 .border_1()
667 .border_color(if typing { c(t.accent) } else { hsla(0., 0., 0., 0.) })
668 .type_style(type_scale::caption())
669 .text_color(c(if enabled { t.ink1 } else { t.ink4 }))
670 .child(value.into());
671 if typing {
672 el = el.child(div().w(px(1.)).h(px(14.)).bg(c(t.accent)));
673 }
674 if let Some(unit) = unit {
675 el = el.child(div().text_color(c(t.ink3)).child(unit));
676 }
677 if !enabled {
678 // Dimmed but still legible: a disabled label must stay readable (it often carries the reason).
679 return el.bg(fills.rest).opacity(0.6).cursor_not_allowed();
680 }
681 match look {
682 Some(ScrubLook::Hover) => el.bg(fills.hover).cursor(CursorStyle::ResizeLeftRight),
683 Some(ScrubLook::Typing) => el.bg(fills.rest),
684 _ => el.bg(fills.rest).hover(move |s| s.bg(fills.hover)).cursor(CursorStyle::ResizeLeftRight),
685 }
686}
687
688/// An inspector section head (§1.1 `section`): 12px Inter 600, sentence case,
689/// `ink2`, in a 24px row; `trailing` (a reset button, a chevron) sits at the right.
690pub fn section_head(text: impl Into<SharedString>, trailing: Option<AnyElement>) -> Div {
691 div()
692 .flex_none()
693 .h(px(r::CONTROL_S))
694 .flex()
695 .items_center()
696 .justify_between()
697 .type_style(type_scale::section())
698 .text_color(c(tokens().ink2))
699 .child(text.into())
700 .children(trailing)
701}
702
703/// A key shown in a tooltip, menu or sheet (§5 rule 1: nowhere else): `e4`
704/// plate, `line_hi` border, `caption` text.
705pub fn keycap(text: impl Into<SharedString>) -> Div {
706 let t = tokens();
707 div()
708 .flex_none()
709 .h(px(18.))
710 .min_w(px(18.))
711 .px(px(5.))
712 .flex()
713 .items_center()
714 .justify_center()
715 .rounded(px(r::R_CONTROL))
716 .border_1()
717 .border_color(ca(t.line_hi))
718 .bg(c(t.e4))
719 .type_style(type_scale::caption())
720 .text_color(c(t.ink2))
721 .child(text.into())
722}
723
724/// The one popup plate (§1.6): `e3`, 1px `line_hi` border, radius 6 (8 for
725/// sheets and the palette), soft shadow. Menus, dropdowns, tooltips and toasts
726/// all start from this.
727pub fn plate(radius: f32) -> Div {
728 let t = tokens();
729 div()
730 .bg(c(t.e3))
731 .border_1()
732 .border_color(ca(t.line_hi))
733 .rounded(px(radius))
734 .shadow(vec![BoxShadow {
735 color: ca(theme::PLATE_SHADOW),
736 offset: point(px(0.), px(8.)),
737 blur_radius: px(24.),
738 spread_radius: px(0.),
739 }])
740}
741
742// ---------------------------------------------------------------------------
743// Card components: what the property cards, the sheets and the dialogs are
744// built from. Each takes its handler as an argument and attaches it only when
745// the control is live, so a disabled one cannot be driven by a stray click.
746// ---------------------------------------------------------------------------
747
748/// A switch row: the label (and, under it, an optional one-line description in
749/// `ink3`) on the left, the [`switch`] on the right, the whole row one click
750/// target. `off_why` disables it: the row dims, the cursor says not-allowed, a
751/// hover tooltip gives the reason, and `on_toggle` is never attached, so the
752/// row ignores input.
753///
754/// ```ignore
755/// switch_row("loop", "Loop playback", Some("Start again at the end".into()), on, None,
756/// move |_, cx| entity.update(cx, |p, cx| p.toggle_loop(cx)))
757/// ```
758pub fn switch_row(
759 id: &'static str,
760 label: impl Into<SharedString>,
761 description: Option<SharedString>,
762 on: bool,
763 off_why: Option<&str>,
764 on_toggle: impl Fn(&mut Window, &mut App) + 'static,
765) -> Stateful<Div> {
766 let t = tokens();
767 let label: SharedString = label.into();
768 let enabled = off_why.is_none();
769 let row = div()
770 .id(id)
771 .w_full()
772 .flex_none()
773 .min_h(px(r::CONTROL_M))
774 .py(px(2.))
775 .flex()
776 .items_center()
777 .justify_between()
778 .gap(px(12.))
779 .child(
780 div()
781 .flex_1()
782 .min_w(px(0.))
783 .flex()
784 .flex_col()
785 .child(
786 div()
787 .type_style(type_scale::body())
788 .text_color(c(if enabled { t.ink1 } else { t.ink4 }))
789 .child(label.clone()),
790 )
791 .children(description.map(|d| {
792 div().type_style(type_scale::caption()).text_color(c(if enabled { t.ink3 } else { t.ink4 })).child(d)
793 })),
794 )
795 .child(switch((id, 1usize), on, enabled, None));
796 match off_why {
797 Some(why) => row
798 .cursor_not_allowed()
799 .tooltip(crate::ui::widgets::overlay_tip_hover(&label, "", Some(why))),
800 None => row.cursor_pointer().on_click(move |_, window, cx| on_toggle(window, cx)),
801 }
802}
803
804/// The reset slot: a 24px square that is *always* in the layout. It holds the
805/// ghost reset icon (tooltip "Reset to default") while `show`, and is empty
806/// otherwise, so a value that changes never nudges its neighbours. The click is
807/// attached only while shown.
808pub fn reset_slot(id: &'static str, show: bool, on_reset: impl Fn(&mut Window, &mut App) + 'static) -> Div {
809 let slot = div().flex_none().size(px(r::CONTROL_S)).flex().items_center().justify_center();
810 if !show {
811 return slot;
812 }
813 slot.child(
814 Button::new(id)
815 .icon(Icon::RotateCcw)
816 .style(ButtonStyle::Ghost)
817 .size(ButtonSize::Small)
818 .build()
819 .tooltip(crate::ui::widgets::overlay_tip_hover("Reset to default", "", None))
820 .on_click(move |_, window, cx| on_reset(window, cx)),
821 )
822}
823
824/// A value pill: a fixed-width `e2` box with the value right-aligned in tabular
825/// `caption` (`ink1` once changed from the default, `ink2` at the default) and
826/// the [`reset_slot`] beside it. Width and slot never change, so editing a
827/// value moves nothing.
828pub fn value_pill(
829 id: &'static str,
830 w: f32,
831 value: impl Into<SharedString>,
832 unit: Option<&'static str>,
833 changed: bool,
834 on_reset: impl Fn(&mut Window, &mut App) + 'static,
835) -> Div {
836 let t = tokens();
837 div()
838 .flex_none()
839 .flex()
840 .items_center()
841 .gap(px(2.))
842 .child(
843 div()
844 .flex_none()
845 .w(px(w))
846 .h(px(r::CONTROL_S))
847 .px(px(8.))
848 .flex()
849 .items_center()
850 .justify_end()
851 .gap(px(2.))
852 .rounded(px(r::R_CONTROL))
853 .bg(c(t.e2))
854 .whitespace_nowrap()
855 .type_style(type_scale::caption())
856 .text_color(c(if changed { t.ink1 } else { t.ink2 }))
857 .child(value.into())
858 .children(unit.map(|u| div().text_color(c(t.ink3)).child(u))),
859 )
860 .child(reset_slot(id, changed, on_reset))
861}
862
863/// A number being typed into a [`number_field`]: the buffer, with the first
864/// keystroke replacing the old text (it opens fully selected). Wire it like
865/// this: a click (or double-click) on the field makes
866/// `NumberEdit::begin(&shown)`; each key goes to [`NumberEdit::key`]; on
867/// `Commit` call [`NumberEdit::commit`] and write the value, on `Cancel` just
868/// drop the edit. Dragging the field is [`scrub_value`].
869#[derive(Clone, Debug, PartialEq, Eq)]
870pub struct NumberEdit {
871 field: crate::player::text_field::TextField,
872}
873
874impl NumberEdit {
875 /// Opens on `shown` (the text the field displayed), all selected.
876 pub fn begin(shown: &str) -> Self {
877 Self { field: crate::player::text_field::TextField::selected(shown) }
878 }
879
880 /// The buffer, for [`number_field`]'s `editing`.
881 pub fn text(&self) -> &str {
882 &self.field.text
883 }
884
885 /// One key: digits, `.`, `,` and `-` are typed (anything else is ignored),
886 /// backspace deletes, Enter commits, Esc cancels.
887 #[allow(dead_code, reason = "the cards adopt it next")]
888 pub fn key(&mut self, key: &str, ctrl: bool, alt: bool, key_char: Option<&str>) -> crate::player::text_field::FieldKey {
889 let typed: Option<String> = key_char
890 .map(|k| k.chars().filter(|c| c.is_ascii_digit() || matches!(c, '.' | ',' | '-')).collect::<String>())
891 .filter(|k| !k.is_empty());
892 // A letter or symbol that is not part of a number changes nothing.
893 if typed.is_none() && key_char.is_some() && !matches!(key, "enter" | "escape" | "backspace") {
894 return crate::player::text_field::FieldKey::Edited;
895 }
896 self.field.key(key, ctrl, alt, typed.as_deref(), 12)
897 }
898
899 /// The typed number clamped to `min..=max`, or `None` when the buffer is
900 /// not a number (the caller then keeps the old value). `,` reads as `.`.
901 #[allow(dead_code, reason = "the cards adopt it next")]
902 pub fn commit(&self, min: f64, max: f64) -> Option<f64> {
903 let v: f64 = self.field.text.trim().replace(',', ".").parse().ok()?;
904 v.is_finite().then(|| v.clamp(min, max))
905 }
906}
907
908/// The value after dragging a [`number_field`] `dx` pixels from where the drag
909/// began at `start`: `per_px` units a pixel (a tenth of that with `fine`, which
910/// callers wire to Shift), clamped to `min..=max`.
911#[allow(dead_code, reason = "the cards adopt it next")]
912pub fn scrub_value(start: f64, dx: f32, per_px: f64, fine: bool, min: f64, max: f64) -> f64 {
913 let per = if fine { per_px / 10. } else { per_px };
914 (start + f64::from(dx) * per).clamp(min, max)
915}
916
917/// The number field (§6): a [`scrub_field`] that also shows what is being
918/// typed. `editing` is the [`NumberEdit`] buffer while the user types (1px
919/// `accent` border, caret), `None` at rest, where the field drags to scrub
920/// (`col-resize` cursor). Compose with a [`reset_slot`] to its right for the
921/// reset-to-default affordance. Drag, click and key wiring are the caller's.
922pub fn number_field(
923 id: &'static str,
924 w: f32,
925 value: impl Into<SharedString>,
926 unit: Option<&'static str>,
927 editing: Option<&NumberEdit>,
928 enabled: bool,
929) -> Stateful<Div> {
930 match editing {
931 Some(edit) => scrub_field(id, w, edit.text().to_string(), unit, enabled, Some(ScrubLook::Typing)),
932 None => scrub_field(id, w, value, unit, enabled, None),
933 }
934}
935
936/// `#RRGGBB` for an `0xRRGGBB` colour.
937pub fn hex_text(rgb: u32) -> String {
938 format!("#{:06X}", rgb & 0xff_ffff)
939}
940
941/// The colour a typed `#RRGGBB` (or `RRGGBB`, or `#RGB`) names.
942#[allow(dead_code, reason = "the cards adopt it next")]
943pub fn parse_hex(text: &str) -> Option<u32> {
944 let h = text.trim().trim_start_matches('#');
945 match h.len() {
946 6 => u32::from_str_radix(h, 16).ok(),
947 3 => {
948 let v = u32::from_str_radix(h, 16).ok()?;
949 let (r_, g, b) = ((v >> 8) & 0xf, (v >> 4) & 0xf, v & 0xf);
950 Some(((r_ * 0x11) << 16) | ((g * 0x11) << 8) | (b * 0x11))
951 }
952 _ => None,
953 }
954}
955
956/// The swatch row: round swatches, the current colour wearing a ring. A
957/// current colour that is not in `colours` (a custom one) is shown as an extra
958/// swatch at the end, ringed, so the row always says what is in force. After
959/// the swatches, the `#RRGGBB` field (`hex_editing` is the typed text while the
960/// field is being edited); a click on it calls `on_hex`. The user's own colour
961/// is used exactly: nothing here rounds it to a swatch.
962pub fn swatch_row(
963 id: &'static str,
964 colours: &[u32],
965 current: u32,
966 hex_editing: Option<&str>,
967 on_pick: impl Fn(u32, &mut Window, &mut App) + Clone + 'static,
968 on_hex: impl Fn(&mut Window, &mut App) + 'static,
969) -> Div {
970 let t = tokens();
971 let current = current & 0xff_ffff;
972 let custom = !colours.iter().any(|x| x & 0xff_ffff == current);
973 let all: Vec<u32> = colours.iter().copied().chain(custom.then_some(current)).collect();
974 let mut row = div().flex().flex_wrap().items_center().gap(px(6.));
975 for (i, colour) in all.into_iter().enumerate() {
976 let on = colour & 0xff_ffff == current;
977 let on_pick = on_pick.clone();
978 // The ring is the box's own border (always there, transparent when off), so
979 // choosing never moves a swatch.
980 row = row.child(
981 div()
982 .id((id, i))
983 .flex_none()
984 .size(px(22.))
985 .flex()
986 .items_center()
987 .justify_center()
988 .rounded_full()
989 .border_2()
990 .border_color(if on { c(t.ink1) } else { hsla(0., 0., 0., 0.) })
991 .cursor_pointer()
992 .when(!on, |d| d.hover(|s| s.border_color(ca(t.line_hi))))
993 .tooltip(crate::ui::widgets::overlay_tip_hover(
994 &if custom && i == colours.len() { format!("Custom {}", hex_text(colour)) } else { hex_text(colour) },
995 "",
996 None,
997 ))
998 .child(div().size(px(14.)).rounded_full().bg(c(colour & 0xff_ffff)).border_1().border_color(ca(t.line)))
999 .on_click(move |_, window, cx| on_pick(colour & 0xff_ffff, window, cx)),
1000 );
1001 }
1002 let typing = hex_editing.is_some();
1003 row.child(
1004 div()
1005 .id((id, 99usize))
1006 .flex_none()
1007 .w(px(76.))
1008 .h(px(r::CONTROL_S))
1009 .px(px(8.))
1010 .flex()
1011 .items_center()
1012 .rounded(px(r::R_CONTROL))
1013 .border_1()
1014 .border_color(if typing { c(t.accent) } else { hsla(0., 0., 0., 0.) })
1015 .bg(c(t.e2))
1016 .cursor(CursorStyle::IBeam)
1017 .hover(move |s| s.bg(c(tokens().e3)))
1018 .type_style(type_scale::caption())
1019 .text_color(c(t.ink1))
1020 .child(match hex_editing {
1021 Some(text) => format!("{text}\u{258f}"),
1022 None => hex_text(current),
1023 })
1024 .on_click(move |_, window, cx| on_hex(window, cx)),
1025 )
1026}
1027
1028/// The closed half of a card dropdown: an `e2` row control, the current value
1029/// on the left, a chevron on the right, 28px tall. It records its bounds under
1030/// `id` ([`crate::ui::anchor`]) so the list it opens hangs from it: on click
1031/// call `Player::picker_at_control(Pick::..)` for an enumerated setting, or
1032/// show a [`choice_list`] at [`crate::ui::anchor::hang`]. A blank value reads
1033/// `Custom` (the setting matches none of the listed choices), never an empty box.
1034pub fn dropdown_field(id: &'static str, value: impl Into<SharedString>, enabled: bool) -> Stateful<Div> {
1035 let t = tokens();
1036 let value: SharedString = value.into();
1037 let value = if value.is_empty() { SharedString::from("Custom") } else { value };
1038 states(
1039 div()
1040 .id(id)
1041 .relative()
1042 .w_full()
1043 .flex_none()
1044 .h(px(r::CONTROL_M))
1045 .px(px(10.))
1046 .flex()
1047 .items_center()
1048 .justify_between()
1049 .gap(px(8.))
1050 .rounded(px(r::R_CONTROL))
1051 .border_1()
1052 .border_color(ca(t.line))
1053 .type_style(type_scale::body_strong())
1054 .text_color(c(if enabled { t.ink1 } else { t.ink4 }))
1055 .child(crate::ui::anchor::probe(id))
1056 .child(div().min_w(px(0.)).truncate().child(value))
1057 .child(Icon::ChevronDown.el(IconSize::Inline, if enabled { t.ink2 } else { t.ink4 })),
1058 Fills::solid(),
1059 enabled,
1060 None,
1061 )
1062}
1063
1064/// The open half of a card dropdown: a [`plate`] of rows, the one in force
1065/// marked with a check (no focus ring: that appears only on keyboard
1066/// navigation). Position it absolutely at [`crate::ui::anchor::hang`] of the
1067/// field. `on_pick` gets the row's index.
1068pub fn choice_list(
1069 id: &'static str,
1070 w: f32,
1071 items: &[SharedString],
1072 current: usize,
1073 on_pick: impl Fn(usize, &mut Window, &mut App) + Clone + 'static,
1074) -> Stateful<Div> {
1075 choice_list_faced(id, w, items, &[], current, on_pick)
1076}
1077
1078/// Moves the highlight of the open list `id` to row `ix` and brings that row into view: for a list
1079/// whose rows just changed (a search narrowed them).
1080pub fn set_list_highlight(id: &'static str, ix: usize) {
1081 OPEN_LIST.with(|l| {
1082 let mut l = l.borrow_mut();
1083 if l.id == id {
1084 l.hi = ix;
1085 }
1086 });
1087 list_scroll(id).scroll_to_item(ix);
1088}
1089
1090/// [`choice_list`] whose row `i` is drawn in the font family `faces[i]` when it is `Some`, and in
1091/// the UI font when it is `None` or `faces` is short. Up, Down and Enter work it as they do any
1092/// list ([`list_nav`]). A list taller than [`LIST_MAX_H`] scrolls.
1093pub fn choice_list_faced(
1094 id: &'static str,
1095 w: f32,
1096 items: &[SharedString],
1097 faces: &[Option<SharedString>],
1098 current: usize,
1099 on_pick: impl Fn(usize, &mut Window, &mut App) + Clone + 'static,
1100) -> Stateful<Div> {
1101 let t = tokens();
1102 let scroll = list_scroll(id);
1103 let hi = OPEN_LIST.with(|l| {
1104 let mut l = l.borrow_mut();
1105 if l.id != id {
1106 l.id = id;
1107 l.hi = current;
1108 scroll.scroll_to_item(current);
1109 }
1110 l.len = items.len();
1111 l.pick = Some(Rc::new(on_pick.clone()));
1112 l.hi
1113 });
1114 let mut list = plate(6.)
1115 .id(id)
1116 .w(px(w))
1117 .p(px(crate::layout::MENU_PAD))
1118 .flex()
1119 .flex_col()
1120 .max_h(px(LIST_MAX_H))
1121 .overflow_y_scroll()
1122 .track_scroll(&scroll)
1123 .occlude();
1124 for (i, label) in items.iter().enumerate() {
1125 let on_pick = on_pick.clone();
1126 let picked = i == current;
1127 list = list.child(
1128 div()
1129 .id((id, i))
1130 .flex_none()
1131 .h(px(crate::layout::MENU_ROW_H))
1132 .px(px(8.))
1133 .flex()
1134 .items_center()
1135 .gap(px(8.))
1136 .rounded(px(4.))
1137 .cursor_pointer()
1138 .hover(|s| s.bg(ca(theme::WASH_HOVER)))
1139 .when(i == hi, |d| d.bg(ca(theme::WASH_HOVER)))
1140 .type_style(type_scale::body_strong())
1141 .text_color(c(t.ink1))
1142 .child(div().flex_none().size(px(16.)).children(picked.then(|| Icon::Check.el(IconSize::Inline, t.accent))))
1143 .child(
1144 div()
1145 .min_w(px(0.))
1146 .whitespace_nowrap()
1147 .when_some(faces.get(i).cloned().flatten(), |d, face| d.font_family(face))
1148 .child(label.clone()),
1149 )
1150 .on_click(move |_, window, cx| on_pick(i, window, cx)),
1151 );
1152 }
1153 list
1154}
1155
1156/// One row of a [`plate`] list: the [`choice_list`] row on its own, for a plate that holds
1157/// more than one list. A check marks the one in force.
1158pub fn choice_row(
1159 id: (&'static str, usize),
1160 label: impl Into<SharedString>,
1161 picked: bool,
1162 on_pick: impl Fn(&mut Window, &mut App) + 'static,
1163) -> Stateful<Div> {
1164 let t = tokens();
1165 div()
1166 .id(id)
1167 .flex_none()
1168 .h(px(crate::layout::MENU_ROW_H))
1169 .px(px(8.))
1170 .flex()
1171 .items_center()
1172 .gap(px(8.))
1173 .rounded(px(4.))
1174 .cursor_pointer()
1175 .hover(|s| s.bg(ca(theme::WASH_HOVER)))
1176 .type_style(type_scale::body_strong())
1177 .text_color(c(t.ink1))
1178 .child(div().flex_none().size(px(16.)).children(picked.then(|| Icon::Check.el(IconSize::Inline, t.accent))))
1179 .child(div().min_w(px(0.)).whitespace_nowrap().child(label.into()))
1180 .on_click(move |_, window, cx| on_pick(window, cx))
1181}
1182
1183/// A ghost icon button with a tooltip, for row actions (move up, move down,
1184/// remove). While `why` is `Some` it is disabled (dimmed, not-allowed, no
1185/// handler) and the tooltip gives the reason instead of the name.
1186pub fn icon_ghost(
1187 id: &'static str,
1188 icon: Icon,
1189 tip: &str,
1190 why: Option<&str>,
1191 on_click: impl Fn(&mut Window, &mut App) + 'static,
1192) -> Stateful<Div> {
1193 let b = Button::new(id)
1194 .icon(icon)
1195 .style(ButtonStyle::Ghost)
1196 .size(ButtonSize::Small)
1197 .enabled(why.is_none())
1198 .build()
1199 .tooltip(crate::ui::widgets::overlay_tip_hover(tip, "", why));
1200 match why {
1201 Some(_) => b,
1202 None => b.on_click(move |_, window, cx| on_click(window, cx)),
1203 }
1204}
1205
1206/// A chord drawn as keycaps: `"Ctrl+Shift+R"` is three [`keycap`]s with a
1207/// small gap. A trailing `+` is the plus key (`"Ctrl++"`), and a bare `+` or
1208/// `-` is its own key. `" or "` separates alternatives (`"Ctrl+Y or Ctrl+Shift+Z"`),
1209/// each drawn as its own run with a plain "or" between. For sheets, the
1210/// palette's hint column and tooltips only (§5 rule 1).
1211pub fn keycaps(chord: &str) -> Div {
1212 let mut parts: Vec<AnyElement> = Vec::new();
1213 for (i, alt) in chord.split(" or ").enumerate() {
1214 if i > 0 {
1215 parts.push(div().type_style(type_scale::caption()).text_color(c(tokens().ink3)).child("or").into_any_element());
1216 }
1217 parts.extend(chord_keys(alt).into_iter().map(|k| keycap(k.to_string()).into_any_element()));
1218 }
1219 div().flex_none().flex().items_center().gap(px(3.)).children(parts)
1220}
1221
1222/// The width [`keycaps`] takes for `chord`, from the same split: each cap's
1223/// text plus its padding and border (never narrower than the cap's minimum), a
1224/// 3px gap between caps, and the "or" word between alternatives. A tooltip sizes
1225/// its plate from this, so a long chord is not clipped.
1226pub fn keycaps_w(chord: &str) -> f32 {
1227 let cap = |k: &str| (crate::ui::popup::text_w(k, 12., false) + 12.).max(18.);
1228 let mut w = 0.;
1229 for (i, alt) in chord.split(" or ").enumerate() {
1230 if i > 0 {
1231 w += crate::ui::popup::text_w("or", 12., false) + 3.;
1232 }
1233 for (j, k) in chord_keys(alt).iter().enumerate() {
1234 w += cap(k) + if j > 0 { 3. } else { 0. };
1235 }
1236 }
1237 w
1238}
1239
1240/// One alternative's keys: `"Ctrl+Shift+R"` is three, `"Ctrl++"` is "Ctrl" and
1241/// "+", a bare `"+"` or `"-"` is itself.
1242fn chord_keys(chord: &str) -> Vec<&str> {
1243 let mut parts: Vec<&str> = Vec::new();
1244 let mut rest = chord;
1245 while !rest.is_empty() {
1246 if rest == "+" {
1247 parts.push("+");
1248 break;
1249 }
1250 match rest.find('+') {
1251 Some(0) => {
1252 parts.push("+");
1253 rest = &rest[1..];
1254 }
1255 Some(at) => {
1256 parts.push(&rest[..at]);
1257 rest = &rest[at + 1..];
1258 }
1259 None => {
1260 parts.push(rest);
1261 break;
1262 }
1263 }
1264 }
1265 parts
1266}
1267
1268// ---------------------------------------------------------------------------
1269// The dialog shell: every modal sheet (New project, Save version, Versions,
1270// Collect media, About, unsaved changes, Relink, Shortcuts) is built from this.
1271// ---------------------------------------------------------------------------
1272
1273/// The dialog layer: a subtle scrim over the window *below the menu bar* (the bar stays live
1274/// and unshaded) that centres its child in the picture region (`bottom_inset` is the height of
1275/// the timeline under it, which the dialog never covers). A press on the scrim is the caller's
1276/// to handle (`.on_mouse_down(..)`); the dialog itself stops it.
1277pub fn dialog_layer(bottom_inset: f32) -> Div {
1278 div()
1279 .absolute()
1280 .left_0()
1281 .right_0()
1282 .bottom_0()
1283 .top(px(crate::layout::MENU_BAR_H))
1284 .occlude()
1285 .pt(px(8.))
1286 .pb(px(8. + bottom_inset * 0.))
1287 .flex()
1288 .items_center()
1289 .justify_center()
1290 .bg(hsla(0., 0., 0., 0.55))
1291}
1292
1293/// The dialog plate: [`plate`]`(8)`, `w` wide, 20px padding, children stacked
1294/// 12px apart, height hugging its content, and the close X at its top right
1295/// (it asks the window to cancel whatever dialog is up, the same as Esc).
1296/// Put `dialog_title`, a body and [`dialog_actions`] in it.
1297pub fn dialog(id: &'static str, w: f32) -> Stateful<Div> {
1298 let close = TAB_POOL.with(|p| {
1299 // The X is a pointer door; Esc is its key, so it takes no place in the Tab order.
1300 let held = p.borrow_mut().0.take();
1301 let b = Button::new("dialog-x")
1302 .icon(Icon::X)
1303 .style(ButtonStyle::Ghost)
1304 .size(ButtonSize::Small)
1305 .build()
1306 .tooltip(crate::ui::widgets::overlay_tip_hover("Close", "Esc", None))
1307 .on_click(|_, window, cx| {
1308 if let Some(Some(player)) = window.root::<Player>() {
1309 player.update(cx, |player, cx| player.dialog_cancel(cx));
1310 }
1311 });
1312 p.borrow_mut().0 = held;
1313 b
1314 });
1315 plate(8.)
1316 .id(id)
1317 .relative()
1318 .flex_none()
1319 .w(px(w))
1320 .max_w(px(900.))
1321 .occlude()
1322 .p(px(20.))
1323 .flex()
1324 .flex_col()
1325 .gap(px(12.))
1326 .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| cx.stop_propagation())
1327 .child(div().absolute().top(px(10.)).right(px(10.)).child(close))
1328}
1329
1330/// A dialog's title: one size for every dialog (`title`, `ink1`), clear of the close X.
1331pub fn dialog_title(text: impl Into<SharedString>) -> Div {
1332 div().pr(px(28.)).type_style(type_scale::title()).text_color(c(tokens().ink1)).child(text.into())
1333}
1334
1335/// A dialog's body line: `body`, `ink2`, wrapping.
1336pub fn dialog_text(text: impl Into<SharedString>) -> Div {
1337 div().type_style(type_scale::body()).text_color(c(tokens().ink2)).child(text.into())
1338}
1339
1340/// The button row at a dialog's foot: right-aligned, 8px between buttons.
1341pub fn dialog_actions() -> Div {
1342 div().flex_none().flex().items_center().justify_end().gap(px(8.)).pt(px(4.))
1343}
1344
1345#[cfg(test)]
1346mod tests {
1347 use super::*;
1348 use crate::player::text_field::FieldKey;
1349
1350 #[test]
1351 fn typing_a_number_replaces_the_old_text_and_commits_clamped() {
1352 let mut e = NumberEdit::begin("1.00");
1353 assert_eq!(e.key("2", false, false, Some("2")), FieldKey::Edited);
1354 e.key(",", false, false, Some(","));
1355 e.key("5", false, false, Some("5"));
1356 // A letter is ignored.
1357 e.key("x", false, false, Some("x"));
1358 assert_eq!(e.text(), "2,5");
1359 assert_eq!(e.commit(0., 2.), Some(2.));
1360 assert_eq!(e.key("enter", false, false, None), FieldKey::Commit);
1361 assert_eq!(e.key("escape", false, false, None), FieldKey::Cancel);
1362 assert_eq!(NumberEdit::begin("").commit(0., 1.), None);
1363 }
1364
1365 #[test]
1366 fn scrubbing_moves_per_pixel_fine_with_shift_and_stays_in_range() {
1367 assert_eq!(scrub_value(1., 10., 0.01, false, 0., 2.), 1.1);
1368 assert!((scrub_value(1., 10., 0.01, true, 0., 2.) - 1.01).abs() < 1e-9);
1369 assert_eq!(scrub_value(1., 1000., 0.01, false, 0., 2.), 2.);
1370 }
1371
1372 #[test]
1373 fn hex_round_trips_and_short_form_expands() {
1374 assert_eq!(hex_text(0x00ff7a), "#00FF7A");
1375 assert_eq!(parse_hex("#00ff7a"), Some(0x00ff7a));
1376 assert_eq!(parse_hex("f80"), Some(0xff8800));
1377 assert_eq!(parse_hex("#12"), None);
1378 }
1379}