1use iced::keyboard::key::Named;
13use iced::widget::{self, button::Status, row, text};
14use iced::{Alignment, Background, Border, Color, Element, Length, Padding, Shadow};
15
16use crate::after_touch::after_touch;
17use crate::focus::{Ring, focusable};
18use crate::icon::{Glyph, opacity, themed};
19use crate::keys::{self, Chord, Keymap};
20use crate::natural::natural;
21use crate::theme::{Tokens, fade, mix, radius, text_size};
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
25pub enum Variant {
26 #[default]
28 Default,
29 Outline,
31}
32
33impl Variant {
34 pub const ALL: [Variant; 2] = [Variant::Default, Variant::Outline];
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
39pub enum Size {
40 Sm,
41 #[default]
42 Md,
43 Lg,
44}
45
46impl Size {
47 pub const ALL: [Size; 3] = [Size::Sm, Size::Md, Size::Lg];
48
49 pub const fn metrics(self) -> Metrics {
51 match self {
52 Size::Sm => Metrics {
53 height: 32.0,
54 padding_x: 10.0,
55 text: text_size::SM,
56 icon: 14.0,
57 },
58 Size::Md => Metrics {
59 height: 36.0,
60 padding_x: 12.0,
61 text: text_size::SM,
62 icon: 16.0,
63 },
64 Size::Lg => Metrics {
65 height: 40.0,
66 padding_x: 16.0,
67 text: text_size::MD,
68 icon: 18.0,
69 },
70 }
71 }
72}
73
74#[derive(Debug, Clone, Copy, PartialEq)]
76pub struct Metrics {
77 pub height: f32,
78 pub padding_x: f32,
79 pub text: f32,
80 pub icon: f32,
81}
82
83pub struct Toggle<'a, Message> {
87 label: text::Fragment<'a>,
88 icon: Option<Glyph>,
89 pressed: bool,
90 variant: Variant,
91 size: Size,
92 on_toggle: Option<Box<dyn Fn(bool) -> Message + 'a>>,
93}
94
95pub fn toggle<'a, Message>(label: impl text::IntoFragment<'a>) -> Toggle<'a, Message> {
97 Toggle {
98 label: label.into_fragment(),
99 icon: None,
100 pressed: false,
101 variant: Variant::default(),
102 size: Size::default(),
103 on_toggle: None,
104 }
105}
106
107impl<Message> std::fmt::Debug for Toggle<'_, Message> {
108 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109 f.debug_struct("Toggle")
110 .field("label", &self.label)
111 .field("icon", &self.icon)
112 .field("pressed", &self.pressed)
113 .field("variant", &self.variant)
114 .field("size", &self.size)
115 .field("enabled", &self.on_toggle.is_some())
116 .finish()
117 }
118}
119
120impl<'a, Message> Toggle<'a, Message> {
121 pub fn icon(mut self, glyph: Glyph) -> Self {
123 self.icon = Some(glyph);
124 self
125 }
126
127 pub fn pressed(mut self, pressed: bool) -> Self {
129 self.pressed = pressed;
130 self
131 }
132
133 pub fn variant(mut self, variant: Variant) -> Self {
134 self.variant = variant;
135 self
136 }
137
138 pub fn size(mut self, size: Size) -> Self {
139 self.size = size;
140 self
141 }
142
143 pub fn on_toggle(mut self, on_toggle: impl Fn(bool) -> Message + 'a) -> Self {
145 self.on_toggle = Some(Box::new(on_toggle));
146 self
147 }
148
149 pub fn on_toggle_maybe(mut self, on_toggle: Option<impl Fn(bool) -> Message + 'a>) -> Self {
151 self.on_toggle = on_toggle.map(|f| Box::new(f) as Box<dyn Fn(bool) -> Message + 'a>);
152 self
153 }
154
155 pub fn is_pressed(&self) -> bool {
156 self.pressed
157 }
158
159 pub fn is_enabled(&self) -> bool {
160 self.on_toggle.is_some()
161 }
162}
163
164impl<'a, Message: Clone + 'a> From<Toggle<'a, Message>> for Element<'a, Message> {
165 fn from(toggle: Toggle<'a, Message>) -> Self {
166 let Toggle {
167 label,
168 icon,
169 pressed,
170 variant,
171 size,
172 on_toggle,
173 } = toggle;
174 let message = on_toggle.map(|on_toggle| on_toggle(!pressed));
175 #[cfg(feature = "icedwright")]
176 let (name, enabled) = (label.clone(), message.is_some());
177 let on_activate = message
178 .clone()
179 .map(|message| Box::new(move || message.clone()) as Box<dyn Fn() -> Message + 'a>);
180 let control = natural(button(
181 label,
182 icon,
183 pressed,
184 size.metrics(),
185 Length::Shrink,
186 message,
187 move |tokens, status| style(tokens, variant, pressed, status),
188 ));
189 let element: Element<'a, Message> =
190 focusable(control, on_activate, Ring::around(radius::MD)).into();
191 #[cfg(feature = "icedwright")]
192 let element = annotate(element, name, pressed, enabled, "iced_cube::toggle");
193 element
194 }
195}
196
197#[cfg(feature = "icedwright")]
199pub(crate) fn annotate<'a, Message: 'a>(
200 element: Element<'a, Message>,
201 name: text::Fragment<'a>,
202 pressed: bool,
203 enabled: bool,
204 kind: &'static str,
205) -> Element<'a, Message> {
206 use icedwright_probe::{role, semantic};
207 semantic(element)
208 .role(role::ToggleButton)
209 .name(name)
210 .pressed(pressed)
211 .disabled(!enabled)
212 .component(kind)
213 .into()
214}
215
216pub(crate) fn button<'a, Message: Clone + 'a>(
220 label: impl text::IntoFragment<'a>,
221 icon: Option<Glyph>,
222 pressed: bool,
223 metrics: Metrics,
224 width: Length,
225 message: Option<Message>,
226 style: impl Fn(&Tokens, Status) -> widget::button::Style + 'a,
227) -> Element<'a, Message> {
228 let enabled = message.is_some();
229 let resting = if enabled {
230 Status::Active
231 } else {
232 Status::Disabled
233 };
234
235 let mut content = row![].spacing(6).align_y(Alignment::Center);
236 if let Some(glyph) = icon {
237 content = content.push(themed(
238 glyph,
239 metrics.icon,
240 opacity(enabled),
241 move |theme| colours(&Tokens::of(theme), pressed, resting).foreground,
242 ));
243 }
244 content = content.push(
245 text(label)
246 .size(metrics.text)
247 .wrapping(text::Wrapping::None),
248 );
249
250 let inner = widget::container(content)
251 .height(Length::Fill)
252 .align_y(Alignment::Center);
253 let inner = if width == Length::Shrink {
254 inner
255 } else {
256 inner.width(Length::Fill).align_x(Alignment::Center)
257 };
258 after_touch(
259 widget::button(inner)
260 .width(width)
261 .height(Length::Fixed(metrics.height))
262 .padding(Padding::from([0.0, metrics.padding_x]))
263 .on_press_maybe(message)
264 .style(move |theme, status| style(&Tokens::of(theme), status)),
265 )
266}
267
268#[derive(Debug, Clone, Copy, PartialEq)]
270pub struct Colours {
271 pub background: Option<Color>,
272 pub foreground: Color,
273}
274
275pub fn colours(tokens: &Tokens, pressed: bool, status: Status) -> Colours {
280 let hover = matches!(status, Status::Hovered | Status::Pressed);
281 let colours = match (pressed, hover) {
282 (true, false) => Colours {
283 background: Some(tokens.accent),
284 foreground: tokens.accent_foreground,
285 },
286 (true, true) => Colours {
287 background: Some(mix(tokens.accent, tokens.foreground, 0.08)),
288 foreground: tokens.accent_foreground,
289 },
290 (false, true) => Colours {
291 background: Some(mix(tokens.background, tokens.accent, 0.5)),
292 foreground: tokens.muted_foreground,
293 },
294 (false, false) => Colours {
295 background: None,
296 foreground: tokens.muted_foreground,
297 },
298 };
299
300 if status != Status::Disabled {
301 return colours;
302 }
303 Colours {
304 background: colours.background.map(|c| fade(c, 0.5)),
305 foreground: fade(colours.foreground, 0.5),
306 }
307}
308
309pub fn style(
311 tokens: &Tokens,
312 variant: Variant,
313 pressed: bool,
314 status: Status,
315) -> widget::button::Style {
316 let colours = colours(tokens, pressed, status);
317 let outline = variant == Variant::Outline;
318 let border = if status == Status::Disabled {
319 fade(tokens.border, 0.5)
320 } else {
321 tokens.border
322 };
323 widget::button::Style {
324 background: colours.background.map(Background::Color),
325 text_color: colours.foreground,
326 border: Border {
327 color: if outline { border } else { Color::TRANSPARENT },
328 width: if outline { 1.0 } else { 0.0 },
329 radius: radius::MD.into(),
330 },
331 shadow: Shadow::default(),
332 snap: true,
333 }
334}
335
336#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
338pub enum Action {
339 Toggle,
340}
341
342impl Action {
343 pub fn apply(self, pressed: bool) -> bool {
345 match self {
346 Action::Toggle => !pressed,
347 }
348 }
349}
350
351impl keys::Action for Action {
352 const ALL: &'static [Self] = &[Action::Toggle];
353
354 fn defaults() -> Keymap<Self> {
355 default_keymap()
356 }
357
358 fn name(self) -> &'static str {
359 match self {
360 Action::Toggle => "Toggle",
361 }
362 }
363
364 fn description(self) -> &'static str {
365 match self {
366 Action::Toggle => "Switches the toggle on or off.",
367 }
368 }
369}
370
371pub fn default_keymap() -> Keymap<Action> {
380 Keymap::new().bind(Chord::named(Named::Space), Action::Toggle)
381}
382
383#[cfg(test)]
384mod tests {
385 use super::*;
386 use crate::theme::{dark, light};
387
388 const STATES: [Status; 4] = [
389 Status::Active,
390 Status::Hovered,
391 Status::Pressed,
392 Status::Disabled,
393 ];
394
395 #[test]
396 fn defaults_to_an_off_medium_toggle_that_is_disabled() {
397 let t: Toggle<'_, bool> = toggle("Bold");
398 assert_eq!(t.variant, Variant::Default);
399 assert_eq!(t.size, Size::Md);
400 assert!(t.icon.is_none());
401 assert!(!t.is_pressed());
402 assert!(!t.is_enabled());
403 }
404
405 #[test]
406 fn builder_sets_every_option() {
407 let t = toggle("Grid")
408 .icon(crate::lucide!(Grid3x3))
409 .pressed(true)
410 .variant(Variant::Outline)
411 .size(Size::Lg)
412 .on_toggle(|on| on);
413 assert_eq!(t.icon.map(Glyph::name), Some("grid-3x3"));
414 assert!(t.is_pressed());
415 assert!(t.is_enabled());
416 assert_eq!(t.variant, Variant::Outline);
417 assert!(
418 !toggle("Grid")
419 .on_toggle_maybe(None::<fn(bool) -> bool>)
420 .is_enabled()
421 );
422 assert!(
423 toggle("Grid")
424 .on_toggle_maybe(Some(|on: bool| on))
425 .is_enabled()
426 );
427 assert_eq!(t.size, Size::Lg);
428 }
429
430 #[test]
431 fn sizes_grow_monotonically() {
432 let heights = Size::ALL.map(|size| size.metrics().height);
433 assert!(heights.windows(2).all(|w| w[0] < w[1]));
434 let icons = Size::ALL.map(|size| size.metrics().icon);
435 assert!(icons.windows(2).all(|w| w[0] < w[1]));
436 }
437
438 #[test]
439 fn on_takes_the_accent_and_off_is_transparent_at_rest() {
440 for theme in [light(), dark()] {
441 let tokens = Tokens::of(&theme);
442 let on = colours(&tokens, true, Status::Active);
443 let off = colours(&tokens, false, Status::Active);
444 assert_eq!(on.background, Some(tokens.accent));
445 assert_eq!(on.foreground, tokens.accent_foreground);
446 assert_eq!(off.background, None);
447 assert_eq!(off.foreground, tokens.muted_foreground);
448 }
449 }
450
451 #[test]
452 fn hover_changes_the_background_on_and_off() {
453 for theme in [light(), dark()] {
454 let tokens = Tokens::of(&theme);
455 for pressed in [false, true] {
456 let rest = colours(&tokens, pressed, Status::Active);
457 for status in [Status::Hovered, Status::Pressed] {
458 let hovered = colours(&tokens, pressed, status);
459 assert_ne!(hovered.background, rest.background, "{pressed} {status:?}");
460 assert!(hovered.background.is_some());
461 }
462 }
463 }
464 }
465
466 fn distance(a: Color, b: Color) -> f32 {
467 (a.r - b.r).abs() + (a.g - b.g).abs() + (a.b - b.b).abs()
468 }
469
470 #[test]
471 fn hovering_an_off_toggle_is_lighter_than_pressing_it() {
472 for theme in [light(), dark()] {
473 let tokens = Tokens::of(&theme);
474 let pressed = colours(&tokens, true, Status::Active);
475 let hovered = colours(&tokens, false, Status::Hovered);
476 let (Some(pressed_fill), Some(hovered_fill)) = (pressed.background, hovered.background)
477 else {
478 panic!("both fill");
479 };
480 let pressed_lift = distance(pressed_fill, tokens.background);
481 let hovered_lift = distance(hovered_fill, tokens.background);
482 assert!(hovered_lift > 0.0, "{}", tokens.is_dark);
483 assert!(hovered_lift < pressed_lift * 0.6, "{}", tokens.is_dark);
484 assert_ne!(hovered.foreground, pressed.foreground);
485 assert_eq!(hovered.foreground, tokens.muted_foreground);
486 }
487 }
488
489 #[test]
490 fn on_and_off_differ_in_every_enabled_state() {
491 let tokens = Tokens::of(&light());
492 for status in [Status::Active, Status::Hovered, Status::Pressed] {
493 assert_ne!(
494 colours(&tokens, true, status),
495 colours(&tokens, false, status),
496 "{status:?}"
497 );
498 }
499 }
500
501 #[test]
502 fn disabled_keeps_the_look_at_half_alpha() {
503 for theme in [light(), dark()] {
504 let tokens = Tokens::of(&theme);
505 for pressed in [false, true] {
506 let rest = colours(&tokens, pressed, Status::Active);
507 let disabled = colours(&tokens, pressed, Status::Disabled);
508 assert!((disabled.foreground.a - rest.foreground.a * 0.5).abs() < 1e-6);
509 assert_eq!(
510 disabled.background.map(|c| c.a),
511 rest.background.map(|c| c.a * 0.5)
512 );
513 }
514 }
515 }
516
517 #[test]
518 fn only_outline_has_a_border_in_every_state() {
519 let tokens = Tokens::of(&dark());
520 for variant in Variant::ALL {
521 for pressed in [false, true] {
522 for status in STATES {
523 let style = style(&tokens, variant, pressed, status);
524 assert_eq!(style.border.width > 0.0, variant == Variant::Outline);
525 assert_eq!(style.border.radius, radius::MD.into());
526 }
527 }
528 }
529 }
530
531 #[test]
532 fn toggle_action_flips_the_state() {
533 assert!(Action::Toggle.apply(false));
534 assert!(!Action::Toggle.apply(true));
535 }
536
537 #[test]
538 fn default_keymap_and_overrides() {
539 let space = iced::keyboard::Key::Named(Named::Space);
540 let keymap = default_keymap();
541 assert_eq!(
542 keymap.resolve(&space, Default::default()),
543 Some(Action::Toggle)
544 );
545 assert_eq!(Keymap::<Action>::defaults(), keymap);
546
547 let bold: Chord = "Ctrl+B".parse().unwrap();
548 let custom = keymap
549 .unbind(&Chord::named(Named::Space))
550 .bind(bold.clone(), Action::Toggle);
551 assert_eq!(custom.resolve(&space, Default::default()), None);
552 assert_eq!(
553 custom.resolve(bold.key(), bold.modifiers()),
554 Some(Action::Toggle)
555 );
556 assert!(custom.unbind_action(&Action::Toggle).is_empty());
557 }
558}