1use 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#[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#[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
68fn 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#[derive(Debug)]
113pub struct ToggleGroup<S, T> {
114 label: String,
115 selected: Sig<S, T>,
116 items: Vec<(T, El<S>)>,
118}
119
120impl<S, T: Serialize + PartialEq> ToggleGroup<S, T> {
121 #[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 #[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 #[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 #[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#[derive(Debug)]
212pub struct MultiToggleGroup<S> {
213 label: String,
214 items: Vec<El<S>>,
215}
216
217impl<S> MultiToggleGroup<S> {
218 #[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 #[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 #[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 #[must_use]
249 pub fn render(self) -> El<S> {
250 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
315fn 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}