Skip to main content

cranpose_liquid/widgets/
button.rs

1//! Glass buttons: capsule glass with a spring press (scale + specular boost)
2//! and haptic feedback.
3
4use crate::material::{Glass, GlassDynamics, GlassMorph, LiquidModifierExt, LiquidShape};
5use crate::motion::{liquid_press_scale, LiquidMotion};
6use crate::theme::{liquid_colors, liquid_typography};
7use cranpose_animation::{AnimationSpec, AnimationType, Easing};
8use cranpose_core::{mutableStateOf, remember};
9use cranpose_macros::composable;
10use cranpose_services::{default_haptics, HapticFeedback};
11use cranpose_ui::rememberMutableInteractionSource;
12use cranpose_ui::text::TextStyle;
13use cranpose_ui::widgets::{Box, BoxSpec, Text};
14use cranpose_ui::{Modifier, PointerEventKind, PointerInputScope, Size};
15use cranpose_ui_graphics::{Color, GraphicsLayer};
16use cranpose_ui_layout::Alignment;
17use std::cell::{Cell, RefCell};
18use std::rc::Rc;
19
20const ICON_BACKPLATE_DIAMETER_RATIO: f32 = 0.50;
21const ICON_BACKPLATE_GLYPH_RATIO: f32 = 0.28;
22
23/// Visual style of a [`GlassButton`].
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
25pub enum GlassButtonStyle {
26    /// Translucent glass with the label in the accent color.
27    #[default]
28    Glass,
29    /// Accent-tinted glass with white content — the primary action.
30    Prominent,
31    /// No material: just the label with press feedback (toolbar/text button).
32    Plain,
33    /// Destructive variant of `Plain`.
34    Destructive,
35}
36
37/// Configuration for [`GlassButton`] / [`GlassIconButton`].
38#[derive(Clone, Debug, Default, PartialEq)]
39pub struct GlassButtonSpec {
40    pub style: GlassButtonStyle,
41    /// Overrides the material (advanced).
42    pub glass: Option<Glass>,
43    /// Overrides the label/icon color (defaults per style).
44    pub content_color: Option<Color>,
45    /// Optional inner color disc for icon buttons. The outer material remains
46    /// clear glass; the disc colors only the icon's compact foreground core.
47    pub icon_backplate: Option<Color>,
48}
49
50impl GlassButtonSpec {
51    pub fn glass() -> Self {
52        Self::default()
53    }
54
55    pub fn prominent() -> Self {
56        Self {
57            style: GlassButtonStyle::Prominent,
58            ..Self::default()
59        }
60    }
61
62    pub fn plain() -> Self {
63        Self {
64            style: GlassButtonStyle::Plain,
65            ..Self::default()
66        }
67    }
68
69    pub fn destructive() -> Self {
70        Self {
71            style: GlassButtonStyle::Destructive,
72            ..Self::default()
73        }
74    }
75
76    pub fn with_glass(mut self, glass: Glass) -> Self {
77        self.glass = Some(glass);
78        self
79    }
80
81    pub fn with_content_color(mut self, color: Color) -> Self {
82        self.content_color = Some(color);
83        self
84    }
85
86    pub fn with_icon_backplate(mut self, color: Color) -> Self {
87        self.icon_backplate = Some(color);
88        self
89    }
90
91    /// The label color for this style under `colors`.
92    pub fn content_color(&self, colors: &crate::theme::LiquidColors) -> Color {
93        if let Some(color) = self.content_color {
94            return color;
95        }
96        match self.style {
97            GlassButtonStyle::Glass => colors.accent,
98            GlassButtonStyle::Prominent => colors.on_accent,
99            GlassButtonStyle::Plain => colors.accent,
100            GlassButtonStyle::Destructive => colors.destructive,
101        }
102    }
103
104    /// The glyph color for icon buttons: the reference nav/search circles
105    /// draw BLACK glyphs on plain glass (only prominent tints stay white).
106    pub fn icon_color(&self, colors: &crate::theme::LiquidColors) -> Color {
107        if let Some(color) = self.content_color {
108            return color;
109        }
110        match self.style {
111            GlassButtonStyle::Glass | GlassButtonStyle::Plain => colors.label,
112            GlassButtonStyle::Prominent => colors.on_accent,
113            GlassButtonStyle::Destructive => colors.destructive,
114        }
115    }
116
117    fn resolve_material(
118        &self,
119        colors: &crate::theme::LiquidColors,
120        foreground: Color,
121    ) -> Option<Glass> {
122        if let Some(glass) = &self.glass {
123            return Some(if glass.foreground.is_some() {
124                glass.clone()
125            } else {
126                glass
127                    .clone()
128                    .adaptive_frost(foreground, glass.adaptive_frost)
129            });
130        }
131        match self.style {
132            GlassButtonStyle::Glass => Some(Glass::regular().adaptive_frost(foreground, 0.65)),
133            GlassButtonStyle::Prominent => Some(
134                Glass::regular()
135                    .tint(colors.accent.with_alpha(0.75))
136                    .adaptive_frost(foreground, 0.65),
137            ),
138            GlassButtonStyle::Plain | GlassButtonStyle::Destructive => None,
139        }
140    }
141}
142
143/// One action in a [`GlassIconButtonGroup`].
144#[derive(Clone)]
145pub struct GlassIconButtonGroupItem {
146    spec: GlassButtonSpec,
147    icon_path: &'static str,
148    content_description: String,
149    on_click: Rc<RefCell<dyn FnMut()>>,
150}
151
152impl PartialEq for GlassIconButtonGroupItem {
153    fn eq(&self, other: &Self) -> bool {
154        self.spec == other.spec
155            && self.icon_path == other.icon_path
156            && self.content_description == other.content_description
157            && Rc::ptr_eq(&self.on_click, &other.on_click)
158    }
159}
160
161impl GlassIconButtonGroupItem {
162    pub fn new(
163        icon_path: &'static str,
164        content_description: impl Into<String>,
165        on_click: impl FnMut() + 'static,
166    ) -> Self {
167        Self {
168            spec: GlassButtonSpec::glass(),
169            icon_path,
170            content_description: content_description.into(),
171            on_click: Rc::new(RefCell::new(on_click)),
172        }
173    }
174
175    pub fn with_spec(mut self, spec: GlassButtonSpec) -> Self {
176        self.spec = spec;
177        self
178    }
179}
180
181/// Geometry and interaction material for [`GlassIconButtonGroup`].
182#[derive(Clone, Copy, Debug, PartialEq)]
183pub struct GlassIconButtonGroupSpec {
184    diameter: f32,
185    spacing: f32,
186    pressed_scale: f32,
187    glue_radius: f32,
188}
189
190impl GlassIconButtonGroupSpec {
191    pub fn new(diameter: f32) -> Self {
192        Self {
193            diameter: diameter.max(1.0),
194            ..Self::default()
195        }
196    }
197
198    pub fn with_spacing(mut self, spacing: f32) -> Self {
199        self.spacing = spacing.max(0.0);
200        self
201    }
202
203    pub fn with_pressed_scale(mut self, pressed_scale: f32) -> Self {
204        self.pressed_scale = pressed_scale.max(1.0);
205        self
206    }
207
208    pub fn with_glue_radius(mut self, glue_radius: f32) -> Self {
209        self.glue_radius = glue_radius.max(0.0);
210        self
211    }
212}
213
214impl Default for GlassIconButtonGroupSpec {
215    fn default() -> Self {
216        Self {
217            diameter: 44.0,
218            spacing: 8.0,
219            pressed_scale: 1.45,
220            glue_radius: 12.0,
221        }
222    }
223}
224
225fn icon_group_width(count: usize, spec: GlassIconButtonGroupSpec) -> f32 {
226    if count == 0 {
227        0.0
228    } else {
229        spec.diameter * count as f32 + spec.spacing * count.saturating_sub(1) as f32
230    }
231}
232
233fn icon_group_item_at(
234    x: f32,
235    y: f32,
236    count: usize,
237    spec: GlassIconButtonGroupSpec,
238) -> Option<usize> {
239    if !(0.0..=spec.diameter).contains(&y) {
240        return None;
241    }
242    let pitch = spec.diameter + spec.spacing;
243    let index = (x / pitch).floor() as isize;
244    if index < 0 || index as usize >= count {
245        return None;
246    }
247    let local_x = x - index as f32 * pitch;
248    (local_x <= spec.diameter).then_some(index as usize)
249}
250
251fn icon_group_neighbor_shapes(
252    count: usize,
253    active: usize,
254    spec: GlassIconButtonGroupSpec,
255    pad: f32,
256    center_y: f32,
257) -> Vec<(f32, f32, f32, f32, f32)> {
258    let pitch = spec.diameter + spec.spacing;
259    let contact_diameter = spec.diameter * 0.36;
260    let contact_offset = spec.diameter * 0.38;
261    (0..count)
262        .filter(|index| index.abs_diff(active) == 1)
263        .map(|index| {
264            let toward_active = if index < active { 1.0 } else { -1.0 };
265            (
266                pad + index as f32 * pitch + spec.diameter * 0.5 + toward_active * contact_offset,
267                center_y,
268                contact_diameter,
269                contact_diameter,
270                -1.0,
271            )
272        })
273        .collect()
274}
275
276/// A glass button. `content` composes the label (see [`GlassButton`] with
277/// [`Text`], or an [`crate::icons::Icon`] + text row).
278#[composable]
279#[allow(non_snake_case)]
280pub fn GlassButton(
281    modifier: Modifier,
282    spec: GlassButtonSpec,
283    on_click: impl Fn() + 'static,
284    content: impl FnMut() + 'static,
285) {
286    let colors = liquid_colors();
287    let interaction = rememberMutableInteractionSource();
288    let (pressed_modifier, pressed, content_alpha) =
289        liquid_press_scale(Modifier::empty(), interaction.clone(), 1.18);
290
291    let material = spec.resolve_material(&colors, spec.content_color(&colors));
292    let mut base = Modifier::empty();
293    if let Some(glass) = material {
294        let pressed_for_glass = pressed;
295        base = base.glass_effect_with(glass, move || GlassDynamics {
296            highlight_boost: if pressed_for_glass.get() { 0.85 } else { 0.0 },
297            ..Default::default()
298        });
299    }
300
301    let on_click = Rc::new(RefCell::new(on_click));
302    let base = base
303        .press_interaction_source(interaction)
304        .clickable(move |_point| {
305            default_haptics().perform(HapticFeedback::ImpactLight);
306            (on_click.borrow_mut())();
307        })
308        .padding_symmetric(16.0, 10.0);
309
310    // Touched glass turns more transparent: the label ghosts while pressed.
311    let content_layer = Modifier::empty().graphics_layer(move || GraphicsLayer {
312        alpha: content_alpha.get().clamp(0.0, 1.0),
313        ..Default::default()
314    });
315    let content = Rc::new(RefCell::new(content));
316    let button = base.then(modifier);
317    Box(pressed_modifier, BoxSpec::default(), move || {
318        let content = Rc::clone(&content);
319        let content_layer = content_layer.clone();
320        Box(
321            button.clone(),
322            BoxSpec::default().content_alignment(Alignment::CENTER),
323            move || {
324                let content = Rc::clone(&content);
325                Box(
326                    content_layer.clone(),
327                    BoxSpec::default().content_alignment(Alignment::CENTER),
328                    move || (content.borrow_mut())(),
329                );
330            },
331        );
332    });
333}
334
335/// Convenience text label styled for the enclosing button.
336#[composable]
337#[allow(non_snake_case)]
338pub fn GlassButtonLabel(text: impl Into<String>, spec: GlassButtonSpec) {
339    let typography = liquid_typography();
340    let color = spec.content_color(&liquid_colors());
341    let style = TextStyle {
342        span_style: cranpose_ui::text::SpanStyle {
343            color: Some(color),
344            ..typography.headline.span_style.clone()
345        },
346        ..typography.headline.clone()
347    };
348    Text(text.into(), Modifier::empty(), style);
349}
350
351#[composable]
352#[allow(non_snake_case)]
353pub(crate) fn GlassIconForeground(spec: GlassButtonSpec, diameter: f32, icon_path: &'static str) {
354    let colors = liquid_colors();
355    let icon_color = spec.icon_color(&colors);
356    if let Some(backplate) = spec.icon_backplate {
357        let backplate_diameter = diameter * ICON_BACKPLATE_DIAMETER_RATIO;
358        Box(
359            Modifier::empty()
360                .size(Size::new(backplate_diameter, backplate_diameter))
361                .draw_behind(move |scope| {
362                    scope.draw_circle(
363                        cranpose_ui_graphics::Brush::solid(backplate),
364                        cranpose_ui_graphics::Point::new(
365                            backplate_diameter * 0.5,
366                            backplate_diameter * 0.5,
367                        ),
368                        backplate_diameter * 0.5,
369                    );
370                }),
371            BoxSpec::default().content_alignment(Alignment::CENTER),
372            move || {
373                crate::icons::Icon(icon_path, diameter * ICON_BACKPLATE_GLYPH_RATIO, icon_color);
374            },
375        );
376    } else {
377        crate::icons::Icon(icon_path, diameter * 0.5, icon_color);
378    }
379}
380
381/// A circular glass icon button (44dp target).
382#[composable]
383#[allow(non_snake_case)]
384pub fn GlassIconButton(
385    modifier: Modifier,
386    spec: GlassButtonSpec,
387    diameter: f32,
388    on_click: impl Fn() + 'static,
389    icon_path: &'static str,
390) {
391    GlassIconButtonWithForegroundAlpha(modifier, spec, diameter, 1.0, on_click, icon_path);
392}
393
394#[composable]
395#[allow(non_snake_case)]
396pub(crate) fn GlassIconButtonWithForegroundAlpha(
397    modifier: Modifier,
398    spec: GlassButtonSpec,
399    diameter: f32,
400    foreground_alpha: f32,
401    on_click: impl Fn() + 'static,
402    icon_path: &'static str,
403) {
404    let colors = liquid_colors();
405    let interaction = rememberMutableInteractionSource();
406    let (pressed_modifier, pressed, content_alpha) =
407        liquid_press_scale(Modifier::empty(), interaction.clone(), 1.20);
408
409    let material = spec
410        .resolve_material(&colors, spec.icon_color(&colors))
411        .map(|glass| glass.shape(LiquidShape::Circle));
412    let mut base = Modifier::empty();
413    if let Some(glass) = material {
414        let pressed_for_glass = pressed;
415        base = base.glass_effect_with(glass, move || GlassDynamics {
416            highlight_boost: if pressed_for_glass.get() { 0.85 } else { 0.0 },
417            ..Default::default()
418        });
419    }
420
421    let on_click = Rc::new(RefCell::new(on_click));
422    let base = base
423        .press_interaction_source(interaction)
424        .clickable(move |_point| {
425            default_haptics().perform(HapticFeedback::ImpactLight);
426            (on_click.borrow_mut())();
427        })
428        .size(Size::new(diameter, diameter));
429
430    // The reference press: the icon ghosts while the glass lifts.
431    let content_layer = Modifier::empty().graphics_layer(move || GraphicsLayer {
432        alpha: content_alpha.get().clamp(0.0, 1.0) * foreground_alpha.clamp(0.0, 1.0),
433        ..Default::default()
434    });
435    let button = base.then(modifier);
436    Box(pressed_modifier, BoxSpec::default(), move || {
437        let foreground_spec = spec.clone();
438        let content_layer = content_layer.clone();
439        Box(
440            button.clone(),
441            BoxSpec::default().content_alignment(Alignment::CENTER),
442            move || {
443                let foreground_spec = foreground_spec.clone();
444                Box(
445                    content_layer.clone(),
446                    BoxSpec::default().content_alignment(Alignment::CENTER),
447                    move || GlassIconForeground(foreground_spec.clone(), diameter, icon_path),
448                );
449            },
450        );
451    });
452}
453
454/// A row of circular actions whose pressed glass can join adjacent members.
455/// Each member keeps its own base material and foreground; one transparent,
456/// persistent interaction field supplies the shared refraction and neck.
457#[composable]
458#[allow(non_snake_case)]
459pub fn GlassIconButtonGroup(
460    modifier: Modifier,
461    spec: GlassIconButtonGroupSpec,
462    items: Vec<GlassIconButtonGroupItem>,
463) {
464    let count = items.len();
465    if count == 0 {
466        return;
467    }
468
469    let colors = liquid_colors();
470    let live_items: Rc<RefCell<Vec<GlassIconButtonGroupItem>>> =
471        remember(|| Rc::new(RefCell::new(Vec::new()))).with(Rc::clone);
472    // A member that leaves the group dissolves in place instead of popping:
473    // the reference confirm disc turns translucent over the surviving "…"
474    // and is gone ~250 ms later (touched-up-state frames f_0350..f_0370).
475    let ghosts: Rc<RefCell<Vec<(GlassIconButtonGroupItem, usize)>>> =
476        remember(|| Rc::new(RefCell::new(Vec::new()))).with(Rc::clone);
477    let ghost_fade = remember(|| {
478        let runtime = cranpose_core::with_current_composer(|composer| composer.runtime_handle());
479        Rc::new(RefCell::new(cranpose_animation::Animatable::new(
480            0.0f32, runtime,
481        )))
482    })
483    .with(Rc::clone);
484    {
485        let previous = live_items.borrow();
486        if !previous.is_empty() && *previous != items {
487            let leavers: Vec<(GlassIconButtonGroupItem, usize)> = previous
488                .iter()
489                .enumerate()
490                .filter(|(_, member)| !items.contains(member))
491                .map(|(index, member)| (member.clone(), index))
492                .collect();
493            if !leavers.is_empty() {
494                *ghosts.borrow_mut() = leavers;
495                let mut fade = ghost_fade.borrow_mut();
496                fade.snapTo(1.0);
497                fade.animateTo(
498                    0.0,
499                    AnimationType::Tween(AnimationSpec::tween(250, Easing::EaseIn)),
500                );
501            }
502        }
503    }
504    let ghost_alpha = ghost_fade.borrow().state();
505    if !ghosts.borrow().is_empty() && ghost_alpha.get() <= 0.01 {
506        ghosts.borrow_mut().clear();
507    }
508    *live_items.borrow_mut() = items;
509    let render_items = live_items.borrow().clone();
510
511    let active = remember(|| mutableStateOf(None::<usize>)).with(|state| *state);
512    // The held disc rides the finger toward a neighbor (the reference press
513    // drifts and necks into the adjacent circle); None between gestures.
514    let drag_x = remember(|| mutableStateOf(None::<f32>)).with(|state| *state);
515    let last_active = remember(|| Rc::new(Cell::new(0usize))).with(Rc::clone);
516    if let Some(index) = active.get() {
517        last_active.set(index.min(count - 1));
518    }
519    let press_progress = cranpose_animation::animateFloatAsState(
520        if active.get().is_some() { 1.0 } else { 0.0 },
521        LiquidMotion::snappy(),
522        "glass-icon-group-press",
523    );
524
525    let width = icon_group_width(count, spec);
526    let gesture_items = Rc::clone(&live_items);
527    let gesture = Modifier::empty()
528        .size(Size::new(width, spec.diameter))
529        .pointer_input(count, move |scope: PointerInputScope| {
530            let gesture_items = Rc::clone(&gesture_items);
531            async move {
532                scope
533                    .await_pointer_event_scope(|await_scope| async move {
534                        let mut down_index = None::<usize>;
535                        loop {
536                            let event = await_scope.await_pointer_event().await;
537                            match event.kind {
538                                PointerEventKind::Down if down_index.is_none() => {
539                                    down_index = icon_group_item_at(
540                                        event.position.x,
541                                        event.position.y,
542                                        gesture_items.borrow().len(),
543                                        spec,
544                                    );
545                                    if let Some(index) = down_index {
546                                        active.set(Some(index));
547                                        drag_x.set(Some(event.position.x));
548                                        default_haptics().perform(HapticFeedback::Selection);
549                                        event.consume();
550                                    }
551                                }
552                                PointerEventKind::Move if down_index.is_some() => {
553                                    drag_x.set(Some(event.position.x));
554                                    event.consume();
555                                }
556                                PointerEventKind::Up => {
557                                    let pressed_index = down_index.take();
558                                    active.set(None);
559                                    drag_x.set(None);
560                                    if let Some(index) = pressed_index {
561                                        let released_index = icon_group_item_at(
562                                            event.position.x,
563                                            event.position.y,
564                                            gesture_items.borrow().len(),
565                                            spec,
566                                        );
567                                        if released_index == Some(index) {
568                                            let on_click = gesture_items
569                                                .borrow()
570                                                .get(index)
571                                                .map(|item| Rc::clone(&item.on_click));
572                                            if let Some(on_click) = on_click {
573                                                default_haptics()
574                                                    .perform(HapticFeedback::ImpactLight);
575                                                (on_click.borrow_mut())();
576                                            }
577                                        }
578                                        event.consume();
579                                    }
580                                }
581                                PointerEventKind::Cancel if down_index.take().is_some() => {
582                                    active.set(None);
583                                    drag_x.set(None);
584                                    event.consume();
585                                }
586                                _ => {}
587                            }
588                        }
589                    })
590                    .await;
591            }
592        })
593        .then(modifier);
594
595    Box(gesture, BoxSpec::default(), move || {
596        let pitch = spec.diameter + spec.spacing;
597        let active_index = last_active.get().min(count - 1);
598
599        // The union field owns the connection and shared refraction. It sits
600        // behind the item faces, and while pressed it carries the ACTIVE
601        // item's tint so the neck toward a neighbor flows in that material
602        // (the reference bridge is the confirm action's cyan, not plain
603        // glass); the tint alpha rides press activity, so the resting field
604        // stays a whisper.
605        let pad = spec.glue_radius + spec.diameter * (spec.pressed_scale - 1.0) * 0.5 + 4.0;
606        let node_width = width + pad * 2.0;
607        let node_height = spec.diameter * spec.pressed_scale + pad * 2.0;
608        let shared_progress = press_progress;
609        let shared_last_active = Rc::clone(&last_active);
610        let union_tint = render_items
611            .get(active_index)
612            .and_then(|item| {
613                item.spec
614                    .resolve_material(&colors, item.spec.icon_color(&colors))
615            })
616            .and_then(|material| material.tint)
617            .map(|tint| tint.with_alpha(0.45))
618            .unwrap_or(Color::WHITE.with_alpha(0.035));
619        let shared = Modifier::empty()
620            .required_size(Size::new(node_width, node_height))
621            .offset(-pad, (spec.diameter - node_height) * 0.5)
622            .glass_effect_with(
623                // Regular variant: the tint covers the whole union field
624                // uniformly, so the thin neck carries the material — the
625                // lens variant's interior ramp fades tint exactly there.
626                Glass::regular()
627                    .blur_radius(0.0)
628                    .tint(union_tint)
629                    .lift(0.0)
630                    .highlight(0.48)
631                    .shadow(false)
632                    .no_clip(),
633                move || {
634                    let progress = shared_progress.get().clamp(0.0, 1.0);
635                    let active_index = shared_last_active.get().min(count - 1);
636                    let center_y = node_height * 0.5;
637                    let rest_center = active_index as f32 * pitch + spec.diameter * 0.5;
638                    // Ride the finger toward a neighbor, one pitch at most:
639                    // approaching the next circle necks the union field.
640                    // Half a pitch keeps the neighbor distinct: the disc
641                    // leans and the glue stretches a thin neck instead of
642                    // the shapes overlapping outright.
643                    let ridden = drag_x
644                        .get()
645                        .map(|x| x.clamp(rest_center - pitch * 0.35, rest_center + pitch * 0.35))
646                        .unwrap_or(rest_center);
647                    let center_x = pad + rest_center + (ridden - rest_center) * progress;
648                    let diameter = spec.diameter * (1.0 + (spec.pressed_scale - 1.0) * progress);
649                    // The reference press concentrates saturation + a soft
650                    // gradient light under the FINGER (touched-up-state
651                    // recording), riding press activity.
652                    let touch = drag_x.get().map(|x| {
653                        (
654                            pad + x.clamp(0.0, node_width - 2.0 * pad),
655                            center_y,
656                            progress,
657                        )
658                    });
659                    GlassDynamics {
660                        activity: Some(progress),
661                        touch,
662                        morph: Some(GlassMorph {
663                            node_size: (node_width, node_height),
664                            primary: (center_x, center_y, diameter, diameter, -1.0),
665                            shapes: icon_group_neighbor_shapes(
666                                count,
667                                active_index,
668                                spec,
669                                pad,
670                                center_y,
671                            ),
672                            glue: spec.glue_radius * progress,
673                            ..Default::default()
674                        }),
675                        ..Default::default()
676                    }
677                },
678            );
679        Box(shared, BoxSpec::default(), || {});
680
681        // Independent base surfaces preserve each member's style and tint.
682        for (index, item) in render_items.iter().enumerate() {
683            let x = index as f32 * pitch;
684            let surface_progress = press_progress;
685            let item_is_active = index == active_index;
686            let outer = Modifier::empty()
687                .size(Size::new(spec.diameter, spec.diameter))
688                .offset(x, 0.0);
689            let rest_center = index as f32 * pitch + spec.diameter * 0.5;
690            let scale_layer = Modifier::empty().graphics_layer(move || {
691                let progress = if item_is_active {
692                    surface_progress.get().clamp(0.0, 1.0)
693                } else {
694                    0.0
695                };
696                let scale = 1.0 + (spec.pressed_scale - 1.0) * progress;
697                let ridden = if item_is_active {
698                    drag_x
699                        .get()
700                        .map(|x| x.clamp(rest_center - pitch * 0.35, rest_center + pitch * 0.35))
701                        .unwrap_or(rest_center)
702                } else {
703                    rest_center
704                };
705                GraphicsLayer {
706                    translation_x: (ridden - rest_center) * progress,
707                    scale_x: scale,
708                    scale_y: scale,
709                    ..Default::default()
710                }
711            });
712            let mut surface = Modifier::empty().size(Size::new(spec.diameter, spec.diameter));
713            if let Some(material) = item
714                .spec
715                .resolve_material(&colors, item.spec.icon_color(&colors))
716            {
717                let surface_progress = press_progress;
718                surface =
719                    surface.glass_effect_with(material.shape(LiquidShape::Circle), move || {
720                        let progress = surface_progress.get().clamp(0.0, 1.0);
721                        // The reference touch-up is an HDR-like lift of the
722                        // SAME material — highlight and saturation surge, no
723                        // recolor (tint stays put).
724                        GlassDynamics {
725                            highlight_boost: if item_is_active { 0.60 * progress } else { 0.0 },
726                            saturation_boost: if item_is_active { 0.85 * progress } else { 0.0 },
727                            ..Default::default()
728                        }
729                    });
730            }
731            Box(outer, BoxSpec::default(), move || {
732                let surface = surface.clone();
733                Box(scale_layer.clone(), BoxSpec::default(), move || {
734                    Box(surface.clone(), BoxSpec::default(), || {});
735                });
736            });
737        }
738
739        // The active foreground is absorbed into the rising material. Other
740        // members stay crisp and retain their independent ownership.
741        for (index, item) in render_items.iter().enumerate() {
742            let x = index as f32 * pitch;
743            let item_is_active = index == active_index;
744            let foreground_progress = press_progress;
745            let foreground_spec = item.spec.clone();
746            let icon_path = item.icon_path;
747            let description = item.content_description.clone();
748            let foreground = Modifier::empty()
749                .size(Size::new(spec.diameter, spec.diameter))
750                .offset(x, 0.0)
751                .graphics_layer(move || GraphicsLayer {
752                    alpha: if item_is_active {
753                        1.0 - foreground_progress.get().clamp(0.0, 1.0)
754                    } else {
755                        1.0
756                    },
757                    ..Default::default()
758                })
759                .semantics(move |config| {
760                    config.is_button = true;
761                    config.is_clickable = true;
762                    config.content_description = Some(description.clone());
763                });
764            Box(
765                foreground,
766                BoxSpec::default().content_alignment(Alignment::CENTER),
767                move || {
768                    GlassIconForeground(foreground_spec.clone(), spec.diameter, icon_path);
769                },
770            );
771        }
772
773        // Departed members: the same surface + glyph at their old slot,
774        // riding one shared fade to transparent. No gestures, no union
775        // membership — a purely optical afterimage.
776        for (ghost, ghost_index) in ghosts.borrow().iter() {
777            let x = *ghost_index as f32 * pitch;
778            let fade = ghost_alpha;
779            let ghost_layer = Modifier::empty()
780                .size(Size::new(spec.diameter, spec.diameter))
781                .offset(x, 0.0)
782                .graphics_layer(move || GraphicsLayer {
783                    alpha: fade.get().clamp(0.0, 1.0),
784                    ..Default::default()
785                });
786            let ghost_spec = ghost.spec.clone();
787            let ghost_icon = ghost.icon_path;
788            let surface = ghost
789                .spec
790                .resolve_material(&colors, ghost.spec.icon_color(&colors))
791                .map(|material| {
792                    Modifier::empty()
793                        .size(Size::new(spec.diameter, spec.diameter))
794                        .glass_effect(material.shape(LiquidShape::Circle))
795                });
796            Box(
797                ghost_layer,
798                BoxSpec::default().content_alignment(Alignment::CENTER),
799                move || {
800                    if let Some(surface) = surface.clone() {
801                        Box(surface, BoxSpec::default(), || {});
802                    }
803                    GlassIconForeground(ghost_spec.clone(), spec.diameter, ghost_icon);
804                },
805            );
806        }
807    });
808}
809
810#[cfg(test)]
811mod tests {
812    use super::*;
813
814    #[test]
815    fn icon_backplate_colors_only_the_compact_foreground_core() {
816        let blue = Color::from_rgb_u8(0, 122, 255);
817        let spec = GlassButtonSpec::glass()
818            .with_icon_backplate(blue)
819            .with_content_color(Color::WHITE);
820        assert_eq!(spec.style, GlassButtonStyle::Glass);
821        assert_eq!(spec.icon_backplate, Some(blue));
822        assert_eq!(spec.content_color, Some(Color::WHITE));
823        assert!(spec.glass.is_none());
824        assert!((0.49..=0.51).contains(&ICON_BACKPLATE_DIAMETER_RATIO));
825        assert!((0.27..=0.29).contains(&ICON_BACKPLATE_GLYPH_RATIO));
826
827        let colors = crate::theme::LiquidColors::light(blue);
828        let material = GlassButtonSpec::glass()
829            .resolve_material(&colors, colors.label)
830            .expect("glass button material");
831        assert_eq!(material.tint, None);
832        assert_eq!(material.resolve(&colors).tint, colors.glass_tint);
833    }
834
835    #[test]
836    fn neutral_button_tint_comes_from_the_theme_not_foreground_polarity() {
837        let accent = Color::from_rgb_u8(0, 122, 255);
838        for colors in [
839            crate::theme::LiquidColors::light(accent),
840            crate::theme::LiquidColors::dark(accent),
841        ] {
842            let material = GlassButtonSpec::glass()
843                .resolve_material(&colors, colors.label)
844                .expect("glass button material");
845            assert_eq!(material.tint, None);
846            assert_eq!(material.resolve(&colors).tint, colors.glass_tint);
847        }
848    }
849
850    #[test]
851    fn icon_button_group_builders_and_hit_regions_preserve_member_gaps() {
852        let spec = GlassIconButtonGroupSpec::new(44.0)
853            .with_spacing(8.0)
854            .with_pressed_scale(1.2)
855            .with_glue_radius(12.0);
856        assert_eq!(icon_group_width(2, spec), 96.0);
857        assert_eq!(icon_group_item_at(22.0, 22.0, 2, spec), Some(0));
858        assert_eq!(icon_group_item_at(48.0, 22.0, 2, spec), None);
859        assert_eq!(icon_group_item_at(74.0, 22.0, 2, spec), Some(1));
860        assert_eq!(icon_group_item_at(22.0, 50.0, 2, spec), None);
861
862        let shapes = icon_group_neighbor_shapes(4, 2, spec, 16.0, 38.0);
863        assert_eq!(shapes.len(), 2);
864        assert!((shapes[0].0 - (16.0 + 52.0 + 22.0 + 44.0 * 0.38)).abs() < 1e-5);
865        assert!((shapes[1].0 - (16.0 + 156.0 + 22.0 - 44.0 * 0.38)).abs() < 1e-5);
866        assert_eq!(shapes[0].2, 44.0 * 0.36);
867
868        let item = GlassIconButtonGroupItem::new("M0 0", "Confirm", || {})
869            .with_spec(GlassButtonSpec::prominent());
870        assert_eq!(item.content_description, "Confirm");
871        assert_eq!(item.spec.style, GlassButtonStyle::Prominent);
872    }
873}