1use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
4use crate::layout::{Column, Container};
5use crate::text::Text;
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 AlignItems, Border, BoxShadow, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius,
11};
12use ailloli_ui_core::{Color, FontId, IconId, TextStyle, Theme};
13use ailloli_ui_runtime::component::{Binding, IntoView, View, Widget};
14use ailloli_ui_runtime::input::{
15 ActivationPolicy, ClickAction, EventCtx, FocusPolicy, IntoClickAction,
16};
17use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
18use ailloli_ui_runtime::scene::PaintCtx;
19use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawImage, DrawRRect, DrawText};
20use ailloli_ui_text::{PreparedTextLayout, TextLayoutParams, WrapMode};
21use std::sync::Arc;
22
23#[derive(Clone, Debug, PartialEq)]
24pub struct SidebarStyle {
39 pub background: Color,
41 pub border: Border,
43 pub radius: Radius,
45 pub shadows: Vec<BoxShadow>,
47 pub width: f32,
49 pub padding: f32,
51 pub gap: f32,
53 pub title_text: TextStyle,
55}
56
57impl Default for SidebarStyle {
58 fn default() -> Self {
59 Self::from_theme(Theme::default())
60 }
61}
62
63impl SidebarStyle {
64 pub fn from_theme(theme: Theme) -> Self {
76 let palette = theme.palette();
77 Self {
78 background: palette.surface,
79 border: Border::new(1.0, palette.border),
80 radius: theme.radius().panel(),
81 shadows: Vec::new(),
82 width: 220.0,
83 padding: theme.spacing().sm,
84 gap: 4.0,
85 title_text: TextStyle::new(FontId::Ui, 12, palette.text_muted),
86 }
87 }
88}
89
90pub struct Sidebar<A = ()> {
104 pub(crate) layout: LayoutStyle,
106 pub(crate) flex_item: FlexItemStyle,
108 style: SidebarStyle,
110 title: Option<String>,
112 items: Vec<View<A>>,
114}
115
116crate::impl_layout_builders!(Sidebar);
117
118impl<A: 'static> Default for Sidebar<A> {
119 fn default() -> Self {
120 Self::new()
121 }
122}
123
124impl<A: 'static> Sidebar<A> {
125 pub fn new() -> Self {
135 let style = SidebarStyle::default();
136 Self {
137 layout: LayoutStyle::default().width(style.width),
138 flex_item: FlexItemStyle::default(),
139 style,
140 title: None,
141 items: Vec::new(),
142 }
143 }
144
145 pub fn title(mut self, title: impl Into<String>) -> Self {
157 self.title = Some(title.into());
158 self
159 }
160
161 pub fn sidebar_style(mut self, style: SidebarStyle) -> Self {
176 self.layout = self.layout.width(style.width);
177 self.style = style;
178 self
179 }
180
181 pub fn nav_item(mut self, item: NavItem<A>) -> Self {
193 self.items.push(item.fill_width().into_view());
194 self
195 }
196}
197
198impl<A: 'static> IntoView<A> for Sidebar<A> {
199 fn into_view(self) -> View<A> {
200 let mut content = Column::new()
201 .gap(self.style.gap)
202 .align_items(AlignItems::Stretch);
203 if let Some(title) = self.title {
204 content = content.child(
205 Container::new()
206 .padding(6.0)
207 .child(Text::new(title).style(self.style.title_text).fill_width()),
208 );
209 }
210 for item in self.items {
211 content = content.child(item);
212 }
213
214 let mut container = Container::<A>::new()
215 .background(self.style.background)
216 .radius(self.style.radius.tl)
217 .border(self.style.border.widths.top, self.style.border.colors.top)
218 .padding(self.style.padding)
219 .child(content);
220 container.layout = self.layout;
221 container.flex_item = self.flex_item;
222 for shadow in self.style.shadows {
223 container = container.shadow(shadow);
224 }
225 container.into_view()
226 }
227}
228
229#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
230pub enum NavItemVariant {
239 #[default]
241 Default,
242 Danger,
244}
245
246#[derive(Clone, Debug, PartialEq)]
247pub struct NavItemStyle {
259 pub height: f32,
261 pub padding_x: f32,
263 pub gap: f32,
265 pub icon_size: f32,
267 pub radius: Radius,
269 pub background: Color,
271 pub hover_background: Color,
273 pub pressed_background: Color,
275 pub selected_background: Color,
277 pub text: TextStyle,
279 pub selected_text: TextStyle,
281 pub muted_text: TextStyle,
283 pub danger_text: TextStyle,
285 pub icon_tint: Color,
287 pub selected_icon_tint: Color,
289 pub badge_background: Color,
291 pub badge_text: TextStyle,
293 pub focus_ring: Border,
295 pub disabled_opacity: f32,
297}
298
299impl Default for NavItemStyle {
300 fn default() -> Self {
301 Self::from_theme(Theme::default())
302 }
303}
304
305impl NavItemStyle {
306 pub fn from_theme(theme: Theme) -> Self {
318 let palette = theme.palette();
319 Self {
320 height: 34.0,
321 padding_x: 10.0,
322 gap: 8.0,
323 icon_size: 16.0,
324 radius: Radius::uniform(theme.radius().md),
325 background: Color::TRANSPARENT,
326 hover_background: palette.surface_elevated,
327 pressed_background: Color::hex_rgb(0x20252A),
328 selected_background: palette.accent.with_alpha(0.22),
329 text: TextStyle::new(FontId::Ui, 13, palette.text),
330 selected_text: TextStyle::new(FontId::Ui, 13, palette.text),
331 muted_text: TextStyle::new(FontId::Ui, 12, palette.text_muted),
332 danger_text: TextStyle::new(FontId::Ui, 13, palette.danger),
333 icon_tint: palette.text_muted,
334 selected_icon_tint: palette.accent,
335 badge_background: palette.accent,
336 badge_text: TextStyle::new(FontId::Ui, 11, palette.text),
337 focus_ring: Border::new(1.0, palette.focus),
338 disabled_opacity: 0.42,
339 }
340 }
341}
342
343pub struct NavItem<A = ()> {
358 pub(crate) layout: LayoutStyle,
360 pub(crate) flex_item: FlexItemStyle,
362 label: String,
364 leading_icon: Option<IconId>,
366 badge: Option<u32>,
368 selected: Binding<bool>,
370 disabled: Binding<bool>,
372 variant: NavItemVariant,
374 style: NavItemStyle,
376 on_select: Option<ClickAction<A>>,
378}
379
380crate::impl_layout_builders!(NavItem);
381
382impl<A: 'static> NavItem<A> {
383 pub fn new(label: impl Into<String>) -> Self {
393 Self {
394 layout: LayoutStyle::default(),
395 flex_item: FlexItemStyle::default(),
396 label: label.into(),
397 leading_icon: None,
398 badge: None,
399 selected: Binding::Static(false),
400 disabled: Binding::Static(false),
401 variant: NavItemVariant::Default,
402 style: NavItemStyle::default(),
403 on_select: None,
404 }
405 }
406
407 pub fn leading_icon(mut self, icon: IconId) -> Self {
418 self.leading_icon = Some(icon);
419 self
420 }
421
422 pub fn badge(mut self, count: u32) -> Self {
434 self.badge = Some(count);
435 self
436 }
437
438 pub fn selected(mut self, selected: impl Into<Binding<bool>>) -> Self {
451 self.selected = selected.into();
452 self
453 }
454
455 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
468 self.disabled = disabled.into();
469 self
470 }
471
472 pub fn variant(mut self, variant: NavItemVariant) -> Self {
482 self.variant = variant;
483 self
484 }
485
486 pub fn nav_item_style(mut self, style: NavItemStyle) -> Self {
498 self.style = style;
499 self
500 }
501
502 pub fn on_select(mut self, action: impl IntoClickAction<A>) -> Self
517 where
518 A: Clone,
519 {
520 self.on_select = Some(action.into_click_action());
521 self
522 }
523
524 pub fn on_select_ctx(mut self, f: impl Fn(&mut EventCtx<A>) + 'static) -> Self {
534 self.on_select = Some(ClickAction::handler(f));
535 self
536 }
537}
538
539struct NavItemWidget<A> {
541 layout: LayoutStyle,
543 label: String,
545 leading_icon: Option<IconId>,
547 badge: Option<u32>,
549 selected: Binding<bool>,
551 disabled: Binding<bool>,
553 variant: NavItemVariant,
555 style: NavItemStyle,
557 on_select: Option<ClickAction<A>>,
559}
560
561impl<A: 'static> Widget<A> for NavItemWidget<A> {
562 fn debug_name(&self) -> &'static str {
563 "NavItem"
564 }
565
566 fn layout(
567 &self,
568 _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
569 ctx: &mut LayoutCtx<'_>,
570 _children: &mut [LayoutChild],
571 constraints: Constraints,
572 ) -> LayoutResult {
573 let text_w = measure_text(ctx, &self.label, self.text_style(false)).unwrap_or(80.0);
574 let icon_w = self
575 .leading_icon
576 .as_ref()
577 .map(|_| self.style.icon_size + self.style.gap)
578 .unwrap_or(0.0);
579 let badge_w = self
580 .badge
581 .map(|count| measure_badge(ctx, count, &self.style))
582 .unwrap_or(0.0);
583 let intrinsic = Size::new(
584 self.style.padding_x * 2.0 + icon_w + text_w + badge_w,
585 self.style.height,
586 );
587 let size = apply_layout_size(intrinsic, self.layout, constraints);
588 LayoutResult {
589 size,
590 children: Vec::new(),
591 paint_bounds: Rect::new(0.0, 0.0, size.w, size.h),
592 visual_bounds: Rect::new(0.0, 0.0, size.w, size.h),
593 overlay_hit_bounds: Vec::new(),
594 clip: None,
595 is_window_root_clip: false,
596 artifact: None,
597 }
598 }
599
600 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
601 let selected = self.selected.read();
602 let disabled = self.disabled.read();
603 let interaction = ctx.interaction();
604 let mut bg = self.style.background;
605 if selected {
606 bg = self.style.selected_background;
607 } else if interaction.pressed && self.on_select.is_some() && !disabled {
608 bg = self.style.pressed_background;
609 } else if interaction.hovered && self.on_select.is_some() && !disabled {
610 bg = self.style.hover_background;
611 }
612
613 let opacity = if disabled {
614 self.style.disabled_opacity
615 } else {
616 1.0
617 };
618 if bg.a > 0.0 {
619 ctx.push(DrawCmd::RRect(DrawRRect {
620 rect: bounds,
621 radius: self.style.radius.tl,
622 color: bg.with_alpha(bg.a * opacity),
623 }));
624 }
625
626 let mut x = bounds.x + self.style.padding_x;
627 if let Some(icon) = &self.leading_icon {
628 let icon_rect = Rect::new(
629 x,
630 bounds.y + (bounds.h - self.style.icon_size) * 0.5,
631 self.style.icon_size,
632 self.style.icon_size,
633 );
634 let tint = if selected {
635 self.style.selected_icon_tint
636 } else {
637 self.style.icon_tint
638 };
639 ctx.push(DrawCmd::Image(DrawImage {
640 rect: icon_rect,
641 icon: icon.clone(),
642 tint: tint.with_alpha(tint.a * opacity),
643 rotation_rad: 0.0,
644 }));
645 x += self.style.icon_size + self.style.gap;
646 }
647
648 let text_style = self.text_style(selected);
649 paint_text_centered(ctx, &self.label, text_style, bounds, x, opacity);
650
651 if let Some(count) = self.badge {
652 paint_badge(ctx, count, bounds, &self.style, opacity);
653 }
654
655 if interaction.focused && self.on_select.is_some() && !disabled {
656 ctx.push(DrawCmd::Border(DrawBorder {
657 rect: bounds,
658 radius: self.style.radius,
659 border: self.style.focus_ring,
660 }));
661 }
662 }
663
664 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
665 if self.disabled.read() {
666 return;
667 }
668 match event {
669 Event::Pointer(PointerEvent::Button {
670 pos,
671 button: MouseButton::Left,
672 pressed: false,
673 ..
674 }) if bounds.contains(pos.x, pos.y) => self.run_action(ctx),
675 Event::Keyboard(key) if key.state == KeyState::Pressed => {
676 if matches!(
677 &key.key,
678 Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space)
679 ) {
680 self.run_action(ctx);
681 }
682 }
683 _ => {}
684 }
685 }
686
687 fn focus_policy(&self) -> FocusPolicy {
688 if self.on_select.is_some() && !self.disabled.read() {
689 FocusPolicy::Focusable
690 } else {
691 FocusPolicy::NotFocusable
692 }
693 }
694
695 fn activation_policy(&self) -> ActivationPolicy {
696 ActivationPolicy::SuppressOnFocusOnly
697 }
698}
699
700impl<A> NavItemWidget<A> {
701 fn run_action(&self, ctx: &mut EventCtx<A>) {
703 if let Some(on_select) = &self.on_select {
704 on_select.run(ctx);
705 ctx.stop_propagation();
706 }
707 }
708
709 fn text_style(&self, selected: bool) -> TextStyle {
711 if self.variant == NavItemVariant::Danger {
712 self.style.danger_text
713 } else if selected {
714 self.style.selected_text
715 } else {
716 self.style.text
717 }
718 }
719}
720
721impl<A: 'static> IntoView<A> for NavItem<A> {
722 fn into_view(self) -> View<A> {
723 finish_view_sized(
724 View::leaf(NavItemWidget {
725 layout: self.layout,
726 label: self.label,
727 leading_icon: self.leading_icon,
728 badge: self.badge,
729 selected: self.selected,
730 disabled: self.disabled,
731 variant: self.variant,
732 style: self.style,
733 on_select: self.on_select,
734 }),
735 self.flex_item,
736 LayoutSizeHint::from_layout(self.layout),
737 )
738 }
739}
740
741fn measure_text(ctx: &mut LayoutCtx<'_>, text: &str, style: TextStyle) -> Option<f32> {
743 ctx.text_system.as_deref_mut().map(|text_system| {
744 text_system
745 .layout_cached(TextLayoutParams {
746 text,
747 style,
748 max_width: None,
749 wrap_mode: WrapMode::NoWrap,
750 })
751 .metrics
752 .width
753 })
754}
755
756fn layout_text(
758 ctx: &mut PaintCtx<'_>,
759 text: &str,
760 style: TextStyle,
761) -> Option<Arc<PreparedTextLayout>> {
762 ctx.text_system.as_deref_mut().map(|text_system| {
763 text_system.layout_cached(TextLayoutParams {
764 text,
765 style,
766 max_width: None,
767 wrap_mode: WrapMode::NoWrap,
768 })
769 })
770}
771
772fn paint_text_centered(
774 ctx: &mut PaintCtx<'_>,
775 text: &str,
776 style: TextStyle,
777 bounds: Rect,
778 x: f32,
779 opacity: f32,
780) {
781 let Some(layout) = layout_text(ctx, text, style) else {
782 return;
783 };
784 let baseline = layout
785 .lines
786 .first()
787 .map(|line| line.baseline_y)
788 .unwrap_or(0.0);
789 let y = bounds.y + (bounds.h - layout.metrics.height) * 0.5 + baseline;
790 ctx.push(DrawCmd::Text(DrawText {
791 pos: [x, y],
792 color: style.color.with_alpha(style.color.a * opacity),
793 decoration: ailloli_ui_core::TextDecoration::None,
794 layout,
795 }));
796}
797
798fn measure_badge(ctx: &mut LayoutCtx<'_>, count: u32, style: &NavItemStyle) -> f32 {
800 let label = count.to_string();
801 let text_w = measure_text(ctx, &label, style.badge_text).unwrap_or(8.0);
802 text_w.max(8.0) + 16.0
803}
804
805fn paint_badge(
807 ctx: &mut PaintCtx<'_>,
808 count: u32,
809 bounds: Rect,
810 style: &NavItemStyle,
811 opacity: f32,
812) {
813 let label = count.to_string();
814 let Some(layout) = layout_text(ctx, &label, style.badge_text) else {
815 return;
816 };
817 let w = (layout.metrics.width + 12.0).max(20.0);
818 let h = 18.0;
819 let rect = Rect::new(
820 bounds.right() - style.padding_x - w,
821 bounds.y + (bounds.h - h) * 0.5,
822 w,
823 h,
824 );
825 ctx.push(DrawCmd::RRect(DrawRRect {
826 rect,
827 radius: h * 0.5,
828 color: style
829 .badge_background
830 .with_alpha(style.badge_background.a * opacity),
831 }));
832 let baseline = layout
833 .lines
834 .first()
835 .map(|line| line.baseline_y)
836 .unwrap_or(0.0);
837 let x = rect.x + (rect.w - layout.metrics.width) * 0.5;
838 let y = rect.y + (rect.h - layout.metrics.height) * 0.5 + baseline;
839 ctx.push(DrawCmd::Text(DrawText {
840 pos: [x, y],
841 color: style
842 .badge_text
843 .color
844 .with_alpha(style.badge_text.color.a * opacity),
845 decoration: ailloli_ui_core::TextDecoration::None,
846 layout,
847 }));
848}