Skip to main content

euv_ui/component/button/
impl.rs

1use super::*;
2
3/// Styling and click handler helpers for `EuvButton`.
4impl EuvButton {
5    /// Attaches a click callback invoked when the button is activated.
6    ///
7    /// # Arguments
8    ///
9    /// - `Self` - Source button.
10    /// - `F` - Click callback closure.
11    ///
12    /// # Returns
13    ///
14    /// - `Self` - Updated button.
15    #[must_use]
16    pub fn on_click<F>(mut self, callback: F) -> Self
17    where
18        F: FnMut(&UiEvent) + 'static,
19    {
20        self.set_on_click(Some(Rc::new(RefCell::new(callback))));
21        self
22    }
23
24    /// Sets the visual emphasis variant fluently.
25    ///
26    /// # Arguments
27    ///
28    /// - `Self` - Source button.
29    /// - `EuvButtonVariant` - Visual variant.
30    ///
31    /// # Returns
32    ///
33    /// - `Self` - Updated button.
34    #[must_use]
35    pub fn variant(mut self, variant: EuvButtonVariant) -> Self {
36        self.set_variant(variant);
37        self
38    }
39
40    /// Sets the control size tier fluently.
41    ///
42    /// # Arguments
43    ///
44    /// - `Self` - Source button.
45    /// - `EuvButtonSize` - Unified control size.
46    ///
47    /// # Returns
48    ///
49    /// - `Self` - Updated button.
50    #[must_use]
51    pub fn size(mut self, size: EuvButtonSize) -> Self {
52        self.set_size(size);
53        self
54    }
55
56    /// Applies the `Secondary` button variant fluently.
57    ///
58    /// # Arguments
59    ///
60    /// - `Self` - Source button.
61    ///
62    /// # Returns
63    ///
64    /// - `Self` - Secondary button.
65    #[must_use]
66    pub fn secondary(self) -> Self {
67        self.variant(EuvButtonVariant::Secondary)
68    }
69
70    /// Applies the `Outline` button variant fluently.
71    ///
72    /// # Arguments
73    ///
74    /// - `Self` - Source button.
75    ///
76    /// # Returns
77    ///
78    /// - `Self` - Outline button.
79    #[must_use]
80    pub fn outline(self) -> Self {
81        self.variant(EuvButtonVariant::Outline)
82    }
83
84    /// Applies the `Ghost` button variant fluently.
85    ///
86    /// # Arguments
87    ///
88    /// - `Self` - Source button.
89    ///
90    /// # Returns
91    ///
92    /// - `Self` - Ghost button.
93    #[must_use]
94    pub fn ghost(self) -> Self {
95        self.variant(EuvButtonVariant::Ghost)
96    }
97
98    /// Applies the `Destructive` button variant fluently.
99    ///
100    /// # Arguments
101    ///
102    /// - `Self` - Source button.
103    ///
104    /// # Returns
105    ///
106    /// - `Self` - Destructive button.
107    #[must_use]
108    pub fn destructive(self) -> Self {
109        self.variant(EuvButtonVariant::Destructive)
110    }
111
112    /// Applies the `Link` button variant fluently.
113    ///
114    /// # Arguments
115    ///
116    /// - `Self` - Source button.
117    ///
118    /// # Returns
119    ///
120    /// - `Self` - Link button.
121    #[must_use]
122    pub fn link(self) -> Self {
123        self.variant(EuvButtonVariant::Link)
124    }
125
126    /// Applies the `Small` unified control height fluently.
127    ///
128    /// # Arguments
129    ///
130    /// - `Self` - Source button.
131    ///
132    /// # Returns
133    ///
134    /// - `Self` - Small button.
135    #[must_use]
136    pub fn sm(self) -> Self {
137        self.size(EuvButtonSize::Small)
138    }
139
140    /// Applies the `Large` unified control height fluently.
141    ///
142    /// # Arguments
143    ///
144    /// - `Self` - Source button.
145    ///
146    /// # Returns
147    ///
148    /// - `Self` - Large button.
149    #[must_use]
150    pub fn lg(self) -> Self {
151        self.size(EuvButtonSize::Large)
152    }
153
154    /// Applies the square `Icon` control preset fluently.
155    ///
156    /// # Arguments
157    ///
158    /// - `Self` - Source button.
159    ///
160    /// # Returns
161    ///
162    /// - `Self` - Icon button.
163    #[must_use]
164    pub fn icon(self) -> Self {
165        self.size(EuvButtonSize::Icon)
166    }
167
168    /// Sets the disabled interaction state fluently.
169    ///
170    /// # Arguments
171    ///
172    /// - `Self` - Source button.
173    /// - `bool` - Whether the button is disabled.
174    ///
175    /// # Returns
176    ///
177    /// - `Self` - Updated button.
178    #[must_use]
179    pub fn disabled(mut self, disabled: bool) -> Self {
180        self.set_disabled(disabled);
181        self
182    }
183
184    /// Enables or disables automatic flex stretching (`flex_grow: 1.0`) inside horizontal rows.
185    ///
186    /// # Arguments
187    ///
188    /// - `Self` - Source button.
189    /// - `bool` - Whether the button stretches to fill remaining row width.
190    ///
191    /// # Returns
192    ///
193    /// - `Self` - Updated button.
194    #[must_use]
195    pub fn fill(mut self, enabled: bool) -> Self {
196        self.set_fill(enabled);
197        self
198    }
199
200    /// Resolves `(background, foreground, border_color)` for a button variant and interaction state using contrast-safe `SurfaceColors`.
201    ///
202    /// # Arguments
203    ///
204    /// - `EuvButtonVariant` - Visual emphasis variant.
205    /// - `ThemePalette` - Live theme palette.
206    /// - `bool` - Whether the button is hovered.
207    /// - `bool` - Whether the button is actively pressed.
208    ///
209    /// # Returns
210    ///
211    /// - `(Option<Color>, Color, Option<Color>)` - Paired `(background, foreground, border_color)`.
212    #[must_use]
213    pub fn state_colors(
214        variant: EuvButtonVariant,
215        palette: ThemePalette,
216        hovered: bool,
217        pressed: bool,
218    ) -> (Option<Color>, Color, Option<Color>) {
219        if pressed {
220            match variant {
221                EuvButtonVariant::Primary => {
222                    let s: SurfaceColors = palette.surface(SurfaceRole::Primary);
223                    let bg: Color = blend_over(s.get_fg().with_alpha(44), s.get_bg());
224                    let fg: Color = palette.readable_foreground_with(s.get_fg(), bg);
225                    (Some(bg), fg, None)
226                }
227                EuvButtonVariant::Secondary => {
228                    let s: SurfaceColors = palette.surface(SurfaceRole::Muted);
229                    let bg: Color = blend_over(s.get_fg().with_alpha(28), s.get_bg());
230                    let fg: Color = palette.readable_foreground_with(s.get_fg(), bg);
231                    (Some(bg), fg, None)
232                }
233                EuvButtonVariant::Destructive => {
234                    let s: SurfaceColors = palette.surface(SurfaceRole::Destructive);
235                    let bg: Color = blend_over(s.get_fg().with_alpha(44), s.get_bg());
236                    let fg: Color = palette.readable_foreground_with(s.get_fg(), bg);
237                    (Some(bg), fg, None)
238                }
239                EuvButtonVariant::Outline => {
240                    let s: SurfaceColors = palette.surface(SurfaceRole::Muted);
241                    let bg: Color = blend_over(s.get_fg().with_alpha(28), s.get_bg());
242                    let fg: Color = palette.readable_foreground_with(s.get_fg(), bg);
243                    (Some(bg), fg, Some(s.get_border()))
244                }
245                EuvButtonVariant::Ghost => {
246                    let s: SurfaceColors = palette.surface(SurfaceRole::Muted);
247                    let bg: Color = blend_over(s.get_fg().with_alpha(28), s.get_bg());
248                    let fg: Color = palette.readable_foreground_with(s.get_fg(), bg);
249                    (Some(bg), fg, None)
250                }
251                EuvButtonVariant::Link => {
252                    let s: SurfaceColors = palette.surface(SurfaceRole::Muted);
253                    let bg: Color = blend_over(s.get_fg().with_alpha(20), s.get_bg());
254                    let opaque_bg: Color = blend_over(bg, palette.get_background());
255                    let fg: Color =
256                        palette.readable_foreground_with(palette.get_primary(), opaque_bg);
257                    (Some(bg), fg, None)
258                }
259            }
260        } else if hovered {
261            match variant {
262                EuvButtonVariant::Primary => {
263                    let s: SurfaceColors = palette.surface(SurfaceRole::Primary);
264                    let bg: Color = blend_over(s.get_fg().with_alpha(24), s.get_bg());
265                    let fg: Color = palette.readable_foreground_with(s.get_fg(), bg);
266                    (Some(bg), fg, None)
267                }
268                EuvButtonVariant::Secondary => {
269                    let s: SurfaceColors = palette.surface(SurfaceRole::Accent);
270                    (Some(s.get_bg()), s.get_fg(), None)
271                }
272                EuvButtonVariant::Destructive => {
273                    let s: SurfaceColors = palette.surface(SurfaceRole::Destructive);
274                    let bg: Color = blend_over(s.get_fg().with_alpha(24), s.get_bg());
275                    let fg: Color = palette.readable_foreground_with(s.get_fg(), bg);
276                    (Some(bg), fg, None)
277                }
278                EuvButtonVariant::Outline => {
279                    let s: SurfaceColors = palette.surface(SurfaceRole::Accent);
280                    (Some(s.get_bg()), s.get_fg(), Some(s.get_border()))
281                }
282                EuvButtonVariant::Ghost => {
283                    let s: SurfaceColors = palette.surface(SurfaceRole::Accent);
284                    (Some(s.get_bg()), s.get_fg(), None)
285                }
286                EuvButtonVariant::Link => {
287                    let s: SurfaceColors = palette.surface(SurfaceRole::Muted);
288                    let opaque_bg: Color = blend_over(s.get_bg(), palette.get_background());
289                    let fg: Color =
290                        palette.readable_foreground_with(palette.get_primary(), opaque_bg);
291                    (Some(s.get_bg()), fg, None)
292                }
293            }
294        } else {
295            match variant {
296                EuvButtonVariant::Primary => {
297                    let s: SurfaceColors = palette.surface(SurfaceRole::Primary);
298                    (Some(s.get_bg()), s.get_fg(), None)
299                }
300                EuvButtonVariant::Secondary => {
301                    let s: SurfaceColors = palette.surface(SurfaceRole::Secondary);
302                    (Some(s.get_bg()), s.get_fg(), None)
303                }
304                EuvButtonVariant::Destructive => {
305                    let s: SurfaceColors = palette.surface(SurfaceRole::Destructive);
306                    (Some(s.get_bg()), s.get_fg(), None)
307                }
308                EuvButtonVariant::Outline => {
309                    let s: SurfaceColors = palette.surface(SurfaceRole::Card);
310                    (Some(s.get_bg()), s.get_fg(), Some(s.get_border()))
311                }
312                EuvButtonVariant::Ghost => {
313                    let s: SurfaceColors = palette.surface(SurfaceRole::Background);
314                    (None, s.get_fg(), None)
315                }
316                EuvButtonVariant::Link => {
317                    let fg: Color = palette
318                        .readable_foreground_with(palette.get_primary(), palette.get_background());
319                    (None, fg, None)
320                }
321            }
322        }
323    }
324
325    /// Writes variant and interaction-state paint onto `paint` and returns the paired text color.
326    ///
327    /// # Arguments
328    ///
329    /// - `&mut PaintStyle` - Target button paint style.
330    /// - `EuvButtonVariant` - Visual emphasis variant.
331    /// - `ThemeTokens` - Live theme tokens.
332    /// - `bool` - Whether the button is hovered.
333    /// - `bool` - Whether the button is actively pressed.
334    ///
335    /// # Returns
336    ///
337    /// - `Color` - Contrast-paired foreground text color.
338    pub fn apply_state_paint(
339        paint: &mut PaintStyle,
340        variant: EuvButtonVariant,
341        tokens: ThemeTokens,
342        hovered: bool,
343        pressed: bool,
344    ) -> Color {
345        let p: ThemePalette = tokens.get_palette();
346        let g: ThemeGeometry = tokens.get_geometry();
347        let (bg, fg, border_col): (Option<Color>, Color, Option<Color>) =
348            Self::state_colors(variant, p, hovered, pressed);
349        let has_shadow: bool = matches!(
350            variant,
351            EuvButtonVariant::Primary | EuvButtonVariant::Destructive | EuvButtonVariant::Outline
352        );
353        let border: Border = match border_col {
354            Some(col) => Border::new(g.get_border_width().max(0.0), col),
355            None => Border::default(),
356        };
357        let _: &mut PaintStyle = paint
358            .set_background(bg)
359            .set_border(border)
360            .set_shadow(if has_shadow {
361                Some(g.get_shadow_xs())
362            } else {
363                None
364            })
365            .set_focus_ring(None);
366        fg
367    }
368
369    /// Resolves the deterministic compiled `Style` for this button under `tokens`.
370    ///
371    /// # Arguments
372    ///
373    /// - `&Self` - Button configuration.
374    /// - `ThemeTokens` - Active theme tokens.
375    ///
376    /// # Returns
377    ///
378    /// - `Style` - Compiled cross-platform style.
379    #[must_use]
380    pub fn resolved_style_with_tokens(&self, tokens: ThemeTokens) -> Style {
381        let g: ThemeGeometry = tokens.get_geometry();
382        let size: EuvButtonSize = self.get_size();
383        let disabled: bool = self.get_disabled();
384        let variant: EuvButtonVariant = self.get_variant();
385        let (height, pad_x, font_sz, radius): (f32, f32, f32, f32) = match size {
386            EuvButtonSize::Small => (g.get_control_sm(), SPACE_SM, 12.0, g.get_radius_sm()),
387            EuvButtonSize::Default => (g.get_control_md(), SPACE_MD, 13.0, g.get_radius_md()),
388            EuvButtonSize::Large => (g.get_control_lg(), SPACE_XL, 14.0, g.get_radius_md()),
389            EuvButtonSize::Icon => (g.get_control_md(), 0.0, 13.0, RADIUS_PILL),
390        };
391        let mut style: Style = Style::default();
392        let layout: &mut LayoutStyle = style.get_mut_layout();
393        let _: &mut LayoutStyle = layout
394            .set_flex_direction(FlexDirection::Row)
395            .set_justify_content(JustifyContent::Center)
396            .set_align_items(AlignItems::Center)
397            .set_height(Length::Px(height))
398            .set_padding(Edges::symmetric(0.0, pad_x))
399            .set_overflow(Overflow::Hidden);
400        if size == EuvButtonSize::Icon {
401            let _: &mut LayoutStyle = layout.set_width(Length::Px(height));
402        } else if self.get_fill() {
403            let _: &mut LayoutStyle = layout.set_flex_grow(1.0).set_flex_shrink(1.0);
404        }
405        let paint: &mut PaintStyle = style.get_mut_paint();
406        let _: &mut PaintStyle = paint
407            .set_radius(CornerRadius::all(radius.max(0.0)))
408            .set_cursor(if disabled {
409                CursorIcon::NotAllowed
410            } else {
411                CursorIcon::Pointer
412            });
413        let text_col: Color = Self::apply_state_paint(paint, variant, tokens, false, false);
414        if disabled {
415            let _: &mut PaintStyle = paint.set_opacity(0.5);
416        }
417        let _: &mut TextStyle = style
418            .get_mut_text()
419            .set_font_size(font_sz)
420            .set_weight(FontWeight::Medium)
421            .set_color(text_col);
422        style.with_overrides(self.get_style())
423    }
424
425    /// Resolves the deterministic compiled `Style` for this button.
426    ///
427    /// # Arguments
428    ///
429    /// - `&Self` - Button configuration.
430    ///
431    /// # Returns
432    ///
433    /// - `Style` - Compiled cross-platform style.
434    #[inline(always)]
435    #[must_use]
436    pub fn resolved_style(&self) -> Style {
437        self.resolved_style_with_tokens(self.get_tokens())
438    }
439}
440
441/// Declarative `#[component]` implementation for `EuvButton`.
442#[component]
443/// Inherent implementation of [`EuvButton`].
444impl EuvButton {
445    /// Renders `EuvButton` into the ambient framework-managed `Context`.
446    ///
447    /// Variant backgrounds, borders, and paired foreground text colors are owned by a reactive `Effect` tracking
448    /// hover, press, and the live ambient theme so every interactive state preserves `>= 4.5:1` contrast without
449    /// stale colors after theme switches.
450    ///
451    /// # Arguments
452    ///
453    /// - `&Self` - Component descriptor reference.
454    ///
455    /// # Returns
456    ///
457    /// - `NodeId` - Mounted root scene node handle.
458    fn render(&self) -> NodeId {
459        let mut ctx: Context = current_context();
460        let base_tokens: ThemeTokens = self.get_tokens();
461        let init_tok: ThemeTokens = live_tokens_untracked(base_tokens);
462        let variant: EuvButtonVariant = self.get_variant();
463        let style: Style = self.resolved_style_with_tokens(init_tok);
464        let text_color: Color = style.get_text().get_color();
465        let font_sz: f32 = style.get_text().get_font_size();
466        let font_wt: FontWeight = style.get_text().get_weight();
467        let disabled: bool = self.get_disabled();
468        let Self {
469            label, on_click, ..
470        } = self;
471        let mut a11y: A11yProps = A11yProps::new(A11yRole::Button, label.clone());
472        let _: &mut A11yProps = a11y.set_disabled(disabled);
473        let handler_opt: Option<UiEventHandler> = if !disabled {
474            on_click.as_ref().map(Rc::clone)
475        } else {
476            None
477        };
478        let mut txt_st: Style = Style::default();
479        let _: &mut LayoutStyle = txt_st
480            .get_mut_layout()
481            .set_max_width(Length::Percent(100.0));
482        let _: &mut TextStyle = txt_st
483            .get_mut_text()
484            .set_color(text_color)
485            .set_font_size(font_sz)
486            .set_weight(font_wt)
487            .set_align(TextAlign::Center)
488            .set_overflow(TextOverflow::Ellipsis);
489        let (btn_node, txt_node): (NodeId, NodeId) = ctx.get_scene().with_write(
490            |tree: &mut SceneTree| {
491                let btn_node: NodeId = tree.create_view(style);
492                if let Some(node) = tree.get_node_mut(btn_node) {
493                    let _: &mut SceneNode = node.set_a11y(Some(a11y));
494                    if let Some(handler_rc) = handler_opt {
495                        let _: &mut EventHandlers =
496                            node.get_mut_handlers().set_on_click(Some(handler_rc));
497                        let _: &mut InteractionState =
498                            node.get_mut_interaction().set_focusable(true);
499                    }
500                    if !disabled {
501                        let mut hover_paint: PaintStyle = style.get_paint();
502                        let _: Color = Self::apply_state_paint(
503                            &mut hover_paint,
504                            variant,
505                            init_tok,
506                            true,
507                            false,
508                        );
509                        let _: &mut SceneNode = node.set_hover_style(Some(hover_paint));
510                    }
511                }
512                let txt_node: NodeId = tree.create_text(label.clone(), txt_st);
513                tree.append_child(btn_node, txt_node);
514                (btn_node, txt_node)
515            },
516            (NodeId::default(), NodeId::default()),
517        );
518        let hovered_sig: Signal<bool> = Signal::new(false);
519        let pressed_sig: Signal<bool> = Signal::new(false);
520        if !disabled {
521            ctx.on_hover(btn_node, move |ev: &UiEvent| match ev.get_kind() {
522                UiEventKind::PointerEnter => {
523                    let _: bool = hovered_sig.set_if_changed(true);
524                }
525                UiEventKind::PointerLeave => {
526                    let _: bool = hovered_sig.set_if_changed(false);
527                    let _: bool = pressed_sig.set_if_changed(false);
528                }
529                _ => {}
530            });
531            ctx.on_pointer_down(btn_node, move |_: &UiEvent| {
532                let _: bool = pressed_sig.set_if_changed(true);
533            });
534            ctx.on_pointer_up(btn_node, move |_: &UiEvent| {
535                let _: bool = pressed_sig.set_if_changed(false);
536            });
537            ctx.on_pointer_cancel(btn_node, move |_: &UiEvent| {
538                let _: bool = hovered_sig.set_if_changed(false);
539                let _: bool = pressed_sig.set_if_changed(false);
540            });
541        }
542        let handle: SceneHandle = ctx.get_scene().clone();
543        let app_state_sig: Signal<AppState> = ctx.get_app_state();
544        let prev_state: Cell<(bool, bool, ThemeKey)> = Cell::new((false, false, init_tok.key()));
545        let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
546            let _: Effect = Effect::new(move || {
547                if app_state_sig.get() != AppState::Active {
548                    let _: bool = hovered_sig.set_if_changed(false);
549                    let _: bool = pressed_sig.set_if_changed(false);
550                }
551            });
552            Effect::new(move || {
553                let is_hovered: bool = !disabled && hovered_sig.get();
554                let is_pressed: bool = !disabled && pressed_sig.get();
555                let tok: ThemeTokens = use_live_tokens(base_tokens);
556                let (old_h, old_p, old_key): (bool, bool, ThemeKey) =
557                    prev_state.replace((is_hovered, is_pressed, tok.key()));
558                if old_h == is_hovered && old_p == is_pressed && old_key == tok.key() {
559                    return;
560                }
561                handle.with_write(
562                    |tree: &mut SceneTree| {
563                        let mut fg_color: Color = text_color;
564                        if let Some(node) = tree.get_node_mut(btn_node) {
565                            let st: &mut Style = node.get_mut_style();
566                            fg_color = Self::apply_state_paint(
567                                st.get_mut_paint(),
568                                variant,
569                                tok,
570                                is_hovered,
571                                is_pressed,
572                            );
573                            let _: &mut TextStyle = st.get_mut_text().set_color(fg_color);
574                            if !disabled {
575                                let mut hover_paint: PaintStyle = st.get_paint();
576                                if !is_pressed {
577                                    let _: Color = Self::apply_state_paint(
578                                        &mut hover_paint,
579                                        variant,
580                                        tok,
581                                        true,
582                                        false,
583                                    );
584                                }
585                                let _: &mut SceneNode = node.set_hover_style(Some(hover_paint));
586                            }
587                            tree.mark_dirty(btn_node, DIRTY_PAINT);
588                        }
589                        if let Some(txt) = tree.get_node_mut(txt_node) {
590                            let _: &mut TextStyle =
591                                txt.get_mut_style().get_mut_text().set_color(fg_color);
592                            tree.mark_dirty(txt_node, DIRTY_PAINT);
593                        }
594                    },
595                    (),
596                );
597            })
598        });
599        ctx.get_scene().with_write(
600            |tree: &mut SceneTree| {
601                mark_theme_owned(tree, &[btn_node, txt_node]);
602                tree.attach_scope(btn_node, scope);
603            },
604            (),
605        );
606        btn_node
607    }
608}