1use std::rc::Rc;
4
5use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
6use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
7use ailloli_ui_core::event::{Event, Key, KeyState, NamedKey};
8use ailloli_ui_core::geometry::{Constraints, Rect, Size};
9use ailloli_ui_core::style::{
10 Border, BoxShadow, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius,
11};
12use ailloli_ui_core::{Color, Theme};
13use ailloli_ui_runtime::component::{Binding, IntoView, Memo, Signal, View, Widget};
14use ailloli_ui_runtime::input::{ActivationPolicy, EventCtx, FocusPolicy};
15use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
16use ailloli_ui_runtime::scene::PaintCtx;
17use ailloli_ui_runtime::{DrawBorder, DrawBoxShadow, DrawCmd, DrawRRect};
18
19#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
20pub enum SwitchSize {
29 Compact,
31 #[default]
33 Default,
34}
35
36#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
37pub enum SwitchOrientation {
46 #[default]
48 Horizontal,
49 Vertical,
51}
52
53#[derive(Clone, Debug, PartialEq)]
54pub struct SwitchStyle {
66 pub track_off: Color,
68 pub track_off_hovered: Color,
70 pub track_off_pressed: Color,
72 pub track_on: Color,
74 pub track_on_hovered: Color,
76 pub track_on_pressed: Color,
78 pub thumb: Color,
80 pub thumb_disabled: Color,
82 pub border_off: Border,
84 pub border_on: Border,
86 pub focus_ring: Border,
88 pub shadows: Vec<BoxShadow>,
90 pub width: f32,
92 pub height: f32,
94 pub thumb_size: f32,
96 pub inset: f32,
98 pub track_radius: f32,
100 pub thumb_radius: f32,
102 pub focus_ring_offset: f32,
104 pub disabled_opacity: f32,
106}
107
108impl Default for SwitchStyle {
109 fn default() -> Self {
110 Self::from_theme(Theme::default(), SwitchSize::Default)
111 }
112}
113
114impl SwitchStyle {
115 pub fn from_theme(theme: Theme, size: SwitchSize) -> Self {
129 let palette = theme.palette();
130 let (width, height, thumb_size, inset) = match size {
131 SwitchSize::Compact => (36.0, 20.0, 14.0, 3.0),
132 SwitchSize::Default => (46.0, 26.0, 20.0, 3.0),
133 };
134 Self {
135 track_off: palette.surface_elevated,
136 track_off_hovered: Color::hex_rgb(0x20252A),
137 track_off_pressed: Color::hex_rgb(0x15191D),
138 track_on: palette.accent,
139 track_on_hovered: theme.button_bg_hover,
140 track_on_pressed: theme.button_bg_pressed,
141 thumb: palette.text,
142 thumb_disabled: palette.text_muted,
143 border_off: Border::new(1.0, palette.border),
144 border_on: Border::new(1.0, palette.accent.with_alpha(0.86)),
145 focus_ring: Border::new(2.0, palette.focus),
146 shadows: Vec::new(),
147 width,
148 height,
149 thumb_size,
150 inset,
151 track_radius: height * 0.5,
152 thumb_radius: thumb_size * 0.5,
153 focus_ring_offset: 3.0,
154 disabled_opacity: 0.45,
155 }
156 }
157
158 fn visual_bounds(&self, rect: Rect) -> Rect {
160 let mut bounds = rect;
161 for shadow in &self.shadows {
162 bounds = union_rect(bounds, shadow.paint_bounds(rect));
163 }
164 if self.focus_ring.is_visible() {
165 let inflate = self.focus_ring_offset + max_border_width(self.focus_ring);
166 bounds = union_rect(bounds, rect.inflate(inflate, inflate));
167 }
168 bounds
169 }
170}
171
172type ChangeHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, bool)>;
174
175pub struct Switch<A = ()> {
191 pub(crate) layout: LayoutStyle,
193 pub(crate) flex_item: FlexItemStyle,
195 checked: Binding<bool>,
197 bound: Option<Signal<bool>>,
199 disabled: Binding<bool>,
201 on_change: Option<ChangeHandler<A>>,
203 orientation: SwitchOrientation,
205 style: SwitchStyle,
207}
208
209crate::impl_layout_builders!(Switch);
210
211impl<A: 'static> Default for Switch<A> {
212 fn default() -> Self {
213 Self::new()
214 }
215}
216
217impl<A: 'static> Switch<A> {
218 pub fn new() -> Self {
228 Self {
229 layout: LayoutStyle::default(),
230 flex_item: FlexItemStyle::default(),
231 checked: Binding::Static(false),
232 bound: None,
233 disabled: Binding::Static(false),
234 on_change: None,
235 orientation: SwitchOrientation::Horizontal,
236 style: SwitchStyle::default(),
237 }
238 }
239
240 pub fn checked(mut self, checked: impl Into<Binding<bool>>) -> Self {
254 self.checked = checked.into();
255 self.bound = None;
256 self
257 }
258
259 pub fn bind(mut self, checked: impl Into<Signal<bool>>) -> Self {
275 let signal = checked.into();
276 self.checked = Binding::Signal(signal.clone());
277 self.bound = Some(signal);
278 self
279 }
280
281 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
294 self.disabled = disabled.into();
295 self
296 }
297
298 pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
309 self.disabled(disabled)
310 }
311
312 pub fn switch_style(mut self, style: SwitchStyle) -> Self {
326 self.style = style;
327 self
328 }
329
330 pub fn switch_size(mut self, size: SwitchSize) -> Self {
340 self.style = SwitchStyle::from_theme(Theme::default(), size);
341 self
342 }
343
344 pub fn orientation(mut self, orientation: SwitchOrientation) -> Self {
357 self.orientation = orientation;
358 self
359 }
360
361 pub fn vertical(self) -> Self {
371 self.orientation(SwitchOrientation::Vertical)
372 }
373
374 pub fn on_change(mut self, f: impl Fn(bool) -> A + 'static) -> Self {
388 self.on_change = Some(Rc::new(move |ctx, next| ctx.dispatch(f(next))));
389 self
390 }
391
392 pub fn on_change_ctx(mut self, f: impl Fn(&mut EventCtx<A>, bool) + 'static) -> Self {
405 self.on_change = Some(Rc::new(f));
406 self
407 }
408}
409
410struct SwitchWidget<A> {
412 layout: LayoutStyle,
414 checked: Binding<bool>,
416 bound: Option<Signal<bool>>,
418 disabled: Binding<bool>,
420 on_change: Option<ChangeHandler<A>>,
422 orientation: SwitchOrientation,
424 style: SwitchStyle,
426}
427
428impl<A: 'static> Widget<A> for SwitchWidget<A> {
429 fn debug_name(&self) -> &'static str {
430 "Switch"
431 }
432
433 fn layout(
434 &self,
435 _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
436 _ctx: &mut LayoutCtx<'_>,
437 _children: &mut [LayoutChild],
438 constraints: Constraints,
439 ) -> LayoutResult {
440 let intrinsic = switch_intrinsic_size(&self.style, self.orientation);
441 let size = apply_layout_size(intrinsic, self.layout, constraints);
442 let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
443 LayoutResult {
444 size,
445 children: Vec::new(),
446 paint_bounds,
447 visual_bounds: self.style.visual_bounds(paint_bounds),
448 overlay_hit_bounds: Vec::new(),
449 clip: None,
450 is_window_root_clip: false,
451 artifact: None,
452 }
453 }
454
455 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout_result: &LayoutResult) {
456 let checked = self.checked.read();
457 let disabled = self.disabled.read();
458 paint_switch(
459 ctx,
460 bounds,
461 checked,
462 disabled,
463 self.orientation,
464 &self.style,
465 );
466 }
467
468 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
469 if self.disabled.read() {
470 return;
471 }
472
473 match event {
474 Event::Pointer(PointerEvent::Button {
475 pos,
476 button: MouseButton::Left,
477 pressed: false,
478 ..
479 }) if bounds.contains(pos.x, pos.y) => self.toggle(ctx),
480 Event::Keyboard(key) if key.state == KeyState::Pressed => {
481 if matches!(
482 &key.key,
483 Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space)
484 ) {
485 self.toggle(ctx);
486 }
487 }
488 _ => {}
489 }
490 }
491
492 fn focus_policy(&self) -> FocusPolicy {
493 if self.disabled.read() {
494 FocusPolicy::NotFocusable
495 } else {
496 FocusPolicy::Focusable
497 }
498 }
499
500 fn activation_policy(&self) -> ActivationPolicy {
501 ActivationPolicy::SuppressOnFocusOnly
502 }
503}
504
505impl<A: 'static> SwitchWidget<A> {
506 fn toggle(&self, ctx: &mut EventCtx<A>) {
508 if self.bound.is_none() && self.on_change.is_none() {
509 return;
510 }
511
512 let next = !self.checked.read();
513 if let Some(bound) = &self.bound {
514 bound.set(next);
515 }
516 if let Some(on_change) = &self.on_change {
517 on_change(ctx, next);
518 }
519 ctx.request_repaint();
520 ctx.stop_propagation();
521 }
522}
523
524impl<A: 'static> IntoView<A> for Switch<A> {
525 fn into_view(self) -> View<A> {
526 finish_view_sized(
527 View::leaf(SwitchWidget {
528 layout: self.layout,
529 checked: self.checked,
530 bound: self.bound,
531 disabled: self.disabled,
532 on_change: self.on_change,
533 orientation: self.orientation,
534 style: self.style,
535 }),
536 self.flex_item,
537 LayoutSizeHint::from_layout(self.layout),
538 )
539 }
540}
541
542fn paint_switch(
544 ctx: &mut PaintCtx<'_>,
545 bounds: Rect,
546 checked: bool,
547 disabled: bool,
548 orientation: SwitchOrientation,
549 style: &SwitchStyle,
550) {
551 let interaction = ctx.interaction();
552 let opacity = if disabled {
553 style.disabled_opacity
554 } else {
555 1.0
556 };
557 let track_color = resolve_track_color(style, checked, interaction.hovered, interaction.pressed);
558 let border = if checked {
559 style.border_on
560 } else {
561 style.border_off
562 };
563 let cross_axis = match orientation {
564 SwitchOrientation::Horizontal => bounds.h,
565 SwitchOrientation::Vertical => bounds.w,
566 };
567 let radius = Radius::uniform(style.track_radius.min(cross_axis * 0.5));
568
569 for shadow in style.shadows.iter().copied() {
570 let mut shadow = shadow;
571 shadow.color = apply_opacity(shadow.color, opacity);
572 if shadow.color.a > 0.0 {
573 ctx.push(DrawCmd::BoxShadow(DrawBoxShadow {
574 rect: bounds,
575 radius,
576 shadow,
577 }));
578 }
579 }
580
581 ctx.push(DrawCmd::RRect(DrawRRect {
582 rect: bounds,
583 radius: radius.tl,
584 color: apply_opacity(track_color, opacity),
585 }));
586
587 let border = apply_border_opacity(border, opacity);
588 if border.is_visible() {
589 ctx.push(DrawCmd::Border(DrawBorder {
590 rect: bounds,
591 radius,
592 border,
593 }));
594 }
595
596 let thumb = thumb_rect(bounds, checked, orientation, style);
597 ctx.push(DrawCmd::RRect(DrawRRect {
598 rect: thumb,
599 radius: style.thumb_radius.min(thumb.h * 0.5),
600 color: apply_opacity(
601 if disabled {
602 style.thumb_disabled
603 } else {
604 style.thumb
605 },
606 opacity,
607 ),
608 }));
609
610 if interaction.focused && !disabled && style.focus_ring.is_visible() {
611 ctx.push(DrawCmd::Border(DrawBorder {
612 rect: bounds.inflate(style.focus_ring_offset, style.focus_ring_offset),
613 radius: Radius::uniform(radius.tl + style.focus_ring_offset),
614 border: style.focus_ring,
615 }));
616 }
617}
618
619fn resolve_track_color(style: &SwitchStyle, checked: bool, hovered: bool, pressed: bool) -> Color {
621 match (checked, pressed, hovered) {
622 (true, true, _) => style.track_on_pressed,
623 (true, false, true) => style.track_on_hovered,
624 (true, false, false) => style.track_on,
625 (false, true, _) => style.track_off_pressed,
626 (false, false, true) => style.track_off_hovered,
627 (false, false, false) => style.track_off,
628 }
629}
630
631fn switch_intrinsic_size(style: &SwitchStyle, orientation: SwitchOrientation) -> Size {
633 match orientation {
634 SwitchOrientation::Horizontal => Size::new(style.width, style.height),
635 SwitchOrientation::Vertical => Size::new(style.height, style.width),
636 }
637}
638
639fn thumb_rect(
641 bounds: Rect,
642 checked: bool,
643 orientation: SwitchOrientation,
644 style: &SwitchStyle,
645) -> Rect {
646 match orientation {
647 SwitchOrientation::Horizontal => {
648 let thumb = style
649 .thumb_size
650 .min((bounds.h - style.inset * 2.0).max(0.0));
651 let x = if checked {
652 bounds.right() - style.inset - thumb
653 } else {
654 bounds.x + style.inset
655 };
656 Rect::new(x, bounds.y + (bounds.h - thumb) * 0.5, thumb, thumb)
657 }
658 SwitchOrientation::Vertical => {
659 let thumb = style
660 .thumb_size
661 .min((bounds.w - style.inset * 2.0).max(0.0));
662 let y = if checked {
663 bounds.bottom() - style.inset - thumb
664 } else {
665 bounds.y + style.inset
666 };
667 Rect::new(bounds.x + (bounds.w - thumb) * 0.5, y, thumb, thumb)
668 }
669 }
670}
671
672fn apply_opacity(mut color: Color, opacity: f32) -> Color {
674 color.a = (color.a * opacity).clamp(0.0, 1.0);
675 color
676}
677
678fn apply_border_opacity(mut border: Border, opacity: f32) -> Border {
680 border.colors.left = apply_opacity(border.colors.left, opacity);
681 border.colors.top = apply_opacity(border.colors.top, opacity);
682 border.colors.right = apply_opacity(border.colors.right, opacity);
683 border.colors.bottom = apply_opacity(border.colors.bottom, opacity);
684 border
685}
686
687fn max_border_width(border: Border) -> f32 {
689 border
690 .widths
691 .left
692 .max(border.widths.top)
693 .max(border.widths.right)
694 .max(border.widths.bottom)
695}
696
697fn union_rect(a: Rect, b: Rect) -> Rect {
699 let x0 = a.x.min(b.x);
700 let y0 = a.y.min(b.y);
701 let x1 = a.right().max(b.right());
702 let y1 = a.bottom().max(b.bottom());
703 Rect::new(x0, y0, x1 - x0, y1 - y0)
704}