1use std::rc::Rc;
4
5use crate::layout::layout_ext::{apply_layout_size, finish_view_sized, LayoutExt};
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::{Border, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius};
10use ailloli_ui_core::{Color, FontId, IconId, TextStyle, Theme};
11use ailloli_ui_runtime::component::{Binding, IntoView, Memo, Signal, View, Widget};
12use ailloli_ui_runtime::input::{EventCtx, FocusPolicy};
13use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
14use ailloli_ui_runtime::scene::PaintCtx;
15use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawImage, DrawRRect, DrawRect, DrawText};
16use ailloli_ui_text::{TextLayoutParams, TextSystem, WrapMode};
17
18#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
19pub enum SegmentedSize {
30 Compact,
32 #[default]
34 Default,
35}
36
37#[derive(Clone, Debug, PartialEq)]
38pub struct SegmentedStyle {
53 pub background: Color,
55 pub background_hovered: Color,
57 pub background_pressed: Color,
59 pub selected_background: Color,
61 pub selected_background_hovered: Color,
63 pub selected_background_pressed: Color,
65 pub border: Border,
67 pub focus_ring: Border,
69 pub divider_color: Color,
71 pub text: TextStyle,
73 pub selected_text: TextStyle,
75 pub disabled_text: TextStyle,
77 pub icon_tint: Color,
79 pub selected_icon_tint: Color,
81 pub disabled_icon_tint: Color,
83 pub height: f32,
85 pub radius: Radius,
87 pub segment_padding_x: f32,
89 pub min_segment_width: f32,
91 pub icon_size: f32,
93 pub icon_gap: f32,
95 pub focus_ring_offset: f32,
97 pub disabled_opacity: f32,
99}
100
101impl Default for SegmentedStyle {
102 fn default() -> Self {
103 Self::from_theme(Theme::default(), SegmentedSize::Default)
104 }
105}
106
107impl SegmentedStyle {
108 pub fn from_theme(theme: Theme, size: SegmentedSize) -> Self {
120 let palette = theme.palette();
121 let (height, padding, min_width, icon_size, text_size) = match size {
122 SegmentedSize::Compact => (28.0, 10.0, 56.0, 14.0, 12),
123 SegmentedSize::Default => (34.0, 12.0, 72.0, 14.0, 13),
124 };
125 let text = TextStyle::new(FontId::Ui, text_size, palette.text);
126 let disabled = TextStyle::new(FontId::Ui, text_size, palette.text_muted.with_alpha(0.70));
127 Self {
128 background: palette.surface_elevated,
129 background_hovered: Color::hex_rgb(0x20252A),
130 background_pressed: Color::hex_rgb(0x15191D),
131 selected_background: palette.accent,
132 selected_background_hovered: theme.button_bg_hover,
133 selected_background_pressed: theme.button_bg_pressed,
134 border: Border::new(1.0, palette.border),
135 focus_ring: Border::new(2.0, palette.focus),
136 divider_color: palette.border,
137 text,
138 selected_text: text,
139 disabled_text: disabled,
140 icon_tint: palette.text_muted,
141 selected_icon_tint: palette.text,
142 disabled_icon_tint: palette.text_muted.with_alpha(0.62),
143 height,
144 radius: Radius::uniform(theme.radius().md),
145 segment_padding_x: padding,
146 min_segment_width: min_width,
147 icon_size,
148 icon_gap: 6.0,
149 focus_ring_offset: 3.0,
150 disabled_opacity: 0.45,
151 }
152 }
153
154 fn visual_bounds(&self, rect: Rect) -> Rect {
156 if self.focus_ring.is_visible() {
157 let inflate = self.focus_ring_offset + max_border_width(self.focus_ring);
158 rect.inflate(inflate, inflate)
159 } else {
160 rect
161 }
162 }
163}
164
165#[derive(Clone)]
166pub struct SegmentedOption<T> {
180 value: T,
182 label: String,
184 icon: Option<IconId>,
186 disabled: Binding<bool>,
188}
189
190impl<T> SegmentedOption<T> {
191 pub fn new(value: T, label: impl Into<String>) -> Self {
201 Self {
202 value,
203 label: label.into(),
204 icon: None,
205 disabled: Binding::Static(false),
206 }
207 }
208
209 pub fn leading_icon(mut self, icon: IconId) -> Self {
220 self.icon = Some(icon);
221 self
222 }
223
224 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
237 self.disabled = disabled.into();
238 self
239 }
240
241 pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
252 self.disabled(disabled)
253 }
254}
255
256type ChangeHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, T)>;
258
259pub struct SegmentedControl<T, A = ()> {
277 pub(crate) layout: LayoutStyle,
279 pub(crate) flex_item: FlexItemStyle,
281 options: Vec<SegmentedOption<T>>,
283 selected: Option<Binding<T>>,
285 bound: Option<Signal<T>>,
287 disabled: Binding<bool>,
289 on_change: Option<ChangeHandler<T, A>>,
291 style: SegmentedStyle,
293}
294
295impl<T: Clone + PartialEq + 'static, A: 'static> Default for SegmentedControl<T, A> {
296 fn default() -> Self {
297 Self::new()
298 }
299}
300
301impl<T: Clone + PartialEq + 'static, A: 'static> LayoutExt for SegmentedControl<T, A> {
302 fn layout_mut(&mut self) -> &mut LayoutStyle {
303 &mut self.layout
304 }
305}
306
307impl<T: Clone + PartialEq + 'static, A: 'static> SegmentedControl<T, A> {
308 pub fn new() -> Self {
321 Self {
322 layout: LayoutStyle::default(),
323 flex_item: FlexItemStyle::default(),
324 options: Vec::new(),
325 selected: None,
326 bound: None,
327 disabled: Binding::Static(false),
328 on_change: None,
329 style: SegmentedStyle::default(),
330 }
331 }
332
333 pub fn option(mut self, value: T, label: impl Into<String>) -> Self {
343 self.options.push(SegmentedOption::new(value, label));
344 self
345 }
346
347 pub fn segmented_option(mut self, option: SegmentedOption<T>) -> Self {
358 self.options.push(option);
359 self
360 }
361
362 pub fn selected(mut self, selected: impl Into<Binding<T>>) -> Self {
375 self.selected = Some(selected.into());
376 self.bound = None;
377 self
378 }
379
380 pub fn bind(mut self, selected: impl Into<Signal<T>>) -> Self {
393 let signal = selected.into();
394 self.selected = Some(Binding::Signal(signal.clone()));
395 self.bound = Some(signal);
396 self
397 }
398
399 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
411 self.disabled = disabled.into();
412 self
413 }
414
415 pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
426 self.disabled(disabled)
427 }
428
429 pub fn segmented_style(mut self, style: SegmentedStyle) -> Self {
439 self.style = style;
440 self
441 }
442
443 pub fn segmented_size(mut self, size: SegmentedSize) -> Self {
453 self.style = SegmentedStyle::from_theme(Theme::default(), size);
454 self
455 }
456
457 pub fn on_change(mut self, f: impl Fn(T) -> A + 'static) -> Self {
472 self.on_change = Some(Rc::new(move |ctx, next| ctx.dispatch(f(next))));
473 self
474 }
475
476 pub fn on_change_ctx(mut self, f: impl Fn(&mut EventCtx<A>, T) + 'static) -> Self {
488 self.on_change = Some(Rc::new(f));
489 self
490 }
491
492 pub fn width(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
501 self.layout.width = value.into();
502 self
503 }
504
505 pub fn height(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
514 self.layout.height = value.into();
515 self
516 }
517
518 pub fn min_width(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
527 self.layout.min_width = value.into();
528 self
529 }
530
531 pub fn max_width(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
540 self.layout.max_width = value.into();
541 self
542 }
543
544 pub fn min_height(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
553 self.layout.min_height = value.into();
554 self
555 }
556
557 pub fn max_height(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
566 self.layout.max_height = value.into();
567 self
568 }
569
570 pub fn fill(mut self) -> Self {
579 self.layout.width = ailloli_ui_core::style::Length::Fill;
580 self.layout.height = ailloli_ui_core::style::Length::Fill;
581 self
582 }
583
584 pub fn fill_width(mut self) -> Self {
593 self.layout.width = ailloli_ui_core::style::Length::Fill;
594 self
595 }
596
597 pub fn fill_height(mut self) -> Self {
606 self.layout.height = ailloli_ui_core::style::Length::Fill;
607 self
608 }
609
610 pub fn margin(mut self, value: f32) -> Self {
619 self.layout = self.layout.margin(value);
620 self
621 }
622
623 pub fn padding(mut self, value: f32) -> Self {
634 self.layout = self.layout.padding(value);
635 self
636 }
637
638 pub fn flex_grow(mut self) -> Self {
647 self.flex_item = self.flex_item.flex_grow(1.0);
648 self
649 }
650
651 pub fn flex_grow_by(mut self, value: f32) -> Self {
660 self.flex_item = self.flex_item.flex_grow(value);
661 self
662 }
663
664 pub fn flex_shrink(mut self, value: f32) -> Self {
673 self.flex_item = self.flex_item.flex_shrink(value);
674 self
675 }
676
677 pub fn flex_basis(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
686 self.flex_item = self.flex_item.flex_basis(value);
687 self
688 }
689
690 pub fn align_self(mut self, value: ailloli_ui_core::style::AlignItems) -> Self {
700 self.flex_item = self.flex_item.align_self(value);
701 self
702 }
703}
704
705struct SegmentedWidget<T, A> {
707 layout: LayoutStyle,
709 options: Vec<SegmentedOption<T>>,
711 selected: Option<Binding<T>>,
713 bound: Option<Signal<T>>,
715 disabled: Binding<bool>,
717 on_change: Option<ChangeHandler<T, A>>,
719 style: SegmentedStyle,
721}
722
723#[derive(Debug, Clone, Copy)]
724struct SegmentPaintState {
726 selected: bool,
728 disabled: bool,
730}
731
732impl<T: Clone + PartialEq + 'static, A: 'static> Widget<A> for SegmentedWidget<T, A> {
733 fn debug_name(&self) -> &'static str {
734 "SegmentedControl"
735 }
736
737 fn layout(
738 &self,
739 _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
740 ctx: &mut LayoutCtx<'_>,
741 _children: &mut [LayoutChild],
742 constraints: Constraints,
743 ) -> LayoutResult {
744 let intrinsic =
745 segmented_intrinsic_size(&self.options, &self.style, ctx.text_system.as_deref_mut());
746 let size = apply_layout_size(intrinsic, self.layout, constraints);
747 let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
748 LayoutResult {
749 size,
750 children: Vec::new(),
751 paint_bounds,
752 visual_bounds: self.style.visual_bounds(paint_bounds),
753 overlay_hit_bounds: Vec::new(),
754 clip: None,
755 is_window_root_clip: false,
756 artifact: None,
757 }
758 }
759
760 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout_result: &LayoutResult) {
761 let disabled = self.disabled.read();
762 let selected = self.selected_value();
763 let selected_index = self.selected_index(selected.as_ref());
764 let segment_rects = segment_rects(bounds, self.options.len());
765 let interaction = ctx.interaction();
766
767 paint_background(
768 ctx,
769 bounds,
770 disabled,
771 interaction.hovered,
772 interaction.pressed,
773 &self.style,
774 );
775
776 if let Some(index) = selected_index {
777 if let Some(rect) = segment_rects.get(index).copied() {
778 paint_selected_segment(
779 ctx,
780 rect,
781 disabled || self.options[index].disabled.read(),
782 &self.style,
783 );
784 }
785 }
786
787 paint_dividers(ctx, bounds, self.options.len(), &self.style);
788
789 for (idx, option) in self.options.iter().enumerate() {
790 let option_disabled = disabled || option.disabled.read();
791 let option_selected = selected_index == Some(idx);
792 paint_segment_content(
793 ctx,
794 segment_rects[idx],
795 option,
796 SegmentPaintState {
797 selected: option_selected,
798 disabled: option_disabled,
799 },
800 &self.style,
801 );
802 }
803
804 if self.style.border.is_visible() {
805 ctx.push(DrawCmd::Border(DrawBorder {
806 rect: bounds,
807 radius: self.style.radius,
808 border: apply_border_opacity(
809 self.style.border,
810 if disabled {
811 self.style.disabled_opacity
812 } else {
813 1.0
814 },
815 ),
816 }));
817 }
818
819 if interaction.focused && !disabled && self.style.focus_ring.is_visible() {
820 ctx.push(DrawCmd::Border(DrawBorder {
821 rect: bounds.inflate(self.style.focus_ring_offset, self.style.focus_ring_offset),
822 radius: Radius::uniform(self.style.radius.tl + self.style.focus_ring_offset),
823 border: self.style.focus_ring,
824 }));
825 }
826 }
827
828 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
829 if self.disabled.read() {
830 return;
831 }
832
833 match event {
834 Event::Pointer(PointerEvent::Button {
835 pos,
836 button: MouseButton::Left,
837 pressed: false,
838 ..
839 }) => {
840 if let Some(index) = self.segment_at(bounds, pos.x, pos.y) {
841 self.select_index(ctx, index);
842 }
843 }
844 Event::Keyboard(key) if key.state == KeyState::Pressed => {
845 let selected = self.selected_value();
846 let target = match &key.key {
847 Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space) => {
848 self.activation_index(selected.as_ref())
849 }
850 Key::Named(NamedKey::ArrowRight) => self.next_enabled_index(selected.as_ref()),
851 Key::Named(NamedKey::ArrowLeft) => {
852 self.previous_enabled_index(selected.as_ref())
853 }
854 Key::Named(NamedKey::Home) => self.first_enabled_index(),
855 Key::Named(NamedKey::End) => self.last_enabled_index(),
856 _ => None,
857 };
858 if let Some(index) = target {
859 self.select_index(ctx, index);
860 }
861 }
862 _ => {}
863 }
864 }
865
866 fn focus_policy(&self) -> FocusPolicy {
867 if self.disabled.read() || self.first_enabled_index().is_none() {
868 FocusPolicy::NotFocusable
869 } else {
870 FocusPolicy::Focusable
871 }
872 }
873}
874
875impl<T: Clone + PartialEq + 'static, A: 'static> SegmentedWidget<T, A> {
876 fn selected_value(&self) -> Option<T> {
878 self.selected.as_ref().map(Binding::read)
879 }
880
881 fn selected_index(&self, selected: Option<&T>) -> Option<usize> {
883 let selected = selected?;
884 self.options
885 .iter()
886 .position(|option| &option.value == selected)
887 }
888
889 fn segment_at(&self, bounds: Rect, x: f32, y: f32) -> Option<usize> {
891 if self.options.is_empty() || !bounds.contains(x, y) {
892 return None;
893 }
894 let segment_width = bounds.w / self.options.len() as f32;
895 if segment_width <= 0.0 {
896 return None;
897 }
898 let index = ((x - bounds.x) / segment_width).floor() as usize;
899 (index < self.options.len()).then_some(index)
900 }
901
902 fn select_index(&self, ctx: &mut EventCtx<A>, index: usize) {
904 let Some(option) = self.options.get(index) else {
905 return;
906 };
907 if option.disabled.read() {
908 return;
909 }
910 if self
911 .selected_value()
912 .as_ref()
913 .is_some_and(|value| value == &option.value)
914 {
915 return;
916 }
917 if self.bound.is_none() && self.on_change.is_none() {
918 return;
919 }
920
921 let next = option.value.clone();
922 if let Some(bound) = &self.bound {
923 bound.set(next.clone());
924 }
925 if let Some(on_change) = &self.on_change {
926 on_change(ctx, next);
927 }
928 ctx.request_repaint();
929 ctx.stop_propagation();
930 }
931
932 fn activation_index(&self, selected: Option<&T>) -> Option<usize> {
934 self.selected_index(selected)
935 .filter(|idx| self.option_enabled(*idx))
936 .or_else(|| self.first_enabled_index())
937 }
938
939 fn next_enabled_index(&self, selected: Option<&T>) -> Option<usize> {
941 let len = self.options.len();
942 if len == 0 {
943 return None;
944 }
945 let start = self.selected_index(selected).unwrap_or(len - 1);
946 (1..=len)
947 .map(|offset| (start + offset) % len)
948 .find(|idx| self.option_enabled(*idx))
949 }
950
951 fn previous_enabled_index(&self, selected: Option<&T>) -> Option<usize> {
953 let len = self.options.len();
954 if len == 0 {
955 return None;
956 }
957 let start = self.selected_index(selected).unwrap_or(0);
958 (1..=len)
959 .map(|offset| (start + len - offset) % len)
960 .find(|idx| self.option_enabled(*idx))
961 }
962
963 fn first_enabled_index(&self) -> Option<usize> {
965 self.options
966 .iter()
967 .enumerate()
968 .find_map(|(idx, _)| self.option_enabled(idx).then_some(idx))
969 }
970
971 fn last_enabled_index(&self) -> Option<usize> {
973 self.options
974 .iter()
975 .enumerate()
976 .rev()
977 .find_map(|(idx, _)| self.option_enabled(idx).then_some(idx))
978 }
979
980 fn option_enabled(&self, index: usize) -> bool {
982 self.options
983 .get(index)
984 .is_some_and(|option| !option.disabled.read())
985 }
986}
987
988impl<T: Clone + PartialEq + 'static, A: 'static> IntoView<A> for SegmentedControl<T, A> {
989 fn into_view(self) -> View<A> {
990 finish_view_sized(
991 View::leaf(SegmentedWidget {
992 layout: self.layout,
993 options: self.options,
994 selected: self.selected,
995 bound: self.bound,
996 disabled: self.disabled,
997 on_change: self.on_change,
998 style: self.style,
999 }),
1000 self.flex_item,
1001 LayoutSizeHint::from_layout(self.layout),
1002 )
1003 }
1004}
1005
1006fn segmented_intrinsic_size<T>(
1008 options: &[SegmentedOption<T>],
1009 style: &SegmentedStyle,
1010 mut text_system: Option<&mut TextSystem>,
1011) -> Size {
1012 if options.is_empty() {
1013 return Size::new(0.0, style.height);
1014 }
1015 let segment_width = options
1016 .iter()
1017 .map(|option| {
1018 let label = measure_text(text_system.as_deref_mut(), &option.label, style.text);
1019 segment_content_width(option, label.w, style)
1020 })
1021 .fold(style.min_segment_width, f32::max);
1022 Size::new(
1023 (segment_width * options.len() as f32).ceil(),
1024 style.height.ceil(),
1025 )
1026}
1027
1028fn segment_content_width<T>(
1030 option: &SegmentedOption<T>,
1031 label_width: f32,
1032 style: &SegmentedStyle,
1033) -> f32 {
1034 let icon_width = if option.icon.is_some() {
1035 style.icon_size + style.icon_gap
1036 } else {
1037 0.0
1038 };
1039 (label_width + icon_width + style.segment_padding_x * 2.0).max(style.min_segment_width)
1040}
1041
1042fn segment_rects(bounds: Rect, count: usize) -> Vec<Rect> {
1044 if count == 0 {
1045 return Vec::new();
1046 }
1047 let segment_width = bounds.w / count as f32;
1048 (0..count)
1049 .map(|idx| {
1050 let x = bounds.x + segment_width * idx as f32;
1051 let w = if idx + 1 == count {
1052 bounds.right() - x
1053 } else {
1054 segment_width
1055 };
1056 Rect::new(x, bounds.y, w, bounds.h)
1057 })
1058 .collect()
1059}
1060
1061fn paint_background(
1063 ctx: &mut PaintCtx<'_>,
1064 bounds: Rect,
1065 disabled: bool,
1066 hovered: bool,
1067 pressed: bool,
1068 style: &SegmentedStyle,
1069) {
1070 let color = if pressed {
1071 style.background_pressed
1072 } else if hovered {
1073 style.background_hovered
1074 } else {
1075 style.background
1076 };
1077 ctx.push(DrawCmd::RRect(DrawRRect {
1078 rect: bounds,
1079 radius: style.radius.tl,
1080 color: apply_opacity(
1081 color,
1082 if disabled {
1083 style.disabled_opacity
1084 } else {
1085 1.0
1086 },
1087 ),
1088 }));
1089}
1090
1091fn paint_selected_segment(
1093 ctx: &mut PaintCtx<'_>,
1094 rect: Rect,
1095 disabled: bool,
1096 style: &SegmentedStyle,
1097) {
1098 let inset = 3.0_f32.min(rect.h * 0.25);
1099 let selected_rect = rect.inflate(-inset, -inset);
1100 ctx.push(DrawCmd::RRect(DrawRRect {
1101 rect: selected_rect,
1102 radius: (style.radius.tl - 2.0).max(0.0),
1103 color: apply_opacity(
1104 style.selected_background,
1105 if disabled {
1106 style.disabled_opacity
1107 } else {
1108 1.0
1109 },
1110 ),
1111 }));
1112}
1113
1114fn paint_dividers(ctx: &mut PaintCtx<'_>, bounds: Rect, count: usize, style: &SegmentedStyle) {
1116 if count <= 1 {
1117 return;
1118 }
1119 let segment_width = bounds.w / count as f32;
1120 for idx in 1..count {
1121 let x = bounds.x + segment_width * idx as f32;
1122 ctx.push(DrawCmd::Rect(DrawRect {
1123 rect: Rect::new(x, bounds.y + 6.0, 1.0, (bounds.h - 12.0).max(0.0)),
1124 color: style.divider_color.with_alpha(0.72),
1125 }));
1126 }
1127}
1128
1129fn paint_segment_content<T>(
1131 ctx: &mut PaintCtx<'_>,
1132 rect: Rect,
1133 option: &SegmentedOption<T>,
1134 state: SegmentPaintState,
1135 style: &SegmentedStyle,
1136) {
1137 let opacity = if state.disabled {
1138 style.disabled_opacity
1139 } else {
1140 1.0
1141 };
1142 let text_style = if state.disabled {
1143 style.disabled_text
1144 } else if state.selected {
1145 style.selected_text
1146 } else {
1147 style.text
1148 };
1149 let label_width = estimate_text_width(&option.label, text_style);
1150 let content_width = label_width
1151 + option
1152 .icon
1153 .as_ref()
1154 .map(|_| style.icon_size + style.icon_gap)
1155 .unwrap_or(0.0);
1156 let mut x = rect.x + (rect.w - content_width).max(0.0) * 0.5;
1157
1158 if let Some(icon) = &option.icon {
1159 let tint = if state.disabled {
1160 style.disabled_icon_tint
1161 } else if state.selected {
1162 style.selected_icon_tint
1163 } else {
1164 style.icon_tint
1165 };
1166 ctx.push(DrawCmd::Image(DrawImage {
1167 rect: Rect::new(
1168 x,
1169 rect.y + (rect.h - style.icon_size) * 0.5,
1170 style.icon_size,
1171 style.icon_size,
1172 ),
1173 icon: icon.clone(),
1174 tint: apply_opacity(tint, opacity),
1175 rotation_rad: 0.0,
1176 }));
1177 x += style.icon_size + style.icon_gap;
1178 }
1179
1180 paint_label(ctx, &option.label, text_style, x, rect, opacity);
1181}
1182
1183fn paint_label(
1185 ctx: &mut PaintCtx<'_>,
1186 label: &str,
1187 style: TextStyle,
1188 x: f32,
1189 bounds: Rect,
1190 opacity: f32,
1191) {
1192 let Some(text_system) = ctx.text_system.as_deref_mut() else {
1193 return;
1194 };
1195 let layout = text_system.layout_cached(TextLayoutParams {
1196 text: label,
1197 style,
1198 max_width: None,
1199 wrap_mode: WrapMode::NoWrap,
1200 });
1201 let baseline = layout
1202 .lines
1203 .first()
1204 .map(|line| line.baseline_y)
1205 .unwrap_or(0.0);
1206 let y = bounds.y + (bounds.h - layout.metrics.height) * 0.5 + baseline;
1207 ctx.push(DrawCmd::Text(DrawText {
1208 pos: [x, y],
1209 color: apply_opacity(style.color, opacity),
1210 decoration: ailloli_ui_core::TextDecoration::None,
1211 layout: layout.clone(),
1212 }));
1213}
1214
1215fn measure_text(text_system: Option<&mut TextSystem>, text: &str, style: TextStyle) -> Size {
1217 if let Some(text_system) = text_system {
1218 let layout = text_system.layout_cached(TextLayoutParams {
1219 text,
1220 style,
1221 max_width: None,
1222 wrap_mode: WrapMode::NoWrap,
1223 });
1224 Size::new(layout.metrics.width, layout.metrics.height)
1225 } else {
1226 Size::new(estimate_text_width(text, style), style.px_size as f32 * 1.2)
1227 }
1228}
1229
1230fn estimate_text_width(text: &str, style: TextStyle) -> f32 {
1232 text.chars().count() as f32 * style.px_size as f32 * 0.58
1233}
1234
1235fn apply_opacity(mut color: Color, opacity: f32) -> Color {
1237 color.a = (color.a * opacity).clamp(0.0, 1.0);
1238 color
1239}
1240
1241fn apply_border_opacity(mut border: Border, opacity: f32) -> Border {
1243 border.colors.left = apply_opacity(border.colors.left, opacity);
1244 border.colors.top = apply_opacity(border.colors.top, opacity);
1245 border.colors.right = apply_opacity(border.colors.right, opacity);
1246 border.colors.bottom = apply_opacity(border.colors.bottom, opacity);
1247 border
1248}
1249
1250fn max_border_width(border: Border) -> f32 {
1252 border
1253 .widths
1254 .left
1255 .max(border.widths.top)
1256 .max(border.widths.right)
1257 .max(border.widths.bottom)
1258}