forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

choice.rs228 lines, 8.2 KiBHistoryRawDownload
1//! Segmented choice: every answer a short setting takes, on the setting's own
2//! row, the one in force lit, a click on any other picking it outright. The
3//! settings page's answer to its "press to cycle" rows (UX audit D-1): a cycle
4//! button shows one value and hides the rest behind a press, so a person
5//! cannot know what a row offers without stepping all the way round it. Five
6//! answers or fewer fit on one row as chips; a longer list is a dropdown
7//! ([`crate::Pick`]) -- still one click away, and the row's caret says so.
8//!
9//! Keyboard: the settings page's own arrow branch
10//! ([`crate::ui::settings_stance::settings_arrow`]) moves a focus between the
11//! choice rows (`↑`/`↓`) and steps the focused row's value (`←`/`→`) -- the
12//! radio group's convention, where an arrow both moves and picks, so there
13//! is no second "confirm" stroke to learn. The focused row wears DESIGN
14//! §4.10's 1px `ink2` top rule, so where the keyboard is looking is visible
15//! before a key is pressed.
16//!
17//! A file of its own rather than a widget in `ui/widgets.rs`: another lane
18//! changed that file at the same time, and this helper has no sibling there.
19
20use crate::ui::hitmap;
21use crate::ui::type_scale::{self, Typeset};
22use crate::*;
23use gpui::SharedString;
24
25/// One chip of a segmented row: its word, and whether it is the value in
26/// force.
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub(crate) struct Chip {
29 pub(crate) label: SharedString,
30 pub(crate) active: bool,
31}
32
33/// The chips of a row from its labels and the index in force: exactly one is
34/// lit, or none when `current` names no row (a setting with nothing behind
35/// it yet, like the tonemap before a project opens).
36pub(crate) fn chips<S: Into<SharedString> + Clone>(
37 labels: &[S],
38 current: Option<usize>,
39) -> Vec<Chip> {
40 labels
41 .iter()
42 .enumerate()
43 .map(|(i, label)| Chip {
44 label: label.clone().into(),
45 active: current == Some(i),
46 })
47 .collect()
48}
49
50/// The index an arrow steps to from `current` in a row of `len`: the next
51/// one, wrapping at either end, so the stroke never dead-ends on the last
52/// chip -- the cycle buttons this replaces wrapped, and a hand used to that
53/// keeps it.
54pub(crate) fn step(len: usize, current: usize, forward: bool) -> usize {
55 if len == 0 {
56 return 0;
57 }
58 match forward {
59 true => (current + 1) % len,
60 false => (current + len - 1) % len,
61 }
62}
63
64/// Where `↑`/`↓` lands among `len` rows: the next row, wrapping; from no
65/// focus, the first row (`↓`) or the last (`↑`). `None` for a tab with no
66/// choice rows, where there is nothing for a focus to sit on.
67pub(crate) fn move_focus(len: usize, focused: Option<usize>, forward: bool) -> Option<usize> {
68 if len == 0 {
69 return None;
70 }
71 Some(match focused.filter(|&at| at < len) {
72 Some(at) => step(len, at, forward),
73 None if forward => 0,
74 None => len - 1,
75 })
76}
77
78/// A chip's side padding, and the gap between two chips.
79pub(crate) const CHIP_PAD: f32 = 8.;
80pub(crate) const CHIP_GAP: f32 = 2.;
81
82/// A chip's width as the page measures it before it is drawn -- the mono
83/// badge glyph's advance per character, generous, plus the padding. For the
84/// fit guard in the tests, never the layout: gpui measures the real thing.
85#[cfg(test)]
86pub(crate) fn chip_w(label: &str) -> f32 {
87 label.chars().count() as f32 * 7. + 2. * CHIP_PAD
88}
89
90/// The width a whole segmented row of `labels` asks for, chips and gaps.
91#[cfg(test)]
92pub(crate) fn row_w<S: AsRef<str>>(labels: &[S]) -> f32 {
93 labels
94 .iter()
95 .map(|label| chip_w(label.as_ref()))
96 .sum::<f32>()
97 + CHIP_GAP * labels.len().saturating_sub(1) as f32
98}
99
100/// The segmented row: one chip per entry, each a hit area of its own
101/// (`{id}-{i}`, so the harness can press any answer, not only the next one).
102/// The chip in force wears the raised plate and `ink1`; the others are `ink3`
103/// and light on hover. Disabled, every chip is `ink4` and takes no click --
104/// the row stays in the tree saying what it offers, which is the point.
105/// `hint` is the row's own sentence, on every chip's hover line. `pick` is
106/// called with the chip's index; it is `Copy` so each chip can carry its own
107/// listener.
108pub(crate) fn segmented<V: 'static>(
109 id: &'static str,
110 chips: Vec<Chip>,
111 enabled: bool,
112 hint: &'static str,
113 cx: &mut Context<V>,
114 pick: impl Fn(&mut V, usize, &mut Context<V>) + Copy + 'static,
115) -> impl IntoElement {
116 let style = type_scale::body_strong();
117 let t = crate::ui::theme::tokens();
118 div()
119 .id(id)
120 .flex_none()
121 .flex()
122 .items_center()
123 .gap(px(CHIP_GAP))
124 .p(px(2.))
125 .rounded(px(4.))
126 .bg(rgb(t.e2))
127 .when(!enabled, |d| d.opacity(0.6))
128 .children(chips.into_iter().enumerate().map(|(i, chip)| {
129 let active = chip.active;
130 let hit_label = chip.label.to_string();
131 let tip = crate::ui::widgets::tip_hover(&hit_label, "", Some(hint));
132 crate::ui::kit::kbd_stop(div().id(SharedString::from(format!("{id}-{i}"))))
133 .flex_none()
134 .flex()
135 .items_center()
136 .h(px(24.))
137 .px(px(CHIP_PAD))
138 .rounded(px(3.))
139 .when(active, |d| d.bg(rgb(t.e3)))
140 .when(enabled, |d| {
141 d.cursor_pointer()
142 .when(!active, |d| d.hover(|s| s.bg(rgba(crate::ui::theme::WASH_HOVER))))
143 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
144 cx.stop_propagation();
145 pick(this, i, cx)
146 }))
147 })
148 .tooltip(tip)
149 .children(hitmap::dynamic(
150 move || (format!("{id}-{i}"), hit_label),
151 enabled,
152 ))
153 .type_style(style.clone())
154 .text_color(rgb(match (enabled, active) {
155 (false, _) => t.ink4,
156 (true, true) => t.ink1,
157 (true, false) => t.ink2,
158 }))
159 .child(chip.label)
160 }))
161}
162
163#[cfg(test)]
164mod tests {
165 use super::*;
166
167 #[test]
168 fn exactly_one_chip_is_lit_and_it_is_the_value_in_force() {
169 let labels = ["Off", "On"];
170 let row = chips(&labels, Some(1));
171 assert_eq!(row.iter().filter(|c| c.active).count(), 1);
172 assert!(row[1].active && !row[0].active);
173 assert_eq!(row[1].label.as_ref(), "On");
174 // Nothing behind the setting yet: every chip rests.
175 assert!(chips(&labels, None).iter().all(|c| !c.active));
176 }
177
178 #[test]
179 fn an_arrow_steps_and_wraps_at_both_ends() {
180 assert_eq!(step(3, 0, true), 1);
181 assert_eq!(
182 step(3, 2, true),
183 0,
184 "→ off the last chip wraps to the first"
185 );
186 assert_eq!(
187 step(3, 0, false),
188 2,
189 "← off the first chip wraps to the last"
190 );
191 assert_eq!(step(0, 0, true), 0, "an empty row has nowhere to step");
192 // A full walk round is a wrap, never a dead end.
193 let mut at = 0;
194 for _ in 0..4 {
195 at = step(4, at, true);
196 }
197 assert_eq!(at, 0);
198 }
199
200 #[test]
201 fn focus_enters_at_an_end_and_walks_the_rows_round() {
202 assert_eq!(
203 move_focus(3, None, true),
204 Some(0),
205 "↓ from nowhere lands on the first row"
206 );
207 assert_eq!(
208 move_focus(3, None, false),
209 Some(2),
210 "↑ from nowhere lands on the last"
211 );
212 assert_eq!(move_focus(3, Some(2), true), Some(0));
213 assert_eq!(move_focus(3, Some(0), false), Some(2));
214 assert_eq!(move_focus(0, Some(1), true), None, "no rows, no focus");
215 // A focus left over from a longer tab is treated as none.
216 assert_eq!(move_focus(2, Some(5), true), Some(0));
217 }
218
219 #[test]
220 fn a_row_measures_its_chips_and_the_gaps_between_them() {
221 assert_eq!(chip_w("On"), 2. * 7. + 2. * CHIP_PAD);
222 assert_eq!(
223 row_w(&["Off", "On"]),
224 chip_w("Off") + chip_w("On") + CHIP_GAP
225 );
226 assert_eq!(row_w::<&str>(&[]), 0.);
227 }
228}