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    /// - `CallbackFn` - Click callback closure.
11    ///
12    /// # Returns
13    ///
14    /// - `Self` - Updated button.
15    #[must_use]
16    pub fn on_click<CallbackFn>(mut self, callback: CallbackFn) -> Self
17    where
18        CallbackFn: 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 small(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 large(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        let role: InteractionRole = match variant {
220            EuvButtonVariant::Primary => InteractionRole::SolidPrimary,
221            EuvButtonVariant::Secondary => InteractionRole::SecondarySurface,
222            EuvButtonVariant::Destructive => InteractionRole::SolidDestructive,
223            EuvButtonVariant::Outline => InteractionRole::OutlineSurface,
224            EuvButtonVariant::Ghost => InteractionRole::GhostSurface,
225            EuvButtonVariant::Link => InteractionRole::LinkSurface,
226        };
227        let surface: SurfaceColors = palette.interaction_colors(role, false, hovered, pressed);
228        let bg_opt: Option<Color> = if surface.get_bg().get_alpha() == 0 {
229            None
230        } else {
231            Some(surface.get_bg())
232        };
233        let border_opt: Option<Color> = match variant {
234            EuvButtonVariant::Outline => Some(surface.get_border()),
235            _ => None,
236        };
237        (bg_opt, surface.get_fg(), border_opt)
238    }
239
240    /// Writes variant and interaction-state paint onto `paint` and returns the paired text color.
241    ///
242    /// # Arguments
243    ///
244    /// - `&mut PaintStyle` - Target button paint style.
245    /// - `EuvButtonVariant` - Visual emphasis variant.
246    /// - `ThemeTokens` - Live theme tokens.
247    /// - `bool` - Whether the button is hovered.
248    /// - `bool` - Whether the button is actively pressed.
249    ///
250    /// # Returns
251    ///
252    /// - `Color` - Contrast-paired foreground text color.
253    pub fn apply_state_paint(
254        paint: &mut PaintStyle,
255        variant: EuvButtonVariant,
256        tokens: ThemeTokens,
257        hovered: bool,
258        pressed: bool,
259    ) -> Color {
260        let theme_palette: ThemePalette = tokens.get_palette();
261        let geometry: ThemeGeometry = tokens.get_geometry();
262        let (bg, fg, border_col): (Option<Color>, Color, Option<Color>) =
263            Self::state_colors(variant, theme_palette, hovered, pressed);
264        let has_shadow: bool = matches!(
265            variant,
266            EuvButtonVariant::Primary | EuvButtonVariant::Destructive | EuvButtonVariant::Outline
267        );
268        let border: Border = match border_col {
269            Some(col) => Border::new(geometry.get_border_width().max(0.0), col),
270            None => Border::default(),
271        };
272        let _: &mut PaintStyle = paint
273            .set_background(bg)
274            .set_border(border)
275            .set_shadow(if has_shadow {
276                Some(geometry.get_shadow_xs())
277            } else {
278                None
279            })
280            .set_focus_ring(None);
281        fg
282    }
283
284    /// Resolves the deterministic compiled `Style` for this button under `tokens`.
285    ///
286    /// # Arguments
287    ///
288    /// - `&Self` - Button configuration.
289    /// - `ThemeTokens` - Active theme tokens.
290    ///
291    /// # Returns
292    ///
293    /// - `Style` - Compiled cross-platform style.
294    #[must_use]
295    pub fn resolved_style_with_tokens(&self, tokens: ThemeTokens) -> Style {
296        let geometry: ThemeGeometry = tokens.get_geometry();
297        let size: EuvButtonSize = self.get_size();
298        let disabled: bool = self.get_disabled();
299        let variant: EuvButtonVariant = self.get_variant();
300        let (height, pad_x, font_sz, radius): (f32, f32, f32, f32) = match size {
301            EuvButtonSize::Small => (
302                geometry.get_control_sm(),
303                SPACE_SM,
304                12.0,
305                geometry.get_radius_sm(),
306            ),
307            EuvButtonSize::Default => (
308                geometry.get_control_md(),
309                SPACE_MD,
310                13.0,
311                geometry.get_radius_md(),
312            ),
313            EuvButtonSize::Large => (
314                geometry.get_control_lg(),
315                SPACE_XL,
316                14.0,
317                geometry.get_radius_md(),
318            ),
319            EuvButtonSize::Icon => (geometry.get_control_md(), 0.0, 13.0, RADIUS_PILL),
320        };
321        let mut style: Style = Style::default();
322        let layout: &mut LayoutStyle = style.get_mut_layout();
323        let _: &mut LayoutStyle = layout
324            .set_flex_direction(FlexDirection::Row)
325            .set_justify_content(JustifyContent::Center)
326            .set_align_items(AlignItems::Center)
327            .set_height(Length::Px(height))
328            .set_padding(Edges::symmetric(0.0, pad_x))
329            .set_overflow(Overflow::Hidden);
330        if size == EuvButtonSize::Icon {
331            let _: &mut LayoutStyle = layout.set_width(Length::Px(height));
332        } else if self.get_fill() {
333            let _: &mut LayoutStyle = layout
334                .set_flex_grow(1.0)
335                .set_flex_shrink(1.0)
336                .set_flex_basis(Length::Px(0.0))
337                .set_min_width(Length::Px(72.0));
338        } else if variant == EuvButtonVariant::Link {
339            let _: &mut LayoutStyle = layout.set_align_self(AlignSelf::Start);
340        }
341        let paint: &mut PaintStyle = style.get_mut_paint();
342        let _: &mut PaintStyle = paint
343            .set_radius(CornerRadius::all(radius.max(0.0)))
344            .set_cursor(if disabled {
345                CursorIcon::NotAllowed
346            } else {
347                CursorIcon::Pointer
348            });
349        let text_col: Color = Self::apply_state_paint(paint, variant, tokens, false, false);
350        if disabled {
351            let _: &mut PaintStyle = paint.set_opacity(0.5);
352        }
353        let _: &mut TextStyle = style
354            .get_mut_text()
355            .set_font_size(font_sz)
356            .set_weight(FontWeight::Medium)
357            .set_color(text_col);
358        style.with_overrides(self.get_style())
359    }
360
361    /// Resolves the deterministic compiled `Style` for this button.
362    ///
363    /// # Arguments
364    ///
365    /// - `&Self` - Button configuration.
366    ///
367    /// # Returns
368    ///
369    /// - `Style` - Compiled cross-platform style.
370    #[inline(always)]
371    #[must_use]
372    pub fn resolved_style(&self) -> Style {
373        self.resolved_style_with_tokens(self.get_tokens())
374    }
375}
376
377/// Declarative `#[component]` implementation for `EuvButton`.
378#[component]
379/// Inherent implementation of [`EuvButton`].
380impl EuvButton {
381    /// Renders `EuvButton` into the ambient framework-managed `Context`.
382    ///
383    /// Variant backgrounds, borders, and paired foreground text colors are owned by a reactive `Effect` tracking
384    /// hover, press, and the live ambient theme so every interactive state preserves `>= 4.5:1` contrast without
385    /// stale colors after theme switches.
386    ///
387    /// # Arguments
388    ///
389    /// - `&Self` - Component descriptor reference.
390    ///
391    /// # Returns
392    ///
393    /// - `NodeId` - Mounted root scene node handle.
394    fn render(&self) -> NodeId {
395        let mut ctx: Context = current_context();
396        let base_tokens: ThemeTokens = self.get_tokens();
397        let init_tok: ThemeTokens = live_tokens_untracked(base_tokens);
398        let variant: EuvButtonVariant = self.get_variant();
399        let style: Style = self.resolved_style_with_tokens(init_tok);
400        let text_color: Color = style.get_text().get_color();
401        let font_sz: f32 = style.get_text().get_font_size();
402        let font_wt: FontWeight = style.get_text().get_weight();
403        let disabled: bool = self.get_disabled();
404        let Self {
405            label, on_click, ..
406        } = self;
407        let mut a11y: A11yProps = A11yProps::new(A11yRole::Button, label.clone());
408        let _: &mut A11yProps = a11y.set_disabled(disabled);
409        let handler_opt: Option<UiEventHandler> = if !disabled {
410            on_click.as_ref().map(Rc::clone)
411        } else {
412            None
413        };
414        let txt_st: Style = style! {
415            FlexShrink(1.0)
416            MinWidth(Length::Px(0.0))
417            MaxWidth(Length::Percent(100.0))
418            Overflow::Hidden
419            TextColor(text_color)
420            FontSize(font_sz)
421            font_wt
422            TextAlign::Center
423            TextOverflow::Ellipsis
424        };
425        let (btn_node, txt_node): (NodeId, NodeId) = ctx.get_scene().with_write(
426            |tree: &mut SceneTree| {
427                let btn_node: NodeId = tree.create_view(style);
428                if let Some(node) = tree.get_node_mut(btn_node) {
429                    let _: &mut SceneNode = node.set_a11y(Some(a11y));
430                    if let Some(handler_rc) = handler_opt {
431                        let _: &mut EventHandlers =
432                            node.get_mut_handlers().set_on_click(Some(handler_rc));
433                        let _: &mut InteractionState =
434                            node.get_mut_interaction().set_focusable(true);
435                    }
436                    if !disabled {
437                        let mut hover_paint: PaintStyle = style.get_paint();
438                        let _: Color = Self::apply_state_paint(
439                            &mut hover_paint,
440                            variant,
441                            init_tok,
442                            true,
443                            false,
444                        );
445                        let _: &mut SceneNode = node.set_hover_style(Some(hover_paint));
446                    }
447                }
448                let txt_node: NodeId = tree.create_text(label.clone(), txt_st);
449                tree.append_child(btn_node, txt_node);
450                (btn_node, txt_node)
451            },
452            (NodeId::default(), NodeId::default()),
453        );
454        let hovered_sig: Signal<bool> = Signal::new(false);
455        let pressed_sig: Signal<bool> = Signal::new(false);
456        if !disabled {
457            ctx.on_hover(btn_node, move |ui_event: &UiEvent| {
458                match ui_event.get_kind() {
459                    UiEventKind::PointerEnter => {
460                        let _: bool = hovered_sig.set_if_changed(true);
461                    }
462                    UiEventKind::PointerLeave => {
463                        let _: bool = hovered_sig.set_if_changed(false);
464                        let _: bool = pressed_sig.set_if_changed(false);
465                    }
466                    _ => {}
467                }
468            });
469            ctx.on_pointer_down(btn_node, move |_: &UiEvent| {
470                let _: bool = pressed_sig.set_if_changed(true);
471            });
472            ctx.on_pointer_up(btn_node, move |_: &UiEvent| {
473                let _: bool = pressed_sig.set_if_changed(false);
474            });
475            ctx.on_pointer_cancel(btn_node, move |_: &UiEvent| {
476                let _: bool = hovered_sig.set_if_changed(false);
477                let _: bool = pressed_sig.set_if_changed(false);
478            });
479        }
480        let handle: SceneHandle = ctx.get_scene().clone();
481        let app_state_sig: Signal<AppState> = ctx.get_app_state();
482        let prev_state: Cell<(bool, bool, ThemeKey)> = Cell::new((false, false, init_tok.key()));
483        let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
484            let _: Effect = Effect::new(move || {
485                if app_state_sig.get() != AppState::Active {
486                    let _: bool = hovered_sig.set_if_changed(false);
487                    let _: bool = pressed_sig.set_if_changed(false);
488                }
489            });
490            Effect::new(move || {
491                let is_hovered: bool = !disabled && hovered_sig.get();
492                let is_pressed: bool = !disabled && pressed_sig.get();
493                let tok: ThemeTokens = use_live_tokens(base_tokens);
494                let (old_h, old_p, old_key): (bool, bool, ThemeKey) =
495                    prev_state.replace((is_hovered, is_pressed, tok.key()));
496                if old_h == is_hovered && old_p == is_pressed && old_key == tok.key() {
497                    return;
498                }
499                handle.with_write(
500                    |tree: &mut SceneTree| {
501                        let mut fg_color: Color = text_color;
502                        if let Some(node) = tree.get_node_mut(btn_node) {
503                            let computed_style: &mut Style = node.get_mut_style();
504                            fg_color = Self::apply_state_paint(
505                                computed_style.get_mut_paint(),
506                                variant,
507                                tok,
508                                is_hovered,
509                                is_pressed,
510                            );
511                            let _: &mut TextStyle =
512                                computed_style.get_mut_text().set_color(fg_color);
513                            if !disabled {
514                                let mut hover_paint: PaintStyle = computed_style.get_paint();
515                                if !is_pressed {
516                                    let _: Color = Self::apply_state_paint(
517                                        &mut hover_paint,
518                                        variant,
519                                        tok,
520                                        true,
521                                        false,
522                                    );
523                                }
524                                let _: &mut SceneNode = node.set_hover_style(Some(hover_paint));
525                            }
526                            tree.mark_dirty(btn_node, DIRTY_PAINT);
527                        }
528                        if let Some(txt) = tree.get_node_mut(txt_node) {
529                            let _: &mut TextStyle =
530                                txt.get_mut_style().get_mut_text().set_color(fg_color);
531                            tree.mark_dirty(txt_node, DIRTY_PAINT);
532                        }
533                    },
534                    (),
535                );
536            })
537        });
538        ctx.get_scene().with_write(
539            |tree: &mut SceneTree| {
540                mark_theme_owned(tree, &[btn_node, txt_node]);
541                tree.attach_scope(btn_node, scope);
542            },
543            (),
544        );
545        btn_node
546    }
547}