ailloli_ui_widgets/controls/button.rs
1//! Clickable single-child buttons with state-aware container styling.
2
3use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
4use crate::text::Text;
5use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
6use ailloli_ui_core::event::Event;
7use ailloli_ui_core::event::{Key, KeyState, NamedKey};
8use ailloli_ui_core::geometry::{Constraints, EdgeInsets, Rect, Size};
9use ailloli_ui_core::style::{
10 AlignItems, Background, Border, BoxShadow, BoxStyle, FlexItemStyle, InteractionState,
11 JustifyContent, LayoutSizeHint, LayoutStyle, Radius, StateStyle,
12};
13use ailloli_ui_core::{Color, FontId, Offset, TextStyle, Theme};
14use ailloli_ui_runtime::component::{Binding, IntoView, Memo, View, Widget};
15use ailloli_ui_runtime::input::{
16 ActivationPolicy, ClickAction, EventCtx, FocusPolicy, IntoClickAction,
17};
18use ailloli_ui_runtime::layout::{ChildLayout, LayoutChild, LayoutCtx, LayoutResult};
19use ailloli_ui_runtime::scene::PaintCtx;
20use ailloli_ui_runtime::{DrawBorder, DrawBoxShadow, DrawCmd, DrawRRect, DrawText};
21use ailloli_ui_text::{TextLayoutParams, TextSystem, WrapMode};
22
23#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
24/// Built-in semantic button appearances.
25///
26/// # Examples
27///
28/// ```
29/// use ailloli_ui_widgets::controls::ButtonVariant;
30/// let variants = [
31/// ButtonVariant::Default,
32/// ButtonVariant::Primary,
33/// ButtonVariant::Secondary,
34/// ButtonVariant::Outline,
35/// ButtonVariant::Ghost,
36/// ButtonVariant::Destructive,
37/// ButtonVariant::Success,
38/// ButtonVariant::Warning,
39/// ButtonVariant::Info,
40/// ];
41/// assert_eq!(variants.len(), 9);
42/// assert_eq!(ButtonVariant::default(), ButtonVariant::Primary);
43/// ```
44pub enum ButtonVariant {
45 /// Compatibility alias for the primary default button.
46 Default,
47 /// Accent-filled primary action; the enum default.
48 #[default]
49 Primary,
50 /// Elevated neutral surface with a border.
51 Secondary,
52 /// Transparent surface with an interaction-state border/fill.
53 Outline,
54 /// Borderless transparent surface with interaction fills.
55 Ghost,
56 /// Danger-tone filled action.
57 Destructive,
58 /// Success-tone filled action.
59 Success,
60 /// Warning-tone filled action with dark text.
61 Warning,
62 /// Info-tone filled action with dark text.
63 Info,
64}
65
66#[derive(Clone, Debug)]
67/// Container/text states and logical-pixel geometry for a button.
68///
69/// The retained [`Button`] widget dynamically resolves `container`. Its child is
70/// independently styled: `text` is copied only by label constructors and is also
71/// used by [`draw_button`]. Likewise, `baseline_shift` only affects
72/// [`draw_button`], not arbitrary child layout.
73///
74/// # Examples
75///
76/// ```
77/// use ailloli_ui_widgets::controls::ButtonStyle;
78/// let style = ButtonStyle::primary();
79/// assert_eq!((style.height, style.horizontal_padding), (36.0, 12.0));
80/// ```
81pub struct ButtonStyle {
82 /// Normal and optional interaction-state box styles.
83 pub container: StateStyle<BoxStyle>,
84 /// Normal and optional interaction-state label text styles.
85 pub text: StateStyle<TextStyle>,
86 /// Minimum intrinsic button height in logical pixels.
87 pub height: f32,
88 /// Horizontal child inset on each side in logical pixels.
89 pub horizontal_padding: f32,
90 /// Vertical child inset on each side in logical pixels.
91 pub vertical_padding: f32,
92 /// Cross-axis child alignment inside available content space.
93 pub align_items: AlignItems,
94 /// Main-axis child alignment inside available content space.
95 pub justify_content: JustifyContent,
96 /// Extra baseline offset used only by [`draw_button`], in logical pixels.
97 pub baseline_shift: f32,
98}
99
100impl Default for ButtonStyle {
101 fn default() -> Self {
102 Self::primary()
103 }
104}
105
106impl ButtonStyle {
107 /// Returns default-theme primary styling.
108 ///
109 /// # Examples
110 ///
111 /// ```
112 /// use ailloli_ui_widgets::controls::ButtonStyle;
113 /// assert_eq!(ButtonStyle::primary().height, 36.0);
114 /// ```
115 pub fn primary() -> Self {
116 Self::from_theme(Theme::default(), ButtonVariant::Primary)
117 }
118
119 /// Returns default-theme secondary styling.
120 ///
121 /// # Examples
122 ///
123 /// ```
124 /// use ailloli_ui_widgets::controls::ButtonStyle;
125 /// assert!(ButtonStyle::secondary().container.normal.border.is_visible());
126 /// ```
127 pub fn secondary() -> Self {
128 Self::from_theme(Theme::default(), ButtonVariant::Secondary)
129 }
130
131 /// Returns default-theme outline styling.
132 ///
133 /// # Examples
134 ///
135 /// ```
136 /// use ailloli_ui_widgets::controls::ButtonStyle;
137 /// assert!(ButtonStyle::outline().container.normal.border.is_visible());
138 /// ```
139 pub fn outline() -> Self {
140 Self::from_theme(Theme::default(), ButtonVariant::Outline)
141 }
142
143 /// Returns default-theme ghost styling.
144 ///
145 /// # Examples
146 ///
147 /// ```
148 /// use ailloli_ui_widgets::controls::ButtonStyle;
149 /// assert!(!ButtonStyle::ghost().container.normal.border.is_visible());
150 /// ```
151 pub fn ghost() -> Self {
152 Self::from_theme(Theme::default(), ButtonVariant::Ghost)
153 }
154
155 /// Returns default-theme danger styling.
156 ///
157 /// # Examples
158 ///
159 /// ```
160 /// use ailloli_ui_widgets::controls::ButtonStyle;
161 /// assert_eq!(ButtonStyle::destructive().height, 36.0);
162 /// ```
163 pub fn destructive() -> Self {
164 Self::from_theme(Theme::default(), ButtonVariant::Destructive)
165 }
166
167 /// Returns default-theme success styling.
168 ///
169 /// # Examples
170 ///
171 /// ```
172 /// use ailloli_ui_widgets::controls::ButtonStyle;
173 /// assert_eq!(ButtonStyle::success().horizontal_padding, 12.0);
174 /// ```
175 pub fn success() -> Self {
176 Self::from_theme(Theme::default(), ButtonVariant::Success)
177 }
178
179 /// Returns default-theme warning styling with dark normal text.
180 ///
181 /// # Examples
182 ///
183 /// ```
184 /// use ailloli_ui_widgets::controls::ButtonStyle;
185 /// assert_eq!(ButtonStyle::warning().text.normal.px_size, 14);
186 /// ```
187 pub fn warning() -> Self {
188 Self::from_theme(Theme::default(), ButtonVariant::Warning)
189 }
190
191 /// Returns default-theme informational styling with dark normal text.
192 ///
193 /// # Examples
194 ///
195 /// ```
196 /// use ailloli_ui_widgets::controls::ButtonStyle;
197 /// assert_eq!(ButtonStyle::info().vertical_padding, 8.0);
198 /// ```
199 pub fn info() -> Self {
200 Self::from_theme(Theme::default(), ButtonVariant::Info)
201 }
202
203 /// Resolves every container/text interaction state from theme and variant.
204 ///
205 /// [`ButtonVariant::Default`] and [`ButtonVariant::Primary`] resolve
206 /// identically. Disabled style is shared across variants.
207 ///
208 /// # Examples
209 ///
210 /// ```
211 /// use ailloli_ui_core::Theme;
212 /// use ailloli_ui_widgets::controls::{ButtonStyle, ButtonVariant};
213 /// let style = ButtonStyle::from_theme(Theme::dark(), ButtonVariant::Secondary);
214 /// assert_eq!(style.height, 36.0);
215 /// assert!(style.container.hovered.is_some());
216 /// ```
217 pub fn from_theme(theme: Theme, variant: ButtonVariant) -> Self {
218 let palette = theme.palette();
219 let radius = theme.radius().button();
220 let text_light = TextStyle::new(FontId::Ui, 14, palette.text);
221 let text_dark = TextStyle::new(FontId::Ui, 14, Color::hex_rgb(0x090B0C));
222 let text_muted = TextStyle::new(FontId::Ui, 14, palette.text_muted.with_alpha(0.70));
223 let border = Border::new(1.0, palette.border);
224 let transparent = Background::color(Color::TRANSPARENT);
225 let disabled = BoxStyle::new()
226 .background(Background::color(palette.surface_elevated.with_alpha(0.48)))
227 .radius(radius);
228
229 let (normal, hovered, pressed, text) = match variant {
230 ButtonVariant::Default | ButtonVariant::Primary => (
231 BoxStyle::new()
232 .background(Background::color(palette.accent))
233 .radius(radius),
234 BoxStyle::new()
235 .background(Background::color(theme.button_bg_hover))
236 .radius(radius),
237 BoxStyle::new()
238 .background(Background::color(theme.button_bg_pressed))
239 .radius(radius),
240 text_light,
241 ),
242 ButtonVariant::Secondary => (
243 BoxStyle::new()
244 .background(Background::color(palette.surface_elevated))
245 .border(border)
246 .radius(radius),
247 BoxStyle::new()
248 .background(Background::color(Color::hex_rgb(0x20252A)))
249 .border(border)
250 .radius(radius),
251 BoxStyle::new()
252 .background(Background::color(Color::hex_rgb(0x15191D)))
253 .border(border)
254 .radius(radius),
255 text_light,
256 ),
257 ButtonVariant::Outline => (
258 BoxStyle::new()
259 .background(transparent)
260 .border(border)
261 .radius(radius),
262 BoxStyle::new()
263 .background(Background::color(palette.surface.with_alpha(0.86)))
264 .border(Border::new(1.0, palette.accent.with_alpha(0.72)))
265 .radius(radius),
266 BoxStyle::new()
267 .background(Background::color(palette.surface_elevated))
268 .border(Border::new(1.0, palette.accent))
269 .radius(radius),
270 text_light,
271 ),
272 ButtonVariant::Ghost => (
273 BoxStyle::new().background(transparent).radius(radius),
274 BoxStyle::new()
275 .background(Background::color(palette.surface.with_alpha(0.72)))
276 .radius(radius),
277 BoxStyle::new()
278 .background(Background::color(palette.surface_elevated))
279 .radius(radius),
280 text_light,
281 ),
282 ButtonVariant::Destructive => tone_button(palette.danger, radius),
283 ButtonVariant::Success => tone_button(palette.success, radius),
284 ButtonVariant::Warning => tone_button(palette.warning, radius),
285 ButtonVariant::Info => tone_button(palette.info, radius),
286 };
287
288 let text = if matches!(variant, ButtonVariant::Warning | ButtonVariant::Info) {
289 text_dark
290 } else {
291 text
292 };
293
294 Self {
295 container: StateStyle {
296 normal,
297 hovered: Some(hovered),
298 pressed: Some(pressed),
299 focused: None,
300 disabled: Some(disabled),
301 },
302 text: StateStyle {
303 normal: text,
304 hovered: None,
305 pressed: None,
306 focused: None,
307 disabled: Some(text_muted),
308 },
309 height: 36.0,
310 horizontal_padding: 12.0,
311 vertical_padding: 8.0,
312 align_items: AlignItems::Center,
313 justify_content: JustifyContent::Center,
314 baseline_shift: 0.0,
315 }
316 }
317
318 /// Creates transparent, zero-padding text-only drawing style.
319 ///
320 /// It has 13-pixel UI text and no hover/pressed/focused/disabled overrides.
321 ///
322 /// # Examples
323 ///
324 /// ```
325 /// use ailloli_ui_core::Color;
326 /// use ailloli_ui_widgets::controls::ButtonStyle;
327 /// let style = ButtonStyle::text_only(Color::WHITE);
328 /// assert_eq!((style.height, style.horizontal_padding), (0.0, 0.0));
329 /// ```
330 pub fn text_only(fg: Color) -> Self {
331 let text = TextStyle::new(FontId::Ui, 13, fg);
332 Self {
333 container: StateStyle {
334 normal: BoxStyle::new().background(Background::color(Color::TRANSPARENT)),
335 hovered: None,
336 pressed: None,
337 focused: None,
338 disabled: None,
339 },
340 text: StateStyle {
341 normal: text,
342 hovered: None,
343 pressed: None,
344 focused: None,
345 disabled: None,
346 },
347 height: 0.0,
348 horizontal_padding: 0.0,
349 vertical_padding: 0.0,
350 align_items: AlignItems::Center,
351 justify_content: JustifyContent::Center,
352 baseline_shift: 0.0,
353 }
354 }
355
356 /// Resolves a concrete box style using `StateStyle` precedence.
357 ///
358 /// # Examples
359 ///
360 /// ```
361 /// use ailloli_ui_core::style::InteractionState;
362 /// use ailloli_ui_widgets::controls::ButtonStyle;
363 /// let resolved = ButtonStyle::primary().resolve_container(InteractionState::default());
364 /// assert!(!resolved.shadows.iter().any(|shadow| shadow.inset));
365 /// ```
366 pub fn resolve_container(&self, state: InteractionState) -> BoxStyle {
367 self.container.resolve(state)
368 }
369
370 /// Resolves a concrete text style using `StateStyle` precedence.
371 ///
372 /// # Examples
373 ///
374 /// ```
375 /// use ailloli_ui_core::style::InteractionState;
376 /// use ailloli_ui_widgets::controls::ButtonStyle;
377 /// assert_eq!(ButtonStyle::primary().resolve_text(InteractionState::default()).px_size, 14);
378 /// ```
379 pub fn resolve_text(&self, state: InteractionState) -> TextStyle {
380 self.text.resolve(state)
381 }
382
383 /// Returns maximum per-edge border widths across every container state.
384 fn layout_border_widths(&self) -> EdgeInsets {
385 let mut widths = self.container.normal.border.layout_widths();
386 for style in [
387 self.container.hovered.as_ref(),
388 self.container.pressed.as_ref(),
389 self.container.focused.as_ref(),
390 self.container.disabled.as_ref(),
391 ]
392 .into_iter()
393 .flatten()
394 {
395 let other = style.border.layout_widths();
396 widths.left = widths.left.max(other.left);
397 widths.top = widths.top.max(other.top);
398 widths.right = widths.right.max(other.right);
399 widths.bottom = widths.bottom.max(other.bottom);
400 }
401 widths
402 }
403
404 /// Unions normal and interaction-state visual bounds for stable layout.
405 fn layout_visual_bounds(&self, rect: Rect) -> Rect {
406 let mut bounds = self.container.normal.visual_bounds(rect);
407 for style in [
408 self.container.hovered.as_ref(),
409 self.container.pressed.as_ref(),
410 self.container.focused.as_ref(),
411 self.container.disabled.as_ref(),
412 ]
413 .into_iter()
414 .flatten()
415 {
416 bounds = union_rect(bounds, style.visual_bounds(rect));
417 }
418 bounds
419 }
420
421 /// Applies a box-style transformation to every existing container state.
422 fn update_containers(&mut self, mut f: impl FnMut(BoxStyle) -> BoxStyle) {
423 self.container.normal = f(self.container.normal.clone());
424 if let Some(style) = self.container.hovered.take() {
425 self.container.hovered = Some(f(style));
426 }
427 if let Some(style) = self.container.pressed.take() {
428 self.container.pressed = Some(f(style));
429 }
430 if let Some(style) = self.container.focused.take() {
431 self.container.focused = Some(f(style));
432 }
433 if let Some(style) = self.container.disabled.take() {
434 self.container.disabled = Some(f(style));
435 }
436 }
437}
438
439/// Resolves single-child main-axis offset; space variants collapse to start/center.
440fn main_axis_offset(justify: JustifyContent, available: f32, child: f32) -> f32 {
441 let free = (available - child).max(0.0);
442 match justify {
443 JustifyContent::Start | JustifyContent::SpaceBetween => 0.0,
444 JustifyContent::Center | JustifyContent::SpaceAround | JustifyContent::SpaceEvenly => {
445 free * 0.5
446 }
447 JustifyContent::End => free,
448 }
449}
450
451/// Resolves single-child cross-axis offset; stretch behaves as start.
452fn cross_axis_offset(align: AlignItems, available: f32, child: f32) -> f32 {
453 let free = (available - child).max(0.0);
454 match align {
455 AlignItems::Start | AlignItems::Stretch => 0.0,
456 AlignItems::Center => free * 0.5,
457 AlignItems::End => free,
458 }
459}
460
461/// Returns the smallest axis-aligned rectangle containing both inputs.
462fn union_rect(a: Rect, b: Rect) -> Rect {
463 let x0 = a.x.min(b.x);
464 let y0 = a.y.min(b.y);
465 let x1 = a.right().max(b.right());
466 let y1 = a.bottom().max(b.bottom());
467 Rect::new(x0, y0, x1 - x0, y1 - y0)
468}
469
470/// Builds normal/hover/press filled states and light text for a semantic tone.
471fn tone_button(color: Color, radius: Radius) -> (BoxStyle, BoxStyle, BoxStyle, TextStyle) {
472 (
473 BoxStyle::new()
474 .background(Background::color(color))
475 .radius(radius),
476 BoxStyle::new()
477 .background(Background::color(color.with_alpha(0.92)))
478 .radius(radius),
479 BoxStyle::new()
480 .background(Background::color(color.with_alpha(0.78)))
481 .radius(radius),
482 TextStyle::new(FontId::Ui, 14, Color::hex_rgb(0xF4F7F8)),
483 )
484}
485
486/// Produces immediate-mode draw commands for a text-only button snapshot.
487///
488/// [`ButtonVariant::Default`] preserves the supplied style; every other variant
489/// replaces it with default-theme styling for that variant. Only normal states
490/// are used. Non-inset shadows, background, one unwrapped label, and border are
491/// emitted in that order. The rectangle and custom geometry are not validated.
492///
493/// # Examples
494///
495/// ```
496/// use ailloli_ui_core::Rect;
497/// use ailloli_ui_text::TextSystem;
498/// use ailloli_ui_widgets::controls::{ButtonStyle, ButtonVariant};
499/// use ailloli_ui_widgets::controls::button::draw_button;
500/// let mut text = TextSystem::new();
501/// let commands = draw_button(
502/// Rect::new(0.0, 0.0, 120.0, 36.0),
503/// "Save",
504/// ButtonVariant::Default,
505/// ButtonStyle::primary(),
506/// &mut text,
507/// );
508/// assert!(!commands.is_empty());
509/// ```
510pub fn draw_button(
511 rect: Rect,
512 label: &str,
513 variant: ButtonVariant,
514 style: ButtonStyle,
515 text: &mut TextSystem,
516) -> Vec<DrawCmd> {
517 let variant_style = if variant == ButtonVariant::Default {
518 style
519 } else {
520 ButtonStyle::from_theme(Theme::default(), variant)
521 };
522 let container = variant_style.container.normal.clone();
523 let bg = match container.background {
524 Background::Color(bg) => bg,
525 Background::None => Color::TRANSPARENT,
526 };
527 let text_style = variant_style.text.normal;
528
529 let mut out = Vec::new();
530 for shadow in container.shadows.iter().copied().filter(|s| !s.inset) {
531 let shadow = apply_shadow_opacity(shadow, container.opacity.0);
532 if shadow.color.a > 0.0 {
533 out.push(DrawCmd::BoxShadow(DrawBoxShadow {
534 rect,
535 radius: container.radius,
536 shadow,
537 }));
538 }
539 }
540 out.extend([DrawCmd::RRect(DrawRRect {
541 rect,
542 radius: container.radius.tl,
543 color: apply_opacity(bg, container.opacity.0),
544 })]);
545
546 let layout = text.layout_cached(TextLayoutParams {
547 text: label,
548 style: text_style,
549 max_width: None,
550 wrap_mode: WrapMode::NoWrap,
551 });
552 let border = container.border.layout_widths();
553 let content_w =
554 (rect.w - border.horizontal() - variant_style.horizontal_padding * 2.0).max(0.0);
555 let content_h = (rect.h - border.vertical() - variant_style.vertical_padding * 2.0).max(0.0);
556 let x = rect.x
557 + border.left
558 + variant_style.horizontal_padding
559 + main_axis_offset(
560 variant_style.justify_content,
561 content_w,
562 layout.metrics.width,
563 );
564 let baseline = layout
565 .lines
566 .first()
567 .map(|line| line.baseline_y)
568 .unwrap_or(0.0);
569 let y = rect.y
570 + border.top
571 + variant_style.vertical_padding
572 + cross_axis_offset(variant_style.align_items, content_h, layout.metrics.height)
573 + baseline
574 + variant_style.baseline_shift;
575 out.push(DrawCmd::Text(DrawText {
576 pos: [x, y],
577 color: text_style.color,
578 decoration: ailloli_ui_core::TextDecoration::None,
579 layout,
580 }));
581
582 let border = apply_border_opacity(container.border, container.opacity.0);
583 if border.is_visible() {
584 out.push(DrawCmd::Border(DrawBorder {
585 rect,
586 radius: container.radius,
587 border,
588 }));
589 }
590
591 out
592}
593
594/// Multiplies alpha by `opacity` and clamps it to `[0, 1]`.
595fn apply_opacity(mut c: Color, opacity: f32) -> Color {
596 c.a = (c.a * opacity).clamp(0.0, 1.0);
597 c
598}
599
600/// Applies an opacity multiplier independently to all border-edge colors.
601fn apply_border_opacity(mut border: Border, opacity: f32) -> Border {
602 border.colors.left = apply_opacity(border.colors.left, opacity);
603 border.colors.top = apply_opacity(border.colors.top, opacity);
604 border.colors.right = apply_opacity(border.colors.right, opacity);
605 border.colors.bottom = apply_opacity(border.colors.bottom, opacity);
606 border
607}
608
609/// Applies an opacity multiplier to one shadow color.
610fn apply_shadow_opacity(mut shadow: BoxShadow, opacity: f32) -> BoxShadow {
611 shadow.color = apply_opacity(shadow.color, opacity);
612 shadow
613}
614
615/// Returns the final shadow, inserting `BoxShadow::md()` when empty.
616fn ensure_shadow(shadows: &mut Vec<BoxShadow>) -> &mut BoxShadow {
617 if shadows.is_empty() {
618 shadows.push(BoxShadow::md());
619 }
620 shadows.last_mut().expect("shadow inserted when empty")
621}
622
623/// Clickable single-child button with stateful container styling.
624///
625/// Enter, Space, or a left-button release inside bounds runs the optional action.
626/// Disabled state suppresses activation and selects disabled styling, but the
627/// current focus policy still reports the button as focusable. Child text is not
628/// dynamically restyled; label constructors copy a normal text style once.
629///
630/// # Examples
631///
632/// ```
633/// use ailloli_ui_widgets::controls::{Button, ButtonVariant};
634/// let button: Button<()> = Button::with_label_variant("Save", ButtonVariant::Primary);
635/// let _ = button;
636/// ```
637pub struct Button<A = ()> {
638 /// Layout configuration applied around the child and button insets.
639 pub(crate) layout: LayoutStyle,
640 /// Flex behavior used by the parent layout.
641 pub(crate) flex_item: FlexItemStyle,
642 /// Sole child view; initially empty.
643 child: View<A>,
644 /// Live disabled state.
645 disabled: Binding<bool>,
646 /// Optional activation action.
647 on_click: Option<ClickAction<A>>,
648 /// Resolved container and label-construction style.
649 style: ButtonStyle,
650}
651
652crate::impl_layout_builders!(Button);
653
654impl<A: 'static> Default for Button<A> {
655 fn default() -> Self {
656 Self::new()
657 }
658}
659
660impl<A: 'static> Button<A> {
661 /// Creates an enabled primary button with an empty child and no action.
662 ///
663 /// # Examples
664 ///
665 /// ```
666 /// use ailloli_ui_widgets::controls::Button;
667 /// let button: Button<()> = Button::new();
668 /// let _ = button;
669 /// ```
670 pub fn new() -> Self {
671 Self {
672 layout: LayoutStyle::default(),
673 flex_item: FlexItemStyle::default(),
674 child: View::empty(),
675 disabled: Binding::Static(false),
676 on_click: None,
677 style: ButtonStyle::primary(),
678 }
679 }
680
681 /// Creates a primary button with one unwrapped text child.
682 ///
683 /// The normal primary text style is copied into the child at construction.
684 ///
685 /// # Examples
686 ///
687 /// ```
688 /// use ailloli_ui_widgets::controls::Button;
689 /// let button: Button<()> = Button::with_label("Save");
690 /// let _ = button;
691 /// ```
692 pub fn with_label(label: impl Into<String>) -> Self {
693 let style = ButtonStyle::primary();
694 Self::new().child(Text::new(label.into()).style(style.text.normal).nowrap())
695 }
696
697 /// Creates a themed variant and an unwrapped label styled to match it.
698 ///
699 /// Prefer this over calling [`Self::variant`] after [`Self::with_label`],
700 /// because later style changes do not propagate into an existing child.
701 ///
702 /// # Examples
703 ///
704 /// ```
705 /// use ailloli_ui_widgets::controls::{Button, ButtonVariant};
706 /// let button: Button<()> = Button::with_label_variant("Delete", ButtonVariant::Destructive);
707 /// let _ = button;
708 /// ```
709 pub fn with_label_variant(label: impl Into<String>, variant: ButtonVariant) -> Self {
710 let style = ButtonStyle::from_theme(Theme::default(), variant);
711 Self::new()
712 .button_style(style.clone())
713 .child(Text::new(label.into()).style(style.text.normal).nowrap())
714 }
715
716 /// Replaces the sole child view.
717 ///
718 /// The button does not apply `ButtonStyle::text` to arbitrary children.
719 ///
720 /// # Examples
721 ///
722 /// ```
723 /// use ailloli_ui_widgets::{controls::Button, text::Text};
724 /// let button: Button<()> = Button::new().child(Text::new("Custom"));
725 /// let _ = button;
726 /// ```
727 pub fn child(mut self, child: impl IntoView<A>) -> Self {
728 self.child = child.into_view();
729 self
730 }
731
732 /// Sets static or reactive disabled state.
733 ///
734 /// Disabled buttons ignore activation but currently remain focusable.
735 ///
736 /// # Examples
737 ///
738 /// ```
739 /// use ailloli_ui_widgets::controls::Button;
740 /// let button: Button<()> = Button::with_label("Unavailable").disabled(true);
741 /// let _ = button;
742 /// ```
743 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
744 self.disabled = disabled.into();
745 self
746 }
747
748 /// Sets disabled state from a derived memo.
749 ///
750 /// # Examples
751 ///
752 /// ```
753 /// use ailloli_ui_runtime::component::Memo;
754 /// use ailloli_ui_widgets::controls::Button;
755 /// let button: Button<()> = Button::new().disabled_signal(Memo::new(|| false));
756 /// let _ = button;
757 /// ```
758 pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
759 self.disabled(disabled)
760 }
761
762 /// Installs an activation action, replacing any previous action.
763 ///
764 /// The application action type must be cloneable for queued dispatch.
765 ///
766 /// # Examples
767 ///
768 /// ```
769 /// use ailloli_ui_widgets::controls::Button;
770 /// #[derive(Clone)]
771 /// enum Action { Save }
772 /// let button = Button::with_label("Save").on_click(Action::Save);
773 /// let _ = button;
774 /// ```
775 pub fn on_click(mut self, action: impl IntoClickAction<A>) -> Self
776 where
777 A: Clone,
778 {
779 self.on_click = Some(action.into_click_action());
780 self
781 }
782
783 /// Installs a context-aware activation handler.
784 ///
785 /// # Examples
786 ///
787 /// ```
788 /// use ailloli_ui_widgets::controls::Button;
789 /// let button = Button::<()>::new().on_click_ctx(|_ctx| {});
790 /// let _ = button;
791 /// ```
792 pub fn on_click_ctx(mut self, f: impl Fn(&mut EventCtx<A>) + 'static) -> Self {
793 self.on_click = Some(ClickAction::handler(f));
794 self
795 }
796
797 /// Replaces only the stored normal label text style for compatibility.
798 ///
799 /// The retained button does not propagate this into an existing child; it is
800 /// observable through the stored style in immediate-mode/compatibility paths.
801 ///
802 /// # Examples
803 ///
804 /// ```
805 /// use ailloli_ui_core::{Color, FontId, TextStyle};
806 /// use ailloli_ui_widgets::controls::Button;
807 /// let button: Button<()> = Button::new().style(TextStyle::new(FontId::Ui, 16, Color::WHITE));
808 /// let _ = button;
809 /// ```
810 pub fn style(mut self, style: TextStyle) -> Self {
811 // Compat: only updates label text in the normal state.
812 self.style.text.normal = style;
813 self
814 }
815
816 /// Replaces the complete button style.
817 ///
818 /// This does not restyle an existing child. A later [`Self::variant`] call
819 /// replaces this custom style.
820 ///
821 /// # Examples
822 ///
823 /// ```
824 /// use ailloli_ui_widgets::controls::{Button, ButtonStyle};
825 /// let button: Button<()> = Button::new().button_style(ButtonStyle::outline());
826 /// let _ = button;
827 /// ```
828 pub fn button_style(mut self, style: ButtonStyle) -> Self {
829 self.style = style;
830 self
831 }
832
833 /// Replaces the complete style with a default-theme variant.
834 ///
835 /// Existing child styling is unchanged.
836 ///
837 /// # Examples
838 ///
839 /// ```
840 /// use ailloli_ui_widgets::controls::{Button, ButtonVariant};
841 /// let button: Button<()> = Button::new().variant(ButtonVariant::Ghost);
842 /// let _ = button;
843 /// ```
844 pub fn variant(mut self, variant: ButtonVariant) -> Self {
845 self.style = ButtonStyle::from_theme(Theme::default(), variant);
846 self
847 }
848
849 /// Sets child cross-axis alignment inside available content space.
850 ///
851 /// `Stretch` currently positions like `Start`; it does not relayout the child.
852 ///
853 /// # Examples
854 ///
855 /// ```
856 /// use ailloli_ui_core::style::AlignItems;
857 /// use ailloli_ui_widgets::controls::Button;
858 /// let button: Button<()> = Button::new().align_items(AlignItems::End);
859 /// let _ = button;
860 /// ```
861 pub fn align_items(mut self, value: AlignItems) -> Self {
862 self.style.align_items = value;
863 self
864 }
865
866 /// Sets child main-axis placement inside available content space.
867 ///
868 /// For one child, `SpaceBetween` behaves as `Start` and `SpaceAround`/
869 /// `SpaceEvenly` behave as `Center`.
870 ///
871 /// # Examples
872 ///
873 /// ```
874 /// use ailloli_ui_core::style::JustifyContent;
875 /// use ailloli_ui_widgets::controls::Button;
876 /// let button: Button<()> = Button::new().justify_content(JustifyContent::End);
877 /// let _ = button;
878 /// ```
879 pub fn justify_content(mut self, value: JustifyContent) -> Self {
880 self.style.justify_content = value;
881 self
882 }
883
884 /// Replaces background color in every existing container state.
885 ///
886 /// Missing optional states remain absent.
887 ///
888 /// # Examples
889 ///
890 /// ```
891 /// use ailloli_ui_core::Color;
892 /// use ailloli_ui_widgets::controls::Button;
893 /// let button: Button<()> = Button::new().background(Color::hex_rgb(0x224466));
894 /// let _ = button;
895 /// ```
896 pub fn background(mut self, color: Color) -> Self {
897 self.style
898 .update_containers(|style| style.background(Background::color(color)));
899 self
900 }
901
902 /// Sets uniform corner radius in every existing container state.
903 ///
904 /// The logical-pixel value is stored without clamping.
905 ///
906 /// # Examples
907 ///
908 /// ```
909 /// use ailloli_ui_widgets::controls::Button;
910 /// let button: Button<()> = Button::new().radius(8.0);
911 /// let _ = button;
912 /// ```
913 pub fn radius(mut self, value: f32) -> Self {
914 let radius = Radius::uniform(value);
915 self.style.update_containers(|style| style.radius(radius));
916 self
917 }
918
919 /// Replaces all four border edges in every existing container state.
920 ///
921 /// Width is in logical pixels and is not normalized here.
922 ///
923 /// # Examples
924 ///
925 /// ```
926 /// use ailloli_ui_core::Color;
927 /// use ailloli_ui_widgets::controls::Button;
928 /// let button: Button<()> = Button::new().border(1.0, Color::WHITE);
929 /// let _ = button;
930 /// ```
931 pub fn border(mut self, width: f32, color: Color) -> Self {
932 self.style
933 .update_containers(|style| style.border(Border::new(width, color)));
934 self
935 }
936
937 /// Replaces every edge width while preserving edge colors in all states.
938 ///
939 /// # Examples
940 ///
941 /// ```
942 /// use ailloli_ui_widgets::controls::Button;
943 /// let button: Button<()> = Button::new().border_width(2.0);
944 /// let _ = button;
945 /// ```
946 pub fn border_width(mut self, width: f32) -> Self {
947 self.style.update_containers(|mut style| {
948 style.border = style.border.with_width(width);
949 style
950 });
951 self
952 }
953
954 /// Replaces every edge color while preserving widths in all states.
955 ///
956 /// # Examples
957 ///
958 /// ```
959 /// use ailloli_ui_core::Color;
960 /// use ailloli_ui_widgets::controls::Button;
961 /// let button: Button<()> = Button::new().border_color(Color::WHITE);
962 /// let _ = button;
963 /// ```
964 pub fn border_color(mut self, color: Color) -> Self {
965 self.style.update_containers(|mut style| {
966 style.border = style.border.with_color(color);
967 style
968 });
969 self
970 }
971
972 /// Replaces only the left border edge in every existing state.
973 ///
974 /// # Examples
975 ///
976 /// ```
977 /// use ailloli_ui_core::Color;
978 /// use ailloli_ui_widgets::controls::Button;
979 /// let button: Button<()> = Button::new().border_left(3.0, Color::WHITE);
980 /// let _ = button;
981 /// ```
982 pub fn border_left(mut self, width: f32, color: Color) -> Self {
983 self.style.update_containers(|mut style| {
984 style.border = style.border.with_left(width, color);
985 style
986 });
987 self
988 }
989
990 /// Replaces only the top border edge in every existing state.
991 ///
992 /// # Examples
993 ///
994 /// ```
995 /// use ailloli_ui_core::Color;
996 /// use ailloli_ui_widgets::controls::Button;
997 /// let button: Button<()> = Button::new().border_top(3.0, Color::WHITE);
998 /// let _ = button;
999 /// ```
1000 pub fn border_top(mut self, width: f32, color: Color) -> Self {
1001 self.style.update_containers(|mut style| {
1002 style.border = style.border.with_top(width, color);
1003 style
1004 });
1005 self
1006 }
1007
1008 /// Replaces only the right border edge in every existing state.
1009 ///
1010 /// # Examples
1011 ///
1012 /// ```
1013 /// use ailloli_ui_core::Color;
1014 /// use ailloli_ui_widgets::controls::Button;
1015 /// let button: Button<()> = Button::new().border_right(3.0, Color::WHITE);
1016 /// let _ = button;
1017 /// ```
1018 pub fn border_right(mut self, width: f32, color: Color) -> Self {
1019 self.style.update_containers(|mut style| {
1020 style.border = style.border.with_right(width, color);
1021 style
1022 });
1023 self
1024 }
1025
1026 /// Replaces only the bottom border edge in every existing state.
1027 ///
1028 /// # Examples
1029 ///
1030 /// ```
1031 /// use ailloli_ui_core::Color;
1032 /// use ailloli_ui_widgets::controls::Button;
1033 /// let button: Button<()> = Button::new().border_bottom(3.0, Color::WHITE);
1034 /// let _ = button;
1035 /// ```
1036 pub fn border_bottom(mut self, width: f32, color: Color) -> Self {
1037 self.style.update_containers(|mut style| {
1038 style.border = style.border.with_bottom(width, color);
1039 style
1040 });
1041 self
1042 }
1043
1044 /// Appends one shadow to every existing container state.
1045 ///
1046 /// Inset shadows contribute to visual bounds but are skipped by painting.
1047 ///
1048 /// # Examples
1049 ///
1050 /// ```
1051 /// use ailloli_ui_core::style::BoxShadow;
1052 /// use ailloli_ui_widgets::controls::Button;
1053 /// let button: Button<()> = Button::new().shadow(BoxShadow::sm());
1054 /// let _ = button;
1055 /// ```
1056 pub fn shadow(mut self, shadow: BoxShadow) -> Self {
1057 self.style.update_containers(|style| style.shadow(shadow));
1058 self
1059 }
1060
1061 /// Removes all shadows from every existing container state.
1062 ///
1063 /// # Examples
1064 ///
1065 /// ```
1066 /// use ailloli_ui_widgets::controls::Button;
1067 /// let button: Button<()> = Button::new().shadow_none();
1068 /// let _ = button;
1069 /// ```
1070 pub fn shadow_none(mut self) -> Self {
1071 self.style.update_containers(|style| style.clear_shadows());
1072 self
1073 }
1074
1075 /// Sets the last shadow color in every existing state.
1076 ///
1077 /// An empty state first receives [`BoxShadow::md`].
1078 ///
1079 /// # Examples
1080 ///
1081 /// ```
1082 /// use ailloli_ui_core::Color;
1083 /// use ailloli_ui_widgets::controls::Button;
1084 /// let button: Button<()> = Button::new().shadow_color(Color::BLACK);
1085 /// let _ = button;
1086 /// ```
1087 pub fn shadow_color(mut self, color: Color) -> Self {
1088 self.style.update_containers(|mut style| {
1089 ensure_shadow(&mut style.shadows).color = color;
1090 style
1091 });
1092 self
1093 }
1094
1095 /// Sets non-negative last-shadow blur radius in logical pixels.
1096 ///
1097 /// Negative values and NaN become zero; an empty state first receives a
1098 /// medium default shadow.
1099 ///
1100 /// # Examples
1101 ///
1102 /// ```
1103 /// use ailloli_ui_widgets::controls::Button;
1104 /// let button: Button<()> = Button::new().shadow_blur(12.0);
1105 /// let _ = button;
1106 /// ```
1107 pub fn shadow_blur(mut self, value: f32) -> Self {
1108 self.style.update_containers(|mut style| {
1109 ensure_shadow(&mut style.shadows).blur_radius = value.max(0.0);
1110 style
1111 });
1112 self
1113 }
1114
1115 /// Sets last-shadow x/y offset in logical pixels without normalization.
1116 ///
1117 /// # Examples
1118 ///
1119 /// ```
1120 /// use ailloli_ui_widgets::controls::Button;
1121 /// let button: Button<()> = Button::new().shadow_offset(0.0, 4.0);
1122 /// let _ = button;
1123 /// ```
1124 pub fn shadow_offset(mut self, x: f32, y: f32) -> Self {
1125 self.style.update_containers(|mut style| {
1126 ensure_shadow(&mut style.shadows).offset = Offset::new(x, y);
1127 style
1128 });
1129 self
1130 }
1131
1132 /// Sets non-negative last-shadow spread in logical pixels.
1133 ///
1134 /// Negative values and NaN become zero.
1135 ///
1136 /// # Examples
1137 ///
1138 /// ```
1139 /// use ailloli_ui_widgets::controls::Button;
1140 /// let button: Button<()> = Button::new().shadow_spread(2.0);
1141 /// let _ = button;
1142 /// ```
1143 pub fn shadow_spread(mut self, value: f32) -> Self {
1144 self.style.update_containers(|mut style| {
1145 ensure_shadow(&mut style.shadows).spread = value.max(0.0);
1146 style
1147 });
1148 self
1149 }
1150}
1151
1152/// Public retained widget type produced internally by [`Button::into_view`].
1153///
1154/// Fields are private; consumers normally construct [`Button`] instead.
1155///
1156/// # Examples
1157///
1158/// ```
1159/// use ailloli_ui_widgets::controls::button::ButtonWidget;
1160/// let widget: Option<ButtonWidget<()>> = None;
1161/// assert!(widget.is_none());
1162/// ```
1163pub struct ButtonWidget<A> {
1164 /// Layout configuration copied from the builder.
1165 layout: LayoutStyle,
1166 /// Live disabled state.
1167 disabled: Binding<bool>,
1168 /// Optional activation action.
1169 on_click: Option<ClickAction<A>>,
1170 /// Resolved container state and geometry.
1171 style: ButtonStyle,
1172}
1173
1174impl<A: 'static> Widget<A> for ButtonWidget<A> {
1175 fn debug_name(&self) -> &'static str {
1176 "Button"
1177 }
1178
1179 fn layout(
1180 &self,
1181 engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
1182 ctx: &mut LayoutCtx<'_>,
1183 children: &mut [LayoutChild],
1184 constraints: Constraints,
1185 ) -> LayoutResult {
1186 let pad_x = self.style.horizontal_padding;
1187 let pad_y = self.style.vertical_padding;
1188 let border = self.style.layout_border_widths();
1189 let inner = Constraints {
1190 min_w: (constraints.min_w - border.horizontal() - pad_x * 2.0).max(0.0),
1191 max_w: (constraints.max_w - border.horizontal() - pad_x * 2.0).max(0.0),
1192 min_h: (constraints.min_h - border.vertical() - pad_y * 2.0).max(0.0),
1193 max_h: (constraints.max_h - border.vertical() - pad_y * 2.0).max(0.0),
1194 };
1195
1196 let mut child_layouts = Vec::new();
1197 let mut child_size = Size::default();
1198
1199 if let Some(child) = children.first_mut() {
1200 let r = child.layout(engine, ctx, inner);
1201 child_size = r.size;
1202 child_layouts.push(ChildLayout {
1203 offset: Offset::default(),
1204 size: r.size,
1205 paint_bounds: Rect::new(0.0, 0.0, r.size.w, r.size.h),
1206 visual_bounds: r.visual_bounds,
1207 });
1208 }
1209
1210 let intrinsic = Size::new(
1211 child_size.w + border.horizontal() + pad_x * 2.0,
1212 self.style
1213 .height
1214 .max(child_size.h + border.vertical() + pad_y * 2.0),
1215 );
1216 let size = apply_layout_size(intrinsic, self.layout, constraints);
1217
1218 if let Some(child_layout) = child_layouts.first_mut() {
1219 let content_w = (size.w - border.horizontal() - pad_x * 2.0).max(0.0);
1220 let content_h = (size.h - border.vertical() - pad_y * 2.0).max(0.0);
1221 child_layout.offset = Offset::new(
1222 border.left
1223 + pad_x
1224 + main_axis_offset(self.style.justify_content, content_w, child_layout.size.w),
1225 border.top
1226 + pad_y
1227 + cross_axis_offset(self.style.align_items, content_h, child_layout.size.h),
1228 );
1229 }
1230 let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
1231 let visual_bounds = self.style.layout_visual_bounds(paint_bounds);
1232
1233 LayoutResult {
1234 size,
1235 children: child_layouts,
1236 paint_bounds,
1237 visual_bounds,
1238 overlay_hit_bounds: Vec::new(),
1239 clip: None,
1240 is_window_root_clip: false,
1241 artifact: None,
1242 }
1243 }
1244
1245 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout_result: &LayoutResult) {
1246 let i = ctx.interaction();
1247 let state = InteractionState {
1248 hovered: i.hovered,
1249 pressed: i.pressed,
1250 focused: i.focused,
1251 disabled: self.disabled.read(),
1252 };
1253
1254 let container = self.style.resolve_container(state);
1255 for shadow in container.shadows.iter().copied().filter(|s| !s.inset) {
1256 let shadow = apply_shadow_opacity(shadow, container.opacity.0);
1257 if shadow.color.a > 0.0 {
1258 ctx.push(DrawCmd::BoxShadow(DrawBoxShadow {
1259 rect: bounds,
1260 radius: container.radius,
1261 shadow,
1262 }));
1263 }
1264 }
1265
1266 if let Background::Color(bg) = container.background {
1267 let bg = apply_opacity(bg, container.opacity.0);
1268 ctx.push(DrawCmd::RRect(DrawRRect {
1269 rect: bounds,
1270 radius: container.radius.tl,
1271 color: bg,
1272 }));
1273 }
1274 }
1275
1276 fn paint_overlay(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout_result: &LayoutResult) {
1277 let i = ctx.interaction();
1278 let state = InteractionState {
1279 hovered: i.hovered,
1280 pressed: i.pressed,
1281 focused: i.focused,
1282 disabled: self.disabled.read(),
1283 };
1284
1285 let container = self.style.resolve_container(state);
1286 let border = apply_border_opacity(container.border, container.opacity.0);
1287 if border.is_visible() {
1288 ctx.push(DrawCmd::Border(DrawBorder {
1289 rect: bounds,
1290 radius: container.radius,
1291 border,
1292 }));
1293 }
1294 }
1295
1296 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
1297 if self.disabled.read() {
1298 return;
1299 }
1300
1301 match event {
1302 Event::Pointer(PointerEvent::Button {
1303 pos,
1304 button: MouseButton::Left,
1305 pressed: false,
1306 ..
1307 }) if bounds.contains(pos.x, pos.y) => {
1308 if let Some(on_click) = &self.on_click {
1309 on_click.run(ctx);
1310 ctx.stop_propagation();
1311 }
1312 }
1313 Event::Keyboard(key) if key.state == KeyState::Pressed => {
1314 if matches!(
1315 &key.key,
1316 Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space)
1317 ) {
1318 if let Some(on_click) = &self.on_click {
1319 on_click.run(ctx);
1320 ctx.stop_propagation();
1321 }
1322 }
1323 }
1324 _ => {}
1325 }
1326 }
1327
1328 fn focus_policy(&self) -> FocusPolicy {
1329 FocusPolicy::Focusable
1330 }
1331
1332 fn activation_policy(&self) -> ActivationPolicy {
1333 ActivationPolicy::SuppressOnFocusOnly
1334 }
1335}
1336
1337impl<A: 'static> IntoView<A> for Button<A> {
1338 fn into_view(self) -> View<A> {
1339 let widget = ButtonWidget {
1340 layout: self.layout,
1341 disabled: self.disabled,
1342 on_click: self.on_click,
1343 style: self.style,
1344 };
1345 finish_view_sized(
1346 View::node(widget, vec![self.child]),
1347 self.flex_item,
1348 LayoutSizeHint::from_layout(self.layout),
1349 )
1350 }
1351}