Skip to main content

hypersig_ui/
toggle.rs

1//! Toggle buttons, alone or in a group that picks one value or several.
2
3use hypersig::html::{El, Event, Node, Orientation, Role, attr, button as button_el, div};
4use hypersig::style::value::{
5    AlignItems, BorderStyle, Color, Cursor, Display, FontWeight, JustifyContent, WhiteSpace, px,
6    rem,
7};
8use hypersig::style::{PseudoClass, Style};
9use hypersig::{Sig, Writable, if_else};
10use serde::Serialize;
11
12use crate::look;
13use crate::token;
14
15/// A button that is pressed while `pressed` is true, and flips it when clicked.
16///
17/// It is a native `<button>` with `aria-pressed`, so a screen reader
18/// announces it as a toggle button that is pressed or not pressed, and Enter
19/// and Space flip it. Keep its text the same in both states, since the state
20/// is announced on its own. It needs no id, so it works on a field of a list
21/// item.
22///
23/// ```
24/// use hypersig::{Page, Signals};
25/// use hypersig_ui::toggle;
26/// use serde::{Deserialize, Serialize};
27///
28/// #[derive(Signals, Serialize, Deserialize)]
29/// struct Editor {
30///     bold: bool,
31/// }
32///
33/// let html = Page::new("Editor", Editor { bold: true })
34///     .child(toggle(Editor::bold()).text("Bold"))
35///     .render();
36/// assert!(html.contains(r#"aria-pressed="true""#));
37/// ```
38#[must_use]
39pub fn toggle<S, R: Writable>(pressed: Sig<S, bool, R>) -> El<S> {
40    pressable(pressed).on_click(pressed.toggle())
41}
42
43/// A toggle that shows only an icon, named `label` for assistive technology.
44///
45/// It is [`toggle`] with `aria-label` set to `label` and a square shape. Add
46/// the icon with [`El::child`].
47///
48/// ```
49/// use hypersig::Signals;
50/// use hypersig_ui::icon_toggle;
51/// use serde::{Deserialize, Serialize};
52///
53/// #[derive(Signals, Serialize, Deserialize)]
54/// struct Editor {
55///     italic: bool,
56/// }
57///
58/// let italic = icon_toggle::<Editor, _>("Italic", Editor::italic()).text("I");
59/// assert!(italic.render().contains(r#"aria-label="Italic""#));
60/// ```
61#[must_use]
62pub fn icon_toggle<S, R: Writable>(label: impl Into<String>, pressed: Sig<S, bool, R>) -> El<S> {
63    toggle(pressed)
64        .attr(attr::ARIA_LABEL, label)
65        .css(Style::new().width(rem(2.25)).padding_inline(px(0)))
66}
67
68/// The button of a toggle bound to `pressed`, without its click statement.
69fn pressable<S, R>(pressed: Sig<S, bool, R>) -> El<S> {
70    button_el()
71        .attr(attr::TYPE, "button")
72        .bind_attr(attr::ARIA_PRESSED, if_else(pressed, "true", "false"))
73        .css(toggle_style())
74        .css_when(on_style(), pressed)
75}
76
77/// A group of toggles named `label` that picks one value of `selected`.
78///
79/// It follows the WAI-ARIA radio group pattern, since exactly one toggle is
80/// on at a time. The group has `role="radiogroup"` and each toggle
81/// `role="radio"` with `aria-checked`. Tab enters the group at the toggle
82/// whose value `selected` holds, and the arrow keys, Home, and End move
83/// between toggles and pick the one they reach, through
84/// [`El::roving_focus`]. While `selected` holds a value no toggle has, Tab
85/// skips the group.
86///
87/// ```
88/// use hypersig::Signals;
89/// use hypersig_ui::ToggleGroup;
90/// use serde::{Deserialize, Serialize};
91///
92/// #[derive(Serialize, Deserialize, Clone, Copy, PartialEq)]
93/// enum Align {
94///     Left,
95///     Center,
96///     Right,
97/// }
98///
99/// #[derive(Signals, Serialize, Deserialize)]
100/// struct Text {
101///     align: Align,
102/// }
103///
104/// let align = ToggleGroup::new("Alignment", Text::align())
105///     .item(Align::Left, "Left")
106///     .item(Align::Center, "Center")
107///     .item(Align::Right, "Right");
108/// let html = align.render().render();
109/// assert!(html.contains(r#"role="radiogroup""#));
110/// assert!(html.contains(r#"role="radio""#));
111/// ```
112#[derive(Debug)]
113pub struct ToggleGroup<S, T> {
114    label: String,
115    selected: Sig<S, T>,
116    /// Each toggle's value, and its button before it is bound to that value.
117    items: Vec<(T, El<S>)>,
118}
119
120impl<S, T: Serialize + PartialEq> ToggleGroup<S, T> {
121    /// An empty group named `label` for assistive technology.
122    #[must_use]
123    pub fn new(label: impl Into<String>, selected: Sig<S, T>) -> Self {
124        Self {
125            label: label.into(),
126            selected,
127            items: Vec::new(),
128        }
129    }
130
131    /// Adds a toggle showing `text` that picks `value`.
132    #[must_use]
133    pub fn item(mut self, value: T, text: impl Into<String>) -> Self {
134        self.items.push((value, button_el().text(text)));
135        self
136    }
137
138    /// Adds a toggle showing `icon` that picks `value`, named `label`.
139    #[must_use]
140    pub fn icon_item(
141        mut self,
142        value: T,
143        label: impl Into<String>,
144        icon: impl Into<Node<S>>,
145    ) -> Self {
146        let item = button_el()
147            .attr(attr::ARIA_LABEL, label)
148            .css(Style::new().width(rem(2.25)).padding_inline(px(0)))
149            .child(icon.into());
150        self.items.push((value, item));
151        self
152    }
153
154    /// The toggles in a `<div>`.
155    #[must_use]
156    pub fn render(self) -> El<S> {
157        let selected = self.selected;
158        group(self.label, Role::RadioGroup).children(self.items.into_iter().map(|(value, item)| {
159            let on = selected.equals(&value);
160            item.attr(attr::TYPE, "button")
161                .role(Role::Radio)
162                .bind_attr(attr::ARIA_CHECKED, if_else(on.clone(), "true", "false"))
163                .bind_attr(attr::TABINDEX, if_else(on.clone(), "0", "-1"))
164                .on(Event::Focus, selected.set(&value))
165                .on_click(selected.set(&value))
166                .css(toggle_style())
167                .css_when(on_style(), on)
168        }))
169    }
170}
171
172impl<S, T: Serialize + PartialEq> From<ToggleGroup<S, T>> for El<S> {
173    fn from(group: ToggleGroup<S, T>) -> Self {
174        group.render()
175    }
176}
177
178impl<S, T: Serialize + PartialEq> From<ToggleGroup<S, T>> for Node<S> {
179    fn from(group: ToggleGroup<S, T>) -> Self {
180        group.render().into()
181    }
182}
183
184/// A group of toggles named `label`, each bound to a flag of its own.
185///
186/// The group has `role="group"` and each toggle is a [`toggle`] with
187/// `aria-pressed`. Tab enters the group at its first toggle, and the arrow
188/// keys, Home, and End move between toggles without flipping them, through
189/// [`El::roving_focus`]. Enter and Space flip the toggle that has focus.
190///
191/// ```
192/// use hypersig::{Page, Signals};
193/// use hypersig_ui::MultiToggleGroup;
194/// use serde::{Deserialize, Serialize};
195///
196/// #[derive(Signals, Serialize, Deserialize)]
197/// struct Editor {
198///     bold: bool,
199///     italic: bool,
200/// }
201///
202/// let style = MultiToggleGroup::new("Text style")
203///     .item(Editor::bold(), "Bold")
204///     .item(Editor::italic(), "Italic");
205/// let html = Page::new("Editor", Editor { bold: true, italic: false })
206///     .child(style)
207///     .render();
208/// assert!(html.contains(r#"role="group""#));
209/// assert!(html.contains(r#"aria-pressed="false""#));
210/// ```
211#[derive(Debug)]
212pub struct MultiToggleGroup<S> {
213    label: String,
214    items: Vec<El<S>>,
215}
216
217impl<S> MultiToggleGroup<S> {
218    /// An empty group named `label` for assistive technology.
219    #[must_use]
220    pub fn new(label: impl Into<String>) -> Self {
221        Self {
222            label: label.into(),
223            items: Vec::new(),
224        }
225    }
226
227    /// Adds a toggle showing `text` that flips `pressed`.
228    #[must_use]
229    pub fn item<R: Writable>(mut self, pressed: Sig<S, bool, R>, text: impl Into<String>) -> Self {
230        self.items.push(toggle(pressed).text(text));
231        self
232    }
233
234    /// Adds a toggle showing `icon` that flips `pressed`, named `label`.
235    #[must_use]
236    pub fn icon_item<R: Writable>(
237        mut self,
238        pressed: Sig<S, bool, R>,
239        label: impl Into<String>,
240        icon: impl Into<Node<S>>,
241    ) -> Self {
242        self.items
243            .push(icon_toggle(label, pressed).child(icon.into()));
244        self
245    }
246
247    /// The toggles in a `<div>`.
248    #[must_use]
249    pub fn render(self) -> El<S> {
250        // A `<button>` is in the tab order by itself, so every toggle but the
251        // first leaves it, and the arrow keys reach them instead.
252        group(self.label, Role::Group).children(
253            self.items.into_iter().enumerate().map(|(index, item)| {
254                item.attr(attr::TABINDEX, if index == 0 { "0" } else { "-1" })
255            }),
256        )
257    }
258}
259
260impl<S> From<MultiToggleGroup<S>> for El<S> {
261    fn from(group: MultiToggleGroup<S>) -> Self {
262        group.render()
263    }
264}
265
266impl<S> From<MultiToggleGroup<S>> for Node<S> {
267    fn from(group: MultiToggleGroup<S>) -> Self {
268        group.render().into()
269    }
270}
271
272fn group<S>(label: String, role: Role) -> El<S> {
273    div()
274        .role(role)
275        .attr(attr::ARIA_LABEL, label)
276        .roving_focus(Orientation::Horizontal)
277        .css(
278            Style::new()
279                .display(Display::InlineFlex)
280                .align_items(AlignItems::Center)
281                .gap(rem(0.25)),
282        )
283}
284
285fn toggle_style() -> Style {
286    Style::new()
287        .display(Display::InlineFlex)
288        .align_items(AlignItems::Center)
289        .justify_content(JustifyContent::Center)
290        .gap(rem(0.5))
291        .height(rem(2.25))
292        .min_width(rem(2.25))
293        .padding_inline(rem(0.625))
294        .border_width(px(1))
295        .border_style(BorderStyle::Solid)
296        .border_color(token::input().var())
297        .border_radius(px(6))
298        .background_color(Color::TRANSPARENT)
299        .color(token::foreground().var())
300        .font_weight(FontWeight::Number(500.0))
301        .white_space(WhiteSpace::Nowrap)
302        .cursor(Cursor::Pointer)
303        .merge(look::small_text())
304        .merge(look::transition())
305        .merge(look::focus_ring())
306        .on(
307            PseudoClass::Hover,
308            Style::new()
309                .background_color(token::muted().var())
310                .color(token::muted_foreground().var()),
311        )
312        .merge(look::disabled())
313}
314
315/// The colors a toggle takes while it is on, which hovering keeps.
316fn on_style() -> Style {
317    Style::new()
318        .background_color(token::accent().var())
319        .color(token::accent_foreground().var())
320        .on(
321            PseudoClass::Hover,
322            Style::new()
323                .background_color(token::accent().var())
324                .color(token::accent_foreground().var()),
325        )
326}
327
328#[cfg(test)]
329mod tests {
330    use hypersig::Signals;
331    use serde::{Deserialize, Serialize};
332
333    use super::{MultiToggleGroup, ToggleGroup, toggle};
334
335    #[derive(Serialize, Deserialize, Clone, Copy, PartialEq)]
336    enum Size {
337        Small,
338        Large,
339    }
340
341    #[derive(Signals, Serialize, Deserialize)]
342    struct Editor {
343        size: Size,
344        bold: bool,
345        italic: bool,
346        underline: bool,
347    }
348
349    #[test]
350    fn a_toggle_flips_its_flag_on_click() {
351        let html = toggle(Editor::bold()).render();
352        assert!(html.contains(r#"type="button""#));
353        assert!(html.contains("data-hs-on-click"));
354        assert!(html.contains("aria-pressed"));
355    }
356
357    #[test]
358    fn a_single_group_picks_its_value_on_focus() {
359        let html = ToggleGroup::new("Size", Editor::size())
360            .item(Size::Small, "S")
361            .item(Size::Large, "L")
362            .render()
363            .render();
364        assert!(html.contains(r#"data-hs-roving="horizontal""#));
365        assert!(html.contains("data-hs-on-focusin"));
366        assert_eq!(html.matches(r#"role="radio""#).count(), 2);
367    }
368
369    #[test]
370    fn a_multiple_group_keeps_only_its_first_toggle_in_the_tab_order() {
371        let html = MultiToggleGroup::new("Style")
372            .item(Editor::bold(), "B")
373            .item(Editor::italic(), "I")
374            .item(Editor::underline(), "U")
375            .render()
376            .render();
377        assert_eq!(html.matches(r#"tabindex="0""#).count(), 1);
378        assert_eq!(html.matches(r#"tabindex="-1""#).count(), 2);
379    }
380}