1use std::{
2 cell::{Cell, RefCell},
3 rc::Rc,
4};
5
6use cranpose_core::{MutableState, SideEffect, mutableStateOf, remember, rememberMutableStateOf};
7use cranpose_foundation::PointerId;
8use cranpose_macros::composable;
9use cranpose_ui::{
10 Modifier, PointerEventKind, PointerInputScope, PressInteractionPress, SemanticsWidgetRole,
11 Size, rememberMutableInteractionSource,
12 text::{FontWeight, SpanStyle, TextStyle, TextUnit},
13 widgets::{Box, BoxSpec, Column, ColumnSpec, PopupDismissableWhen, Row, RowSpec, Text},
14};
15use cranpose_ui_graphics::{Brush, Color, CornerRadii, GraphicsLayer, Point, Rect, RenderEffect};
16use cranpose_ui_layout::VerticalAlignment;
17
18use crate::{
19 material::{Glass, GlassDynamics, GlassMorph, GlassShadow, LiquidModifierExt, LiquidShape},
20 theme::{liquid_colors, liquid_typography},
21 widgets::content_scope::ScopeContent,
22};
23
24#[derive(Clone, Debug, PartialEq)]
26pub struct LiquidMenuItem {
27 pub label: String,
28 pub icon: Option<&'static str>,
30 pub checked: bool,
32 pub destructive: bool,
34 pub section_start: bool,
36 pub header: bool,
38 pub keeps_open: bool,
41 pub subtitle: Option<String>,
45}
46
47impl LiquidMenuItem {
48 pub fn new(label: impl Into<String>) -> Self {
49 Self {
50 label: label.into(),
51 icon: None,
52 checked: false,
53 destructive: false,
54 section_start: false,
55 header: false,
56 keeps_open: false,
57 subtitle: None,
58 }
59 }
60
61 pub fn header(label: impl Into<String>) -> Self {
63 Self {
64 header: true,
65 ..Self::new(label)
66 }
67 }
68
69 pub fn icon(mut self, icon: &'static str) -> Self {
70 self.icon = Some(icon);
71 self
72 }
73
74 pub fn checked(mut self, checked: bool) -> Self {
75 self.checked = checked;
76 self
77 }
78
79 pub fn destructive(mut self) -> Self {
80 self.destructive = true;
81 self
82 }
83
84 pub fn section_start(mut self) -> Self {
85 self.section_start = true;
86 self
87 }
88
89 pub fn keeps_open(mut self) -> Self {
92 self.keeps_open = true;
93 self
94 }
95
96 pub fn subtitle(mut self, subtitle: impl Into<String>) -> Self {
98 self.subtitle = Some(subtitle.into());
99 self
100 }
101}
102
103#[derive(Clone, Debug, PartialEq)]
106pub struct LiquidMenuAbsorbedSource {
107 pub rect: Rect,
108 pub spec: crate::widgets::GlassButtonSpec,
109 pub diameter: f32,
110 pub icon_path: &'static str,
111}
112
113#[derive(Clone, Debug, Default, PartialEq)]
115pub struct LiquidDropdownMenuSpec {
116 pub menu: LiquidMenuSpec,
117 pub absorbed: Vec<LiquidMenuAbsorbedSource>,
118}
119
120impl LiquidDropdownMenuSpec {
121 pub fn menu(mut self, menu: LiquidMenuSpec) -> Self {
122 self.menu = menu;
123 self
124 }
125
126 pub fn absorbed(mut self, absorbed: Vec<LiquidMenuAbsorbedSource>) -> Self {
127 self.absorbed = absorbed;
128 self
129 }
130}
131
132#[derive(Clone)]
133struct LiquidMenuEntry {
134 item: LiquidMenuItem,
135 action: Option<Rc<dyn Fn()>>,
136}
137
138pub struct LiquidMenuScope {
144 entries: ScopeContent<LiquidMenuEntry>,
145 section_next: Cell<bool>,
146}
147
148impl LiquidMenuScope {
149 pub fn item(&self, item: LiquidMenuItem, on_click: impl Fn() + 'static) {
152 self.push(LiquidMenuEntry {
153 item,
154 action: Some(Rc::new(on_click)),
155 });
156 }
157
158 pub fn header(&self, label: impl Into<String>) {
160 self.push(LiquidMenuEntry {
161 item: LiquidMenuItem::header(label),
162 action: None,
163 });
164 }
165
166 pub fn separator(&self) {
168 self.section_next.set(true);
169 }
170
171 fn push(&self, mut entry: LiquidMenuEntry) {
172 if self.section_next.replace(false) {
173 entry.item.section_start = true;
174 }
175 self.entries.push(entry);
176 }
177}
178
179fn collect_entries(content: impl FnOnce(&LiquidMenuScope)) -> Vec<LiquidMenuEntry> {
180 ScopeContent::collect(
181 |entries| LiquidMenuScope {
182 entries,
183 section_next: Cell::new(false),
184 },
185 content,
186 )
187}
188
189impl LiquidMenuAbsorbedSource {
190 pub fn new(
191 rect: Rect,
192 spec: crate::widgets::GlassButtonSpec,
193 diameter: f32,
194 icon_path: &'static str,
195 ) -> Self {
196 Self {
197 rect,
198 spec,
199 diameter,
200 icon_path,
201 }
202 }
203}
204
205#[derive(Clone, Copy, Debug, PartialEq)]
207pub struct LiquidMenuSpec {
208 pub width: f32,
211}
212
213impl Default for LiquidMenuSpec {
214 fn default() -> Self {
215 Self { width: MENU_WIDTH }
216 }
217}
218
219impl LiquidMenuSpec {
220 pub fn new(width: f32) -> Self {
221 Self {
222 width: if width.is_finite() {
223 width.max(120.0)
224 } else {
225 MENU_WIDTH
226 },
227 }
228 }
229}
230
231const MENU_WIDTH: f32 = 250.0;
232const MENU_SHADOW_PAD: f32 = 48.0;
233const MENU_RADIUS: f32 = 32.0;
234const MENU_GROW_DELAY: f32 = 0.050;
235const MENU_SOURCE_SEPARATE_END: f32 = 0.06;
236const MENU_CARD_WIDTH_GROW_START: f32 = 0.16;
237const MENU_CARD_HEIGHT_GROW_START: f32 = 0.12;
238const MENU_OVERSHOOT_SCALE: f32 = 0.30;
239const MENU_GROW_STIFFNESS: f32 = 62.0;
240const MENU_REVEAL_STIFFNESS: f32 = 26.0;
241const MENU_WIDTH_EASE_POWER: f32 = 4.5;
242const MENU_HEIGHT_EASE_POWER: f32 = 18.0;
243const MENU_HEIGHT_OVERSHOOT: f32 = 0.15;
244const MENU_HEIGHT_OVERSHOOT_END: f32 = 0.52;
245const MENU_VERTICAL_REBOUND: f32 = 18.0;
246const MENU_VERTICAL_REBOUND_END: f32 = 0.70;
247const MENU_SOURCE_HEIGHT_RATIO: f32 = 0.86;
248const MENU_SOURCE_TARGET_Y_PROGRESS: f32 = 0.0;
249const ANCHOR_OVERLAP: f32 = 0.0;
250const ROW_PADDING_X: f32 = 20.0;
251const ROW_PADDING_Y: f32 = 9.25;
252const CHIP_INSET_X: f32 = 10.0;
253const MENU_CONTENT_INSET_Y: f32 = 9.5;
254const CHECK_COLUMN: f32 = 24.0;
255const ICON_SIZE: f32 = 24.0;
256const ICON_GAP: f32 = 12.0;
257const MENU_LONG_PRESS_MS: u64 = 500;
258const MENU_LONG_PRESS_SLOP: f32 = 12.0;
259const MENU_CONTENT_BLUR: f32 = 14.0;
260const MENU_CONTENT_BLUR_POWER: f32 = 0.65;
261const MENU_CONTENT_ALPHA_POWER: f32 = 0.45;
262const MENU_TRIGGER_GLASS_CUTOFF: f32 = 0.05;
263const MENU_TRIGGER_ABSORPTION_MS: u64 = 36;
264const MENU_TRIGGER_RESTORE_DELAY_MS: u64 = 205;
265const MENU_SOURCE_FOREGROUND_HIDE_MS: u64 = 200;
266const MENU_SOURCE_FOREGROUND_RESTORE_DELAY_MS: u64 = 205;
267#[derive(Clone, Copy, Debug, PartialEq)]
268struct MenuGestureSnapshot {
269 active: bool,
270 claimed: bool,
271 start: Point,
272 position: Point,
273 release: Option<(u64, Point)>,
274}
275
276impl Default for MenuGestureSnapshot {
277 fn default() -> Self {
278 Self {
279 active: false,
280 claimed: false,
281 start: Point::new(0.0, 0.0),
282 position: Point::new(0.0, 0.0),
283 release: None,
284 }
285 }
286}
287
288struct LiquidMenuGestureInner {
289 snapshot: MutableState<MenuGestureSnapshot>,
290 next_release: Cell<u64>,
291 item_rects: RefCell<Vec<Rc<Cell<Rect>>>>,
292}
293
294#[derive(Clone)]
298pub struct LiquidMenuGesture {
299 inner: Rc<LiquidMenuGestureInner>,
300}
301
302impl PartialEq for LiquidMenuGesture {
303 fn eq(&self, other: &Self) -> bool {
304 Rc::ptr_eq(&self.inner, &other.inner)
305 }
306}
307
308impl LiquidMenuGesture {
309 pub fn is_pressed(&self) -> bool {
312 self.inner.snapshot.get().active
313 }
314
315 pub fn press_point(&self) -> Option<Point> {
318 let snapshot = self.inner.snapshot.get();
319 snapshot.active.then_some(snapshot.position)
320 }
321
322 fn new() -> Self {
323 Self {
324 inner: Rc::new(LiquidMenuGestureInner {
325 snapshot: mutableStateOf(MenuGestureSnapshot::default()),
326 next_release: Cell::new(0),
327 item_rects: RefCell::new(Vec::new()),
328 }),
329 }
330 }
331
332 fn id(&self) -> usize {
333 Rc::as_ptr(&self.inner) as usize
334 }
335
336 fn begin(&self, point: Point) {
337 self.inner.snapshot.set(MenuGestureSnapshot {
338 active: true,
339 start: point,
340 position: point,
341 ..MenuGestureSnapshot::default()
342 });
343 }
344
345 fn move_to(&self, point: Point) {
346 let mut snapshot = self.inner.snapshot.get();
347 if snapshot.active {
348 snapshot.position = point;
349 self.inner.snapshot.set(snapshot);
350 }
351 }
352
353 fn claim(&self) {
354 let mut snapshot = self.inner.snapshot.get();
355 if snapshot.active && !snapshot.claimed {
356 snapshot.claimed = true;
357 self.inner.snapshot.set(snapshot);
358 }
359 }
360
361 fn release(&self, point: Point) {
362 let mut snapshot = self.inner.snapshot.get();
363 if !snapshot.active {
364 return;
365 }
366 snapshot.position = point;
367 snapshot.active = false;
368 if snapshot.claimed {
369 let sequence = self.inner.next_release.get().wrapping_add(1);
370 self.inner.next_release.set(sequence);
371 snapshot.release = Some((sequence, point));
372 }
373 self.inner.snapshot.set(snapshot);
374 }
375
376 fn cancel(&self) {
377 let mut snapshot = self.inner.snapshot.get();
378 snapshot.active = false;
379 snapshot.claimed = false;
380 snapshot.release = None;
381 self.inner.snapshot.set(snapshot);
382 }
383
384 fn snapshot(&self) -> MenuGestureSnapshot {
385 self.inner.snapshot.get()
386 }
387
388 fn item_rect(&self, index: usize) -> Rc<Cell<Rect>> {
389 let mut rects = self.inner.item_rects.borrow_mut();
390 while rects.len() <= index {
391 rects.push(Rc::new(Cell::new(Rect {
392 x: 0.0,
393 y: 0.0,
394 width: 0.0,
395 height: 0.0,
396 })));
397 }
398 Rc::clone(&rects[index])
399 }
400
401 fn item_at(&self, point: Point, items: &[LiquidMenuItem]) -> Option<usize> {
402 self.inner
403 .item_rects
404 .borrow()
405 .iter()
406 .enumerate()
407 .take(items.len())
408 .find_map(|(index, rect)| {
409 (!items[index].header && rect.get().contains(point.x, point.y)).then_some(index)
410 })
411 }
412}
413
414#[composable]
416#[track_caller]
417pub fn rememberLiquidMenuGesture() -> LiquidMenuGesture {
418 remember(LiquidMenuGesture::new).with(Clone::clone)
419}
420
421#[composable]
424#[allow(non_snake_case)]
425pub fn LiquidMenuAbsorbedIconButton(
426 modifier: Modifier,
427 spec: crate::widgets::GlassButtonSpec,
428 diameter: f32,
429 transferred: bool,
430 on_click: impl Fn() + 'static,
431 icon_path: &'static str,
432) {
433 let foreground = cranpose_animation::animate_float_as_state_with_initial(
434 1.0,
435 if transferred { 0.0 } else { 1.0 },
436 cranpose_animation::AnimationType::Tween(if transferred {
437 cranpose_animation::AnimationSpec::tween(
438 MENU_SOURCE_FOREGROUND_HIDE_MS,
439 cranpose_animation::Easing::LinearEasing,
440 )
441 } else {
442 cranpose_animation::AnimationSpec::tween(5, cranpose_animation::Easing::EaseOut)
443 .with_delay(MENU_SOURCE_FOREGROUND_RESTORE_DELAY_MS)
444 }),
445 "menu-source-foreground-ownership",
446 );
447 crate::widgets::button::GlassIconButtonWithForegroundAlpha(
448 modifier,
449 spec,
450 diameter,
451 foreground.get(),
452 on_click,
453 icon_path,
454 );
455}
456
457#[derive(Clone, Copy, Debug, PartialEq)]
458struct MenuGeometryPhase {
459 path: f32,
460 width: f32,
461 height: f32,
462}
463
464fn menu_geometry_phase(expanded: bool, appear: f32) -> MenuGeometryPhase {
465 if expanded && appear > 1.0 {
466 let settle = 1.0 + (appear - 1.0) * MENU_OVERSHOOT_SCALE;
467 return MenuGeometryPhase {
468 path: settle,
469 width: settle,
470 height: settle,
471 };
472 }
473
474 let appear = appear.clamp(0.0, 1.0);
475 if !expanded {
476 let normalized = ((appear - 0.015) / 0.985).clamp(0.0, 1.0);
477 return MenuGeometryPhase {
478 path: normalized,
479 width: 1.0 - (1.0 - normalized).powf(2.5),
480 height: 1.0 - (1.0 - normalized).powf(14.0),
481 };
482 }
483
484 if appear < MENU_GROW_DELAY {
485 let source_merge = smoothstep(0.10, 0.58, appear / MENU_GROW_DELAY);
486 return MenuGeometryPhase {
487 path: 0.0,
488 width: source_merge,
489 height: source_merge,
490 };
491 }
492
493 let path = ((appear - MENU_GROW_DELAY) / (1.0 - MENU_GROW_DELAY)).clamp(0.0, 1.0);
494 let width_growth =
495 ((path - MENU_CARD_WIDTH_GROW_START) / (1.0 - MENU_CARD_WIDTH_GROW_START)).clamp(0.0, 1.0);
496 let height_growth = ((path - MENU_CARD_HEIGHT_GROW_START)
497 / (1.0 - MENU_CARD_HEIGHT_GROW_START))
498 .clamp(0.0, 1.0);
499 let overshoot_phase = ((path - 0.50) / 0.50).clamp(0.0, 1.0);
500 let overshoot = 0.040 * (std::f32::consts::PI * overshoot_phase).sin().max(0.0);
501 let height_overshoot_phase = (height_growth / MENU_HEIGHT_OVERSHOOT_END).clamp(0.0, 1.0);
502 let height_overshoot = MENU_HEIGHT_OVERSHOOT
503 * (std::f32::consts::PI * height_overshoot_phase)
504 .sin()
505 .max(0.0);
506 MenuGeometryPhase {
507 path,
508 width: 1.0 - (1.0 - width_growth).powf(MENU_WIDTH_EASE_POWER) + overshoot,
509 height: 1.0 - (1.0 - height_growth).powf(MENU_HEIGHT_EASE_POWER) + height_overshoot,
510 }
511}
512
513#[derive(Clone, Copy, Debug, PartialEq)]
514struct MenuShape {
515 center_x: f32,
516 center_y: f32,
517 width: f32,
518 height: f32,
519 radius: f32,
520}
521
522impl MenuShape {
523 fn capsule(center_x: f32, center_y: f32, width: f32, height: f32) -> Self {
524 Self {
525 center_x,
526 center_y,
527 width,
528 height,
529 radius: -1.0,
530 }
531 }
532
533 fn from_window_rect(rect: Rect, node_origin: Point) -> Option<Self> {
534 (rect.width > 0.0 && rect.height > 0.0).then(|| {
535 Self::capsule(
536 rect.x + rect.width * 0.5 - node_origin.x,
537 rect.y + rect.height * 0.5 - node_origin.y,
538 rect.width,
539 rect.height,
540 )
541 })
542 }
543
544 fn as_glass_shape(self) -> (f32, f32, f32, f32, f32) {
545 (
546 self.center_x,
547 self.center_y,
548 self.width,
549 self.height,
550 self.radius,
551 )
552 }
553}
554
555#[derive(Clone, Copy, Debug, PartialEq)]
556struct MenuMorphGeometry {
557 primary: MenuShape,
558 source: MenuShape,
559 target: MenuShape,
560 path: f32,
561}
562
563fn menu_source_shape(anchor: MenuShape, absorbed: &[MenuShape], target: MenuShape) -> MenuShape {
564 let mut left = anchor.center_x - anchor.width * 0.5;
565 let mut right = anchor.center_x + anchor.width * 0.5;
566 let mut top = anchor.center_y - anchor.height * 0.5;
567 let mut bottom = anchor.center_y + anchor.height * 0.5;
568 for shape in absorbed {
569 left = left.min(shape.center_x - shape.width * 0.5);
570 right = right.max(shape.center_x + shape.width * 0.5);
571 top = top.min(shape.center_y - shape.height * 0.5);
572 bottom = bottom.max(shape.center_y + shape.height * 0.5);
573 }
574
575 let width = right - left;
576 let cluster_height = bottom - top;
577 let height = cluster_height
578 .max(width * MENU_SOURCE_HEIGHT_RATIO)
579 .min(target.height);
580 let cluster_center_y = (top + bottom) * 0.5;
581 MenuShape::capsule(
582 (left + right) * 0.5,
583 cluster_center_y + (target.center_y - cluster_center_y) * MENU_SOURCE_TARGET_Y_PROGRESS,
584 width,
585 height,
586 )
587}
588
589fn interpolate_menu_shape(
590 start: MenuShape,
591 target: MenuShape,
592 width_progress: f32,
593 height_progress: f32,
594) -> MenuShape {
595 let lerp = |a: f32, b: f32, progress: f32| a + (b - a) * progress;
596 MenuShape::capsule(
597 lerp(start.center_x, target.center_x, width_progress),
598 lerp(start.center_y, target.center_y, height_progress),
599 lerp(start.width, target.width, width_progress),
600 lerp(start.height, target.height, height_progress),
601 )
602}
603
604fn menu_vertical_rebound(path: f32) -> f32 {
605 if !(0.0..MENU_VERTICAL_REBOUND_END).contains(&path) {
606 return 0.0;
607 }
608
609 let normalized = path / MENU_VERTICAL_REBOUND_END;
610 let onset = smoothstep(0.0, 0.012, path);
611 MENU_VERTICAL_REBOUND
612 * onset
613 * (std::f32::consts::PI * normalized.powf(0.45))
614 .sin()
615 .max(0.0)
616}
617
618fn menu_morph_geometry(
619 expanded: bool,
620 appear: f32,
621 anchor: MenuShape,
622 absorbed: &[MenuShape],
623 target: MenuShape,
624) -> MenuMorphGeometry {
625 let phase = menu_geometry_phase(expanded, appear);
626 let source = menu_source_shape(anchor, absorbed, target);
627 let mut primary = if expanded && phase.path < MENU_SOURCE_SEPARATE_END {
628 anchor
629 } else {
630 let start = if expanded { source } else { anchor };
631 interpolate_menu_shape(start, target, phase.width, phase.height)
632 };
633 if expanded && phase.path >= MENU_SOURCE_SEPARATE_END {
634 let descent = smoothstep(0.10, 0.90, phase.path);
635 primary.center_y = source.center_y + (target.center_y - source.center_y) * descent;
636 primary.center_y += menu_vertical_rebound(phase.path);
637 }
638 let blob_radius = primary.height * 0.5;
639 let squareness = smoothstep(0.55, 0.88, phase.path);
640 primary.radius = if !expanded {
641 blob_radius
642 } else if phase.path >= 1.0 {
643 target.radius
644 } else {
645 blob_radius + (target.radius - blob_radius) * squareness
646 };
647 MenuMorphGeometry {
648 primary,
649 source,
650 target,
651 path: phase.path,
652 }
653}
654
655fn menu_ellipse_blend(path: f32) -> f32 {
656 0.5 * smoothstep(0.06, 0.22, path) * (1.0 - smoothstep(0.62, 0.88, path))
657}
658
659fn menu_content_progress(expanded: bool, appear: f32, reveal: f32) -> f32 {
660 if expanded {
661 smoothstep(0.17, 0.82, reveal)
662 } else {
663 smoothstep(0.20, 0.75, appear)
664 }
665}
666
667fn menu_content_blur(progress: f32) -> f32 {
668 MENU_CONTENT_BLUR * (1.0 - progress.clamp(0.0, 1.0)).powf(MENU_CONTENT_BLUR_POWER)
669}
670
671fn menu_content_alpha(progress: f32) -> f32 {
672 progress.clamp(0.0, 1.0).powf(MENU_CONTENT_ALPHA_POWER)
673}
674
675fn menu_content_scale(progress: f32) -> f32 {
676 0.80 + 0.20 * progress.clamp(0.0, 1.0)
677}
678
679#[derive(Clone, Copy, Debug, PartialEq)]
680struct MenuAbsorbedVisualPhase {
681 foreground_alpha: f32,
682 backdrop_alpha: f32,
683 foreground_blur: f32,
684 scale_x: f32,
685 scale_y: f32,
686}
687
688fn menu_absorbed_visual_phase(appear: f32, path: f32) -> MenuAbsorbedVisualPhase {
689 let appear = appear.clamp(0.0, 1.0);
690 let path = path.clamp(0.0, 1.0);
691 let shrink = smoothstep(0.0, 0.24, path);
692 let base_scale = 1.0 - 0.25 * shrink;
693 let stretch = smoothstep(0.30, 0.56, path);
694 let handoff = smoothstep(0.30, 0.55, appear);
695 let readable_alpha = 1.0 + (0.40 - 1.0) * handoff;
696 MenuAbsorbedVisualPhase {
697 foreground_alpha: readable_alpha * (1.0 - smoothstep(0.45, 0.85, path)),
698 backdrop_alpha: 0.62 * smoothstep(0.45, 0.85, path),
699 foreground_blur: 7.0 * smoothstep(0.45, 0.85, path),
700 scale_x: base_scale * (1.0 + 0.20 * stretch),
701 scale_y: base_scale * (1.0 + 0.28 * stretch),
702 }
703}
704
705#[derive(Clone, Copy, Debug, PartialEq)]
706struct MenuSurfacePhase {
707 anchor_presence: f32,
708 glue: f32,
709 wobble: f32,
710 bulge: f32,
711}
712
713fn menu_surface_phase(expanded: bool, appear: f32, path: f32) -> MenuSurfacePhase {
714 let appear = appear.clamp(0.0, 1.0);
715 let path = path.clamp(0.0, 1.0);
716 let activity = (std::f32::consts::PI * path).sin().max(0.0);
717 if expanded && path <= f32::EPSILON {
718 let recoil = (appear / MENU_GROW_DELAY).clamp(0.0, 1.0);
719 return MenuSurfacePhase {
720 anchor_presence: 0.0,
721 glue: 0.0,
722 wobble: 0.18 * (std::f32::consts::PI * recoil).sin().max(0.0),
723 bulge: 0.0,
724 };
725 }
726 if expanded {
727 return MenuSurfacePhase {
728 anchor_presence: 0.0,
729 glue: 0.0,
730 wobble: 0.08 * activity,
731 bulge: 0.35 * activity,
732 };
733 }
734 MenuSurfacePhase {
735 anchor_presence: 0.0,
736 glue: 0.0,
737 wobble: 0.04 * activity,
738 bulge: 0.25 * activity,
739 }
740}
741
742fn menu_absorbed_shape_presence(path: f32) -> f32 {
743 1.0 - smoothstep(MENU_SOURCE_SEPARATE_END, 0.30, path)
744}
745
746fn smoothstep(edge0: f32, edge1: f32, value: f32) -> f32 {
747 let t = ((value - edge0) / (edge1 - edge0)).clamp(0.0, 1.0);
748 t * t * (3.0 - 2.0 * t)
749}
750
751pub fn liquid_menu_trigger_input(
757 modifier: Modifier,
758 gesture: LiquidMenuGesture,
759 on_open: impl Fn() + 'static,
760) -> Modifier {
761 let gate = remember(|| {
762 let runtime = cranpose_core::with_current_composer(|composer| composer.runtime_handle());
763 Rc::new(RefCell::new(cranpose_animation::Animatable::new(
764 0.0, runtime,
765 )))
766 })
767 .with(Rc::clone);
768 let on_open: Rc<dyn Fn()> = Rc::new(on_open);
769
770 let snapshot = gesture.snapshot();
771 let gate_progress = gate.borrow().state().value();
772 if gate_progress >= 1.0 && snapshot.active && !snapshot.claimed {
773 gesture.claim();
774 let on_open = Rc::clone(&on_open);
775 SideEffect(move || on_open());
776 }
777
778 modifier.pointer_input(gesture.id(), {
779 let gesture = gesture.clone();
780 let gate = Rc::clone(&gate);
781 let on_open = Rc::clone(&on_open);
782 move |scope: PointerInputScope| {
783 let gesture = gesture.clone();
784 let gate = Rc::clone(&gate);
785 let on_open = Rc::clone(&on_open);
786 async move {
787 scope
788 .await_pointer_event_scope(|await_scope| async move {
789 let mut active_pointer = Option::<PointerId>::None;
790 let mut moved = false;
791 loop {
792 let event = await_scope.await_pointer_event().await;
793 match event.kind {
794 PointerEventKind::Down if active_pointer.is_none() => {
795 active_pointer = Some(event.id);
796 moved = false;
797 gesture.begin(event.global_position);
798 let mut timer = gate.borrow_mut();
799 timer.snapTo(0.0);
800 timer.animateTo(
801 1.0,
802 cranpose_animation::AnimationType::Tween(
803 cranpose_animation::AnimationSpec::linear(
804 MENU_LONG_PRESS_MS,
805 ),
806 ),
807 );
808 event.consume();
809 }
810 PointerEventKind::Move if active_pointer == Some(event.id) => {
811 gesture.move_to(event.global_position);
812 let state = gesture.snapshot();
813 let dx = event.global_position.x - state.start.x;
814 let dy = event.global_position.y - state.start.y;
815 if !state.claimed
816 && dx * dx + dy * dy
817 > MENU_LONG_PRESS_SLOP * MENU_LONG_PRESS_SLOP
818 {
819 moved = true;
820 gate.borrow_mut().snapTo(0.0);
821 }
822 event.consume();
823 }
824 PointerEventKind::Up if active_pointer == Some(event.id) => {
825 active_pointer = None;
826 let claimed = gesture.snapshot().claimed;
827 gate.borrow_mut().snapTo(0.0);
828 if claimed {
829 gesture.release(event.global_position);
830 } else {
831 gesture.cancel();
832 if !moved {
833 on_open();
834 }
835 }
836 event.consume();
837 }
838 PointerEventKind::Cancel if active_pointer == Some(event.id) => {
839 active_pointer = None;
840 gate.borrow_mut().snapTo(0.0);
841 gesture.cancel();
842 event.consume();
843 }
844 _ => {}
845 }
846 }
847 })
848 .await;
849 }
850 }
851 })
852}
853
854#[allow(clippy::too_many_arguments)]
858#[composable]
859#[allow(non_snake_case)]
860pub fn LiquidMenuIconButton(
861 modifier: Modifier,
862 spec: crate::widgets::GlassButtonSpec,
863 diameter: f32,
864 covered: bool,
865 gesture: LiquidMenuGesture,
866 on_open: impl Fn() + 'static,
867 icon_path: &'static str,
868) {
869 let interaction = rememberMutableInteractionSource();
870 let (pressed_modifier, _, content_alpha) =
871 crate::motion::liquid_press_scale(Modifier::empty(), interaction, 1.12);
872 let trigger_visual = cranpose_animation::animate_float_as_state_with_initial(
873 1.0,
874 if covered { 0.0 } else { 1.0 },
875 cranpose_animation::AnimationType::Tween(if covered {
876 cranpose_animation::AnimationSpec::tween(
877 MENU_TRIGGER_ABSORPTION_MS,
878 cranpose_animation::Easing::EaseOut,
879 )
880 } else {
881 cranpose_animation::AnimationSpec::tween(5, cranpose_animation::Easing::EaseOut)
882 .with_delay(MENU_TRIGGER_RESTORE_DELAY_MS)
883 }),
884 "menu-trigger-absorption",
885 );
886 let gate = remember(|| {
887 let runtime = cranpose_core::with_current_composer(|composer| composer.runtime_handle());
888 Rc::new(RefCell::new(cranpose_animation::Animatable::new(
889 0.0, runtime,
890 )))
891 })
892 .with(Rc::clone);
893 let on_open: Rc<dyn Fn()> = Rc::new(on_open);
894
895 let snapshot = gesture.snapshot();
896 let gate_progress = gate.borrow().state().value();
897 if gate_progress >= 1.0 && snapshot.active && !snapshot.claimed {
898 gesture.claim();
899 let on_open = Rc::clone(&on_open);
900 SideEffect(move || on_open());
901 }
902
903 let input = Modifier::empty()
904 .size(Size::new(diameter, diameter))
905 .pointer_input(gesture.id(), {
906 let gesture = gesture.clone();
907 let gate = Rc::clone(&gate);
908 let on_open = Rc::clone(&on_open);
909 move |scope: PointerInputScope| {
910 let gesture = gesture.clone();
911 let gate = Rc::clone(&gate);
912 let on_open = Rc::clone(&on_open);
913 async move {
914 scope
915 .await_pointer_event_scope(|await_scope| async move {
916 let mut active_pointer = Option::<PointerId>::None;
917 let mut moved = false;
918 let mut press: Option<PressInteractionPress> = None;
919 loop {
920 let event = await_scope.await_pointer_event().await;
921 match event.kind {
922 PointerEventKind::Down if active_pointer.is_none() => {
923 active_pointer = Some(event.id);
924 moved = false;
925 gesture.begin(event.global_position);
926 press = Some(interaction.press(event.position));
927 let mut timer = gate.borrow_mut();
928 timer.snapTo(0.0);
929 timer.animateTo(
930 1.0,
931 cranpose_animation::AnimationType::Tween(
932 cranpose_animation::AnimationSpec::linear(
933 MENU_LONG_PRESS_MS,
934 ),
935 ),
936 );
937 event.consume();
938 }
939 PointerEventKind::Move if active_pointer == Some(event.id) => {
940 gesture.move_to(event.global_position);
941 let state = gesture.snapshot();
942 let dx = event.global_position.x - state.start.x;
943 let dy = event.global_position.y - state.start.y;
944 if !state.claimed
945 && dx * dx + dy * dy
946 > MENU_LONG_PRESS_SLOP * MENU_LONG_PRESS_SLOP
947 {
948 moved = true;
949 gate.borrow_mut().snapTo(0.0);
950 }
951 event.consume();
952 }
953 PointerEventKind::Up if active_pointer == Some(event.id) => {
954 active_pointer = None;
955 let claimed = gesture.snapshot().claimed;
956 gate.borrow_mut().snapTo(0.0);
957 if claimed {
958 gesture.release(event.global_position);
959 } else {
960 gesture.cancel();
961 if !moved {
962 on_open();
963 }
964 }
965 if let Some(active_press) = press.take() {
966 interaction.release(active_press);
967 }
968 event.consume();
969 }
970 PointerEventKind::Cancel
971 if active_pointer == Some(event.id) =>
972 {
973 active_pointer = None;
974 gate.borrow_mut().snapTo(0.0);
975 gesture.cancel();
976 if let Some(active_press) = press.take() {
977 interaction.cancel(active_press);
978 }
979 event.consume();
980 }
981 _ => {}
982 }
983 }
984 })
985 .await;
986 }
987 }
988 });
989
990 Box(
991 pressed_modifier
992 .then(modifier)
993 .size(Size::new(diameter, diameter)),
994 BoxSpec::default().content_alignment(cranpose_ui_layout::Alignment::CENTER),
995 move || {
996 let visual_alpha = trigger_visual.get().clamp(0.0, 1.0);
997 let melt = 1.0 - visual_alpha;
998 let visual_spec = spec.clone();
999 let visual = Modifier::empty()
1000 .size(Size::new(diameter, diameter))
1001 .graphics_layer(move || GraphicsLayer {
1002 alpha: visual_alpha * content_alpha.get().clamp(0.0, 1.0),
1003 scale_x: 1.0 - 0.12 * melt,
1004 scale_y: 1.0 - 0.12 * melt,
1005 ..Default::default()
1006 });
1007 Box(
1008 visual,
1009 BoxSpec::default().content_alignment(cranpose_ui_layout::Alignment::CENTER),
1010 move || {
1011 if visual_alpha > MENU_TRIGGER_GLASS_CUTOFF {
1012 crate::widgets::GlassIconButton(
1013 Modifier::empty(),
1014 visual_spec.clone(),
1015 diameter,
1016 || {},
1017 icon_path,
1018 );
1019 }
1020 },
1021 );
1022 Box(input.clone(), BoxSpec::default(), || {});
1023 },
1024 );
1025}
1026
1027#[composable]
1028#[allow(non_snake_case)]
1029fn AbsorbedSourceVisual(
1030 source: LiquidMenuAbsorbedSource,
1031 node_origin: Point,
1032 alpha: f32,
1033 blur: f32,
1034 scale_x: f32,
1035 scale_y: f32,
1036) {
1037 if alpha <= 0.001 {
1038 return;
1039 }
1040
1041 let diameter = source.diameter;
1042 let foreground_spec = source.spec.clone();
1043 let layer = Modifier::empty()
1044 .absolute_offset(source.rect.x - node_origin.x, source.rect.y - node_origin.y)
1045 .size(Size::new(diameter, diameter))
1046 .graphics_layer(move || GraphicsLayer {
1047 alpha,
1048 scale_x,
1049 scale_y,
1050 render_effect: (blur > 0.35).then(|| RenderEffect::blur(blur)),
1051 ..Default::default()
1052 });
1053 Box(
1054 layer,
1055 BoxSpec::default().content_alignment(cranpose_ui_layout::Alignment::CENTER),
1056 move || {
1057 crate::widgets::button::GlassIconForeground(
1058 foreground_spec.clone(),
1059 diameter,
1060 source.icon_path,
1061 );
1062 },
1063 );
1064}
1065
1066#[composable]
1085#[allow(non_snake_case)]
1086pub fn LiquidMenu(
1087 expanded: bool,
1088 anchor: Rect,
1089 spec: LiquidMenuSpec,
1090 absorbed: Vec<LiquidMenuAbsorbedSource>,
1091 gesture: LiquidMenuGesture,
1092 on_dismiss: impl Fn() + 'static,
1093 content: impl FnOnce(&LiquidMenuScope),
1094) {
1095 let entries = Rc::new(collect_entries(content));
1096 let items: Vec<LiquidMenuItem> = entries.iter().map(|entry| entry.item.clone()).collect();
1097 let menu_width = spec.width;
1098 let visible = remember(|| mutableStateOf(false)).with(|s| *s);
1099 if expanded && !visible.get() {
1100 visible.set(true);
1101 }
1102 if !expanded && !visible.get() {
1103 return;
1104 }
1105 let colors = liquid_colors();
1106 let typography = liquid_typography();
1107 let on_item: Rc<dyn Fn(usize)> = Rc::new(move |index| {
1108 if let Some(action) = entries.get(index).and_then(|entry| entry.action.as_ref()) {
1109 action();
1110 }
1111 });
1112 let on_dismiss: Rc<dyn Fn()> = Rc::new(on_dismiss);
1113 let gesture_snapshot = gesture.snapshot();
1114 let gesture_hover = (gesture_snapshot.active && gesture_snapshot.claimed)
1115 .then(|| gesture.item_at(gesture_snapshot.position, &items))
1116 .flatten();
1117 let dwell_gate = remember(|| {
1118 let runtime = cranpose_core::with_current_composer(|composer| composer.runtime_handle());
1119 Rc::new(RefCell::new(cranpose_animation::Animatable::new(
1120 0.0f32, runtime,
1121 )))
1122 })
1123 .with(Rc::clone);
1124 let dwell_row = remember(|| Rc::new(Cell::new(Option::<usize>::None))).with(Rc::clone);
1125 let dwell_fired = remember(|| Rc::new(Cell::new(Option::<usize>::None))).with(Rc::clone);
1126 {
1127 let hover_accordion =
1128 gesture_hover.filter(|index| items.get(*index).is_some_and(|item| item.keeps_open));
1129 if hover_accordion != dwell_row.get() {
1130 dwell_row.set(hover_accordion);
1131 dwell_fired.set(None);
1132 let mut gate = dwell_gate.borrow_mut();
1133 gate.snapTo(0.0);
1134 if hover_accordion.is_some() {
1135 gate.animateTo(
1136 1.0,
1137 cranpose_animation::AnimationType::Tween(
1138 cranpose_animation::AnimationSpec::linear(450),
1139 ),
1140 );
1141 }
1142 }
1143 let gate_value = dwell_gate.borrow().state().get();
1144 if gate_value >= 1.0 {
1145 if let Some(index) = dwell_row.get() {
1146 if dwell_fired.get() != Some(index) {
1147 dwell_fired.set(Some(index));
1148 let on_item_dwell = Rc::clone(&on_item);
1149 SideEffect(move || on_item_dwell(index));
1150 }
1151 }
1152 }
1153 }
1154 let handled_release = remember(|| Rc::new(Cell::new(0u64))).with(Rc::clone);
1155 if let Some((sequence, point)) = gesture_snapshot.release {
1156 if handled_release.get() != sequence {
1157 handled_release.set(sequence);
1158 if let Some(index) = gesture.item_at(point, &items) {
1159 let keeps_open = items.get(index).is_some_and(|item| item.keeps_open);
1160 let on_item = Rc::clone(&on_item);
1161 let on_dismiss = Rc::clone(&on_dismiss);
1162 SideEffect(move || commit_menu_row(index, keeps_open, &on_item, &on_dismiss));
1163 }
1164 }
1165 }
1166
1167 let grow = cranpose_animation::animate_float_as_state_with_initial(
1168 0.0,
1169 if expanded { 1.0 } else { 0.0 },
1170 if expanded {
1171 cranpose_animation::spring(0.78, MENU_GROW_STIFFNESS)
1172 } else {
1173 cranpose_animation::AnimationType::Tween(cranpose_animation::AnimationSpec::linear(205))
1174 },
1175 "menu-grow",
1176 );
1177 let reveal_anim = cranpose_animation::animate_float_as_state_with_initial(
1178 0.0,
1179 if expanded { 1.0 } else { 0.0 },
1180 if expanded {
1181 cranpose_animation::spring(1.0, MENU_REVEAL_STIFFNESS)
1182 } else {
1183 cranpose_animation::spring(1.0, 900.0)
1184 },
1185 "menu-reveal",
1186 );
1187 let appear = grow.get().max(0.0);
1188 let reveal = reveal_anim.get().clamp(0.0, 1.0);
1189 if !expanded && appear < 0.02 {
1190 visible.set(false);
1191 return;
1192 }
1193
1194 let anchor_zone = anchor.height * ANCHOR_OVERLAP;
1195 let node_size =
1196 remember(|| Rc::new(Cell::new(cranpose_ui_graphics::Size::ZERO))).with(Rc::clone);
1197 let resize_anim = remember(|| {
1198 let runtime = cranpose_core::with_current_composer(|composer| composer.runtime_handle());
1199 Rc::new(RefCell::new(cranpose_animation::Animatable::new(
1200 1.0f32, runtime,
1201 )))
1202 })
1203 .with(Rc::clone);
1204 let resize_from_h = remember(|| Rc::new(Cell::new(0.0f32))).with(Rc::clone);
1205 let items_signature: String = items
1206 .iter()
1207 .map(|item| {
1208 format!(
1209 "{}|{}|{}{}{}{}{};",
1210 item.label,
1211 item.subtitle.as_deref().unwrap_or(""),
1212 item.checked as u8,
1213 item.destructive as u8,
1214 item.section_start as u8,
1215 item.header as u8,
1216 item.keeps_open as u8,
1217 )
1218 })
1219 .collect();
1220 let last_signature = remember(|| Rc::new(RefCell::new(String::new()))).with(Rc::clone);
1221 if *last_signature.borrow() != items_signature {
1222 let was_open = !last_signature.borrow().is_empty()
1223 && expanded
1224 && grow.get() > 0.5
1225 && node_size.get().height > 1.0;
1226 *last_signature.borrow_mut() = items_signature;
1227 if was_open {
1228 resize_from_h.set(node_size.get().height);
1229 let mut anim = resize_anim.borrow_mut();
1230 anim.snapTo(0.0);
1231 anim.animateTo(1.0, cranpose_animation::spring(0.78, 170.0));
1232 }
1233 }
1234 let resize_state = resize_anim.borrow().state();
1235 let scrim_dismiss = Rc::clone(&on_dismiss);
1236 PopupDismissableWhen(
1237 expanded,
1238 anchor,
1239 Point::new(
1240 anchor.width - menu_width - MENU_SHADOW_PAD,
1241 -MENU_SHADOW_PAD,
1242 ),
1243 move || scrim_dismiss(),
1244 {
1245 let absorbed = absorbed.clone();
1246 let items = items.clone();
1247 let typography = typography.clone();
1248 let on_item = Rc::clone(&on_item);
1249 let on_dismiss = Rc::clone(&on_dismiss);
1250 let node_size = Rc::clone(&node_size);
1251 let gesture = gesture.clone();
1252 move || {
1253 let anchor_center = (
1254 menu_width - anchor.width * 0.5 + MENU_SHADOW_PAD,
1255 anchor.height * 0.5 + MENU_SHADOW_PAD,
1256 );
1257 let anchor_shape = MenuShape::capsule(
1258 anchor_center.0,
1259 anchor_center.1,
1260 anchor.width,
1261 anchor.height,
1262 );
1263 let node_origin = Point::new(
1264 anchor.x + anchor.width - menu_width - MENU_SHADOW_PAD,
1265 anchor.y - MENU_SHADOW_PAD,
1266 );
1267 let absorbed_shapes: Vec<MenuShape> = absorbed
1268 .iter()
1269 .filter_map(|source| MenuShape::from_window_rect(source.rect, node_origin))
1270 .collect();
1271 let morph_size = Rc::clone(&node_size);
1272 let glass = Glass::regular()
1273 .shape(LiquidShape::RoundedRect(MENU_RADIUS))
1274 .adaptive_frost(colors.label, 0.18)
1275 .blur_radius(30.0)
1276 .saturation(if colors.is_dark { 1.90 } else { 1.55 })
1277 .lift(if colors.is_dark { 0.10 } else { 0.58 })
1278 .highlight(0.14);
1279 let glass = if colors.is_dark {
1280 glass
1281 .contrast(0.37)
1282 .tint(Color::from_rgba_u8(34, 10, 34, 146))
1283 } else {
1284 glass
1285 };
1286 let glass = glass
1287 .shadow_style(GlassShadow::new(
1288 Color::BLACK.with_alpha(if colors.is_dark { 0.60 } else { 0.11 }),
1289 if colors.is_dark { 32.0 } else { 26.0 },
1290 if colors.is_dark { 10.0 } else { 8.0 },
1291 0.0,
1292 ))
1293 .no_clip();
1294 let resize_from = Rc::clone(&resize_from_h);
1295 let glow_point: Rc<Cell<Option<(f32, f32)>>> =
1296 remember(|| Rc::new(Cell::new(None))).with(Rc::clone);
1297 let glow_for_glass = Rc::clone(&glow_point);
1298 let glass_node_origin = node_origin;
1299 let birth_milk = Some(if colors.is_dark {
1300 Color::from_rgba_u8(208, 204, 214, 240)
1301 } else {
1302 Color::from_rgba_u8(246, 247, 250, 210)
1303 });
1304 let card = Modifier::empty()
1305 .report_size(Rc::clone(&node_size))
1306 .glass_effect_with(glass, move || {
1307 let glow_touch = glow_for_glass.get().map(|(x, y)| {
1308 (x - glass_node_origin.x, y - glass_node_origin.y, 1.0f32)
1309 });
1310 let size = morph_size.get();
1311 let measured_h =
1312 (size.height - anchor_zone - MENU_SHADOW_PAD * 2.0).max(24.0);
1313 let resize_t = resize_state.get();
1314 let from_h =
1315 (resize_from.get() - anchor_zone - MENU_SHADOW_PAD * 2.0).max(24.0);
1316 let menu_h = if resize_from.get() > 1.0 {
1317 from_h + (measured_h - from_h) * resize_t.max(0.0)
1318 } else {
1319 measured_h
1320 };
1321 let settle_radius = (menu_h * 0.32).clamp(26.0, MENU_RADIUS);
1322 let target = MenuShape {
1323 center_x: menu_width * 0.5 + MENU_SHADOW_PAD,
1324 center_y: anchor_zone + MENU_SHADOW_PAD + menu_h * 0.5,
1325 width: menu_width,
1326 height: menu_h,
1327 radius: settle_radius,
1328 };
1329 let geometry = menu_morph_geometry(
1330 expanded,
1331 appear,
1332 anchor_shape,
1333 &absorbed_shapes,
1334 target,
1335 );
1336 let t = geometry.path;
1337 let primary = geometry.primary.as_glass_shape();
1338 let start = if expanded {
1339 geometry.source
1340 } else {
1341 anchor_shape
1342 };
1343 let target = geometry.target;
1344 let surface = menu_surface_phase(expanded, appear, t);
1345 let dir_x = target.center_x - start.center_x;
1346 let dir_y = target.center_y - start.center_y;
1347 let mut bulge_dir = dir_y.atan2(dir_x);
1348 if !expanded {
1349 bulge_dir += std::f32::consts::PI;
1350 }
1351 let mut shapes = Vec::new();
1352 if surface.anchor_presence > 0.01 {
1353 shapes.push((
1354 anchor_shape.center_x,
1355 anchor_shape.center_y,
1356 anchor_shape.width * surface.anchor_presence,
1357 anchor_shape.height * surface.anchor_presence,
1358 -1.0,
1359 ));
1360 }
1361 let absorbed_presence = menu_absorbed_shape_presence(t);
1362 if expanded && absorbed_presence > 0.01 {
1363 shapes.extend(absorbed_shapes.iter().map(|shape| {
1364 (
1365 shape.center_x,
1366 shape.center_y,
1367 shape.width * absorbed_presence,
1368 shape.height * absorbed_presence,
1369 -1.0,
1370 )
1371 }));
1372 }
1373 let glue = surface.glue;
1374 let activity = if expanded {
1375 smoothstep(0.0, 0.42, t)
1376 } else {
1377 smoothstep(0.0, 0.12, t)
1378 };
1379 GlassDynamics {
1380 activity: Some(activity),
1381 resting_tint: birth_milk,
1382 touch: glow_touch,
1383 morph: Some(GlassMorph {
1384 node_size: (size.width.max(1.0), size.height.max(1.0)),
1385 primary,
1386 shapes,
1387 glue,
1388 wobble_amplitude: surface.wobble,
1389 wobble_phase: t * 8.0,
1390 bulge_amplitude: surface.bulge,
1391 bulge_direction: bulge_dir,
1392 ellipse_blend: menu_ellipse_blend(t),
1393 deformation: None,
1394 zoom_anchor: (0.0, 0.0),
1395 }),
1396 ..Default::default()
1397 }
1398 })
1399 .width(menu_width + MENU_SHADOW_PAD * 2.0);
1400
1401 let has_checks = items.iter().any(|item| item.checked);
1402 let hovered = remember(|| mutableStateOf(Option::<usize>::None)).with(|s| *s);
1403 let glow_row = gesture_hover.or(hovered.get());
1404 glow_point.set(glow_row.map(|index| {
1405 let rect = gesture.item_rect(index).get();
1406 (rect.x + rect.width * 0.5, rect.y + rect.height * 0.5)
1407 }));
1408 let gesture = gesture.clone();
1409 let source_phase =
1410 menu_absorbed_visual_phase(appear, menu_geometry_phase(expanded, appear).path);
1411 for source in absorbed.iter().cloned() {
1412 AbsorbedSourceVisual(
1413 source,
1414 node_origin,
1415 source_phase.backdrop_alpha,
1416 0.0,
1417 source_phase.scale_x,
1418 source_phase.scale_y,
1419 );
1420 }
1421 Box(card, BoxSpec::default(), {
1422 let items = items.clone();
1423 let typography = typography.clone();
1424 let on_item = Rc::clone(&on_item);
1425 let on_dismiss = Rc::clone(&on_dismiss);
1426 move || {
1427 Column(
1428 Modifier::empty().fill_max_width().padding(MENU_SHADOW_PAD),
1429 ColumnSpec::default(),
1430 {
1431 let items = items.clone();
1432 let typography = typography.clone();
1433 let on_item = Rc::clone(&on_item);
1434 let on_dismiss = Rc::clone(&on_dismiss);
1435 let gesture = gesture.clone();
1436 move || {
1437 Box(
1438 Modifier::empty().height(anchor_zone),
1439 BoxSpec::default(),
1440 || {},
1441 );
1442 let content = menu_content_progress(expanded, appear, reveal);
1443 let resize_t = resize_state.get().clamp(0.0, 1.0);
1444 let content =
1445 content * (0.45 + 0.55 * smoothstep(0.35, 1.0, resize_t));
1446 let content_scale = menu_content_scale(content);
1447 let content_blur = menu_content_blur(content);
1448 let content_translation_y = if expanded {
1449 menu_vertical_rebound(
1450 menu_geometry_phase(expanded, appear).path,
1451 )
1452 } else {
1453 0.0
1454 };
1455 let rows_wrap = Modifier::empty()
1456 .fill_max_width()
1457 .graphics_layer(move || GraphicsLayer {
1458 alpha: menu_content_alpha(content),
1459 scale_x: content_scale,
1460 scale_y: content_scale,
1461 transform_origin:
1462 cranpose_ui_graphics::TransformOrigin {
1463 pivot_fraction_x: 1.0,
1464 pivot_fraction_y: 0.0,
1465 },
1466 translation_y: content_translation_y,
1467 render_effect: (content_blur > 0.35)
1468 .then(|| RenderEffect::blur(content_blur)),
1469 ..Default::default()
1470 });
1471 Box(rows_wrap, BoxSpec::default(), {
1472 let items = items.clone();
1473 let typography = typography.clone();
1474 let on_item = Rc::clone(&on_item);
1475 let on_dismiss = Rc::clone(&on_dismiss);
1476 let gesture = gesture.clone();
1477 move || {
1478 Column(
1479 Modifier::empty().fill_max_width().padding_each(
1480 0.0,
1481 MENU_CONTENT_INSET_Y,
1482 0.0,
1483 MENU_CONTENT_INSET_Y,
1484 ),
1485 ColumnSpec::default(),
1486 {
1487 let items = items.clone();
1488 let typography = typography.clone();
1489 let on_item = Rc::clone(&on_item);
1490 let on_dismiss = Rc::clone(&on_dismiss);
1491 let gesture = gesture.clone();
1492 move || {
1493 for (index, item) in
1494 items.iter().enumerate()
1495 {
1496 if item.section_start && index > 0 {
1497 let separator =
1498 colors.separator.with_alpha(
1499 colors.separator.a() * 0.22,
1500 );
1501 Box(
1502 Modifier::empty()
1503 .fill_max_width()
1504 .padding_symmetric(ROW_PADDING_X, 0.0)
1505 .height(1.0)
1506 .draw_behind(move |scope| {
1507 scope.draw_rect(
1508 cranpose_ui_graphics::Brush::solid(
1509 separator,
1510 ),
1511 );
1512 }),
1513 BoxSpec::default(),
1514 || {},
1515 );
1516 }
1517
1518 if item.header {
1519 menu_header_row(
1520 item,
1521 &typography,
1522 has_checks,
1523 colors,
1524 );
1525 continue;
1526 }
1527 let expanded_header = item.keeps_open
1528 && items
1529 .get(index + 1)
1530 .is_some_and(|next| {
1531 !next.keeps_open
1532 && !next.header
1533 });
1534 menu_item_row(
1535 index,
1536 item,
1537 &typography,
1538 has_checks,
1539 colors,
1540 hovered,
1541 gesture_hover,
1542 expanded_header,
1543 gesture.item_rect(index),
1544 Rc::clone(&on_item),
1545 Rc::clone(&on_dismiss),
1546 );
1547 }
1548 }
1549 },
1550 );
1551 }
1552 });
1553 }
1554 },
1555 );
1556 }
1557 });
1558 for source in absorbed.iter().cloned() {
1559 AbsorbedSourceVisual(
1560 source,
1561 node_origin,
1562 source_phase.foreground_alpha,
1563 source_phase.foreground_blur,
1564 source_phase.scale_x,
1565 source_phase.scale_y,
1566 );
1567 }
1568 }
1569 },
1570 );
1571}
1572
1573#[composable]
1576#[allow(non_snake_case)]
1577pub fn LiquidDropdownMenu<A>(
1578 modifier: Modifier,
1579 expanded: bool,
1580 spec: LiquidDropdownMenuSpec,
1581 on_dismiss: impl Fn() + 'static,
1582 mut anchor_content: A,
1583 content: impl Fn(&LiquidMenuScope) + 'static,
1584) where
1585 A: FnMut() + 'static,
1586{
1587 let anchor = rememberMutableStateOf(|| Rect {
1588 x: 0.0,
1589 y: 0.0,
1590 width: 0.0,
1591 height: 0.0,
1592 });
1593 let gesture = rememberLiquidMenuGesture();
1594 let on_dismiss = Rc::new(on_dismiss);
1595 let content = Rc::new(content);
1596 Box(
1597 modifier.report_window_rect_state(anchor),
1598 BoxSpec::default(),
1599 move || {
1600 anchor_content();
1601 let content = Rc::clone(&content);
1602 let dismiss = Rc::clone(&on_dismiss);
1603 LiquidMenu(
1604 expanded,
1605 anchor.get(),
1606 spec.menu,
1607 spec.absorbed.clone(),
1608 gesture.clone(),
1609 move || dismiss(),
1610 move |scope| content(scope),
1611 );
1612 },
1613 );
1614}
1615
1616fn commit_menu_row(
1617 index: usize,
1618 keeps_open: bool,
1619 on_item: &Rc<dyn Fn(usize)>,
1620 on_dismiss: &Rc<dyn Fn()>,
1621) {
1622 on_item(index);
1623 if !keeps_open {
1624 on_dismiss();
1625 }
1626}
1627
1628fn menu_header_row(
1629 item: &LiquidMenuItem,
1630 typography: &crate::theme::LiquidTypography,
1631 has_checks: bool,
1632 colors: crate::theme::LiquidColors,
1633) {
1634 let label = item.label.clone();
1635 let style = TextStyle {
1636 span_style: SpanStyle {
1637 color: Some(colors.secondary_label),
1638 font_size: TextUnit::Sp(13.0),
1639 ..typography.footnote.span_style.clone()
1640 },
1641 ..typography.footnote.clone()
1642 };
1643 let indent = ROW_PADDING_X + if has_checks { CHECK_COLUMN } else { 0.0 };
1644 let row = Modifier::empty()
1645 .fill_max_width()
1646 .padding_each(indent, 12.0, ROW_PADDING_X, 2.0);
1647 Row(row, RowSpec::default(), move || {
1648 Text(label.clone(), Modifier::empty(), style.clone());
1649 });
1650}
1651
1652#[allow(non_snake_case)]
1653#[allow(clippy::too_many_arguments)]
1654fn menu_item_row(
1655 index: usize,
1656 item: &LiquidMenuItem,
1657 typography: &crate::theme::LiquidTypography,
1658 has_checks: bool,
1659 colors: crate::theme::LiquidColors,
1660 hovered: cranpose_core::MutableState<Option<usize>>,
1661 gesture_hover: Option<usize>,
1662 expanded_header: bool,
1663 rect_sink: Rc<Cell<Rect>>,
1664 on_item: Rc<dyn Fn(usize)>,
1665 on_dismiss: Rc<dyn Fn()>,
1666) {
1667 let color = if item.destructive {
1668 colors.destructive
1669 } else {
1670 colors.label
1671 };
1672 let is_hovered = hovered.get() == Some(index) || gesture_hover == Some(index);
1673 let highlight = if colors.is_dark {
1674 cranpose_ui_graphics::Color::from_rgba_u8(120, 120, 128, 44)
1675 } else {
1676 cranpose_ui_graphics::Color::from_rgba_u8(120, 120, 128, 30)
1677 };
1678 let row_label = item.label.clone();
1679 let keeps_open = item.keeps_open;
1680 let row = Modifier::empty()
1681 .fill_max_width()
1682 .report_window_rect(rect_sink)
1683 .semantics(move |config| {
1684 config.role = Some(SemanticsWidgetRole::Button);
1685 config.is_clickable = true;
1686 config.content_description = Some(row_label.clone());
1687 })
1688 .pointer_input(index, {
1689 let on_item = Rc::clone(&on_item);
1690 let on_dismiss = Rc::clone(&on_dismiss);
1691 move |scope: PointerInputScope| {
1692 let on_item = Rc::clone(&on_item);
1693 let on_dismiss = Rc::clone(&on_dismiss);
1694 async move {
1695 scope
1696 .await_pointer_event_scope(|await_scope| async move {
1697 loop {
1698 let event = await_scope.await_pointer_event().await;
1699 match event.kind {
1700 PointerEventKind::Enter | PointerEventKind::Move => {
1701 hovered.set(Some(index));
1702 }
1703 PointerEventKind::Exit if hovered.get() == Some(index) => {
1704 hovered.set(None);
1705 }
1706 PointerEventKind::Down => {
1707 hovered.set(Some(index));
1708 event.consume();
1709 }
1710 PointerEventKind::Up => {
1711 hovered.set(None);
1712 commit_menu_row(index, keeps_open, &on_item, &on_dismiss);
1713 event.consume();
1714 }
1715 _ => {}
1716 }
1717 }
1718 })
1719 .await;
1720 }
1721 }
1722 })
1723 .draw_behind(move |scope| {
1724 if expanded_header {
1725 let chip = if colors.is_dark {
1726 Color::from_rgb_u8(255, 224, 248).with_alpha(0.52)
1727 } else {
1728 Color::BLACK.with_alpha(0.08)
1729 };
1730 let size = scope.size();
1731 scope.draw_round_rect_at(
1732 Rect {
1733 x: CHIP_INSET_X,
1734 y: 0.0,
1735 width: (size.width - CHIP_INSET_X * 2.0).max(0.0),
1736 height: size.height,
1737 },
1738 Brush::solid(chip),
1739 CornerRadii::uniform(16.0),
1740 );
1741 }
1742 if is_hovered {
1743 scope.draw_round_rect(Brush::solid(highlight), CornerRadii::uniform(14.0));
1744 }
1745 })
1746 .padding_symmetric(ROW_PADDING_X, ROW_PADDING_Y);
1747
1748 let label = item.label.clone();
1749 let subtitle = item.subtitle.clone();
1750 let icon = item.icon;
1751 let checked = item.checked;
1752 let accordion_chevron = item.keeps_open && subtitle.is_some();
1753 let secondary = colors.secondary_label;
1754 let typography = typography.clone();
1755 Row(
1756 row,
1757 RowSpec::default().vertical_alignment(VerticalAlignment::CenterVertically),
1758 move || {
1759 let label = label.clone();
1760 let subtitle = subtitle.clone();
1761 if has_checks {
1762 Box(
1763 Modifier::empty().width(CHECK_COLUMN),
1764 BoxSpec::default(),
1765 move || {
1766 if checked {
1767 crate::icons::Icon(crate::icons::CHECK, 16.0, color);
1768 }
1769 },
1770 );
1771 }
1772 if let Some(icon) = icon {
1773 crate::icons::Icon(icon, ICON_SIZE, color);
1774 Box(Modifier::empty().width(ICON_GAP), BoxSpec::default(), || {});
1775 }
1776 let style = TextStyle {
1777 span_style: SpanStyle {
1778 color: Some(color),
1779 font_weight: Some(FontWeight::NORMAL),
1780 ..typography.body.span_style.clone()
1781 },
1782 ..typography.body.clone()
1783 };
1784 if let Some(subtitle) = subtitle {
1785 let subtitle_style = TextStyle {
1786 span_style: SpanStyle {
1787 color: Some(secondary),
1788 font_size: TextUnit::Sp(13.0),
1789 ..typography.footnote.span_style.clone()
1790 },
1791 ..typography.footnote.clone()
1792 };
1793 Column(
1794 Modifier::empty().weight(1.0),
1795 ColumnSpec::default(),
1796 move || {
1797 Text(label.clone(), Modifier::empty(), style.clone());
1798 Text(subtitle.clone(), Modifier::empty(), subtitle_style.clone());
1799 },
1800 );
1801 } else {
1802 Text(label, Modifier::empty().weight(1.0), style);
1803 }
1804 if accordion_chevron {
1805 crate::icons::Icon(crate::icons::CHEVRON_DOWN, 18.0, secondary);
1806 }
1807 },
1808 );
1809}
1810
1811#[cfg(test)]
1812mod tests {
1813 use super::*;
1814
1815 #[test]
1816 fn a_scope_keeps_actions_with_their_items() {
1817 let selected = Rc::new(Cell::new(false));
1818 let selected_by_action = Rc::clone(&selected);
1819 let entries = collect_entries(|scope| {
1820 scope.header("Section");
1821 scope.separator();
1822 scope.item(LiquidMenuItem::new("Open"), move || {
1823 selected_by_action.set(true)
1824 });
1825 });
1826
1827 assert_eq!(entries.len(), 2);
1828 assert!(entries[0].item.header);
1829 assert!(entries[1].item.section_start);
1830 entries[1].action.as_ref().unwrap()();
1831 assert!(selected.get());
1832 }
1833
1834 #[test]
1835 fn dropdown_spec_builders_preserve_menu_configuration() {
1836 let menu = LiquidMenuSpec { width: 180.0 };
1837 let absorbed = LiquidMenuAbsorbedSource::new(
1838 Rect::from_origin_size(Point::ZERO, Size::new(44.0, 44.0)),
1839 crate::widgets::GlassButtonSpec::default(),
1840 44.0,
1841 crate::icons::SEARCH,
1842 );
1843 let spec = LiquidDropdownMenuSpec::default()
1844 .menu(menu)
1845 .absorbed(vec![absorbed]);
1846 assert_eq!(spec.menu, menu);
1847 assert_eq!(spec.absorbed.len(), 1);
1848 }
1849
1850 #[test]
1851 fn menu_rows_use_the_reference_leading_grid_and_vertical_rhythm() {
1852 assert_eq!(ROW_PADDING_X, 20.0);
1853 assert_eq!(CHECK_COLUMN, 24.0);
1854 assert_eq!(ICON_SIZE, 24.0);
1855 assert_eq!(ICON_GAP, 12.0);
1856
1857 let check_center = ROW_PADDING_X + 8.0;
1858 let icon_center = ROW_PADDING_X + CHECK_COLUMN + ICON_SIZE * 0.5;
1859 let label_start = ROW_PADDING_X + CHECK_COLUMN + ICON_SIZE + ICON_GAP;
1860 assert_eq!((check_center, icon_center, label_start), (28.0, 56.0, 80.0));
1861
1862 let row_height = ICON_SIZE + ROW_PADDING_Y * 2.0;
1863 assert!((42.0..=43.0).contains(&row_height));
1864 assert_eq!(MENU_CONTENT_INSET_Y, 9.5);
1865 let two_row_panel_height = row_height * 2.0 + MENU_CONTENT_INSET_Y * 2.0;
1866 assert!((103.5..=104.5).contains(&two_row_panel_height));
1867 }
1868
1869 #[test]
1870 fn menu_geometry_keeps_the_source_cluster_horizontal_before_card_growth() {
1871 let anchor = MenuShape::capsule(228.0, 22.0, 44.0, 44.0);
1872 let absorbed = [MenuShape::capsule(176.0, 22.0, 44.0, 44.0)];
1873 let target = MenuShape {
1874 center_x: 125.0,
1875 center_y: 52.0,
1876 width: 250.0,
1877 height: 104.0,
1878 radius: 32.0,
1879 };
1880 let pose = |appear| menu_morph_geometry(true, appear, anchor, &absorbed, target).primary;
1881
1882 let initial = pose(0.0);
1883 assert_eq!((initial.width, initial.height), (44.0, 44.0));
1884
1885 let merged = pose(0.028_576);
1886 assert_eq!(merged, initial);
1887 let source = menu_source_shape(anchor, &absorbed, target);
1888 assert_eq!(source.width, 96.0);
1889 assert!((82.5..=82.6).contains(&source.height));
1890 assert_eq!(source.center_y, anchor.center_y);
1891 assert_eq!(menu_absorbed_shape_presence(0.0), 1.0);
1892 assert_eq!(menu_absorbed_shape_presence(0.30), 0.0);
1893
1894 let early = pose(0.070_208);
1895 let middle = pose(0.199_019);
1896 let broad = pose(0.539_174);
1897 assert_eq!(early, initial);
1898 assert_eq!(middle.width, source.width);
1899 assert!(middle.height >= source.height);
1900 assert!(broad.width > middle.width && broad.height <= target.height * 1.1);
1901 assert!(middle.width > middle.height);
1902 assert!(broad.width > broad.height * 2.0);
1903
1904 let swell = pose(0.701_903);
1905 assert!(
1906 (252.0..=259.0).contains(&swell.width) && (102.0..=106.0).contains(&swell.height),
1907 "the broad body must overshoot horizontally without inflating vertically: {swell:?}"
1908 );
1909 assert!(menu_ellipse_blend(0.25) > 0.3);
1910 assert_eq!(menu_ellipse_blend(0.0), 0.0);
1911 assert_eq!(menu_ellipse_blend(1.0), 0.0);
1912
1913 let overshoot = pose(1.08);
1914 assert!((250.0..=254.0).contains(&overshoot.width));
1915 assert!((104.0..=106.0).contains(&overshoot.height));
1916 assert_eq!(MENU_RADIUS, 32.0);
1917 assert!((0.045..=0.055).contains(&MENU_GROW_DELAY));
1918 assert!((55.0..=70.0).contains(&MENU_GROW_STIFFNESS));
1919 }
1920
1921 #[test]
1922 fn menu_open_spring_departs_early_then_settles_without_a_dead_interval() {
1923 let (source_phase, _) =
1924 cranpose_animation::advance_spring(0.0, 0.0, 1.0, 0.78, MENU_GROW_STIFFNESS, 0.054);
1925 assert!(
1926 source_phase > MENU_GROW_DELAY,
1927 "the departing oval must be visible by the target's early frame: {source_phase}"
1928 );
1929 let (broad_phase, _) =
1930 cranpose_animation::advance_spring(0.0, 0.0, 1.0, 0.78, MENU_GROW_STIFFNESS, 0.180);
1931 assert!(
1932 (0.35..=0.60).contains(&broad_phase),
1933 "the broad menu body must be established by 180ms: {broad_phase}"
1934 );
1935 let (settled_phase, _) =
1936 cranpose_animation::advance_spring(0.0, 0.0, 1.0, 0.78, MENU_GROW_STIFFNESS, 0.600);
1937 assert!(settled_phase > 0.95);
1938 }
1939
1940 #[test]
1941 fn menu_body_uses_the_shared_vertical_rebound_path() {
1942 let anchor = MenuShape::capsule(228.0, 22.0, 44.0, 44.0);
1943 let absorbed = [MenuShape::capsule(176.0, 22.0, 44.0, 44.0)];
1944 let target = MenuShape {
1945 center_x: 125.0,
1946 center_y: 52.0,
1947 width: 250.0,
1948 height: 104.0,
1949 radius: 32.0,
1950 };
1951
1952 let source = menu_source_shape(anchor, &absorbed, target);
1953 for appear in [0.199_019, 0.296_780, 0.412_956, 0.539_174] {
1954 let geometry = menu_morph_geometry(true, appear, anchor, &absorbed, target);
1955 let phase = menu_geometry_phase(true, appear);
1956 let descent = smoothstep(0.10, 0.90, phase.path);
1957 let interpolated_y = source.center_y + (target.center_y - source.center_y) * descent;
1958 let expected_y = interpolated_y + menu_vertical_rebound(phase.path);
1959 assert!(
1960 (geometry.primary.center_y - expected_y).abs() < 0.001,
1961 "body and content must resolve the same rebound path: {geometry:?}"
1962 );
1963 }
1964 assert_eq!(menu_vertical_rebound(0.0), 0.0);
1965 assert!(menu_vertical_rebound(0.25) > 0.0);
1966 assert_eq!(menu_vertical_rebound(MENU_VERTICAL_REBOUND_END), 0.0);
1967 }
1968
1969 #[test]
1970 fn menu_close_reverses_through_a_smooth_oval() {
1971 let phase = menu_geometry_phase(false, 0.6);
1972 assert!(
1973 phase.width > 0.80,
1974 "the close must retain its broad body at mid-flight: {phase:?}"
1975 );
1976 assert!(
1977 44.0 + (250.0 - 44.0) * phase.width > 1.8 * (44.0 + (104.0 - 44.0) * phase.height),
1978 "the close must pass back through the wide oval in physical dimensions: {phase:?}"
1979 );
1980 assert!(
1981 menu_content_progress(false, 0.6, 1.0) > 0.75,
1982 "content must remain coherent through the initial deflation"
1983 );
1984 assert_eq!(menu_content_progress(false, 0.2, 1.0), 0.0);
1985 let rounded_volume = menu_geometry_phase(false, 0.21);
1986 assert!(
1987 rounded_volume.width > 0.35,
1988 "the terminal body must contract continuously into the anchor: {rounded_volume:?}"
1989 );
1990 assert!(
1991 44.0 + (250.0 - 44.0) * rounded_volume.width
1992 > 44.0 + (104.0 - 44.0) * rounded_volume.height,
1993 "the terminal body must stay smooth rather than forming a vertical leaf in physical dimensions: {rounded_volume:?}"
1994 );
1995 }
1996
1997 #[test]
1998 fn menu_content_materializes_early_and_is_sharp_by_settle() {
1999 let birth = menu_content_progress(true, 0.35, 0.25);
2000 assert!(
2001 birth > 0.02 && birth < 0.08,
2002 "rows must begin as a faint smudge after the blank birth phase: {birth}"
2003 );
2004 let mid = menu_content_progress(true, 0.55, 0.55);
2005 assert!(
2006 (0.55..0.70).contains(&mid),
2007 "rows must remain visibly soft at mid-flight: {mid}"
2008 );
2009 let settle = menu_content_progress(true, 1.0, 0.92);
2010 assert!(
2011 settle > 0.99,
2012 "rows must be effectively sharp when the shape settles: {settle}"
2013 );
2014 assert!(menu_content_blur(birth) > 13.0);
2015 assert!((7.0..8.0).contains(&menu_content_blur(mid)));
2016 assert!(menu_content_blur(settle) < 0.5);
2017 assert!((20.0..=32.0).contains(&MENU_REVEAL_STIFFNESS));
2018 assert!((0.34..=0.37).contains(&menu_content_alpha(0.10)));
2019 assert!((0.79..=0.82).contains(&menu_content_alpha(0.62)));
2020 assert_eq!(menu_content_alpha(1.0), 1.0);
2021 assert!((0.85..=0.87).contains(&menu_content_scale(0.30)));
2022 assert!((0.92..=0.93).contains(&menu_content_scale(0.62)));
2023 assert_eq!(menu_content_scale(1.0), 1.0);
2024 }
2025
2026 #[test]
2027 fn menu_surface_motion_is_smooth_and_capture_cadence_independent() {
2028 let merged = menu_surface_phase(true, 0.14, 0.0);
2029 assert_eq!(merged.anchor_presence, 0.0);
2030 assert_eq!(merged.glue, 0.0);
2031 let recoil = menu_surface_phase(true, 0.275, 0.0);
2032 assert_eq!(recoil.glue, 0.0);
2033
2034 let early = menu_surface_phase(true, 0.40, 0.25);
2035 assert!(
2036 early.anchor_presence == 0.0,
2037 "the primary alone owns the anchor recoil: {early:?}"
2038 );
2039 assert_eq!(early.glue, 0.0);
2040 assert!(early.wobble <= 0.10);
2041 assert!(early.bulge <= 0.40);
2042 assert_eq!(early, menu_surface_phase(true, 0.40, 0.25));
2043
2044 let closing = menu_surface_phase(false, 0.6, 0.68);
2045 assert_eq!(closing.anchor_presence, 0.0);
2046 assert_eq!(closing.glue, 0.0);
2047 assert!(closing.wobble <= 0.05);
2048 assert!(
2049 closing.bulge <= 0.30,
2050 "close must remain smooth: {closing:?}"
2051 );
2052 }
2053
2054 #[test]
2055 fn menu_trigger_backdrop_unmounts_during_the_first_absorption_frame() {
2056 assert!((30..=40).contains(&MENU_TRIGGER_ABSORPTION_MS));
2057 assert_eq!(MENU_TRIGGER_RESTORE_DELAY_MS, 205);
2058 }
2059
2060 #[test]
2061 fn absorbed_source_foreground_stays_readable_then_stretches_into_the_surface() {
2062 let source = LiquidMenuAbsorbedSource::new(
2063 Rect {
2064 x: 10.0,
2065 y: 20.0,
2066 width: 44.0,
2067 height: 44.0,
2068 },
2069 crate::widgets::GlassButtonSpec::glass()
2070 .with_icon_backplate(Color::from_rgb_u8(0, 122, 255))
2071 .with_content_color(Color::WHITE),
2072 44.0,
2073 "M0 0",
2074 );
2075 assert_eq!(source.rect.width, 44.0);
2076 assert_eq!(source.diameter, 44.0);
2077 assert_eq!(source.icon_path, "M0 0");
2078
2079 let source = menu_absorbed_visual_phase(0.0, 0.0);
2080 assert_eq!(source.foreground_alpha, 1.0);
2081 assert_eq!(source.backdrop_alpha, 0.0);
2082
2083 let crisp = menu_absorbed_visual_phase(0.20, 0.20);
2084 assert_eq!(crisp.foreground_alpha, 1.0);
2085 assert_eq!(crisp.backdrop_alpha, 0.0);
2086 assert_eq!(crisp.foreground_blur, 0.0);
2087 assert!((0.76..=0.78).contains(&crisp.scale_x));
2088 assert!((0.76..=0.78).contains(&crisp.scale_y));
2089 let dimmed = menu_absorbed_visual_phase(0.60, 0.30);
2090 assert!((0.38..=0.42).contains(&dimmed.foreground_alpha));
2091
2092 let melt = menu_absorbed_visual_phase(0.95, 0.90);
2093 assert_eq!(melt.foreground_alpha, 0.0);
2094 assert_eq!(melt.backdrop_alpha, 0.62);
2095 assert!((0.92..=0.97).contains(&melt.scale_y));
2096 assert!((0.87..=0.905).contains(&melt.scale_x));
2097
2098 let smear = menu_absorbed_visual_phase(0.72, 0.69);
2099 assert!((0.94..=0.98).contains(&smear.scale_y));
2100 assert!((0.89..=0.91).contains(&smear.scale_x));
2101 assert!((0.10..=0.18).contains(&smear.foreground_alpha));
2102 assert!((0.36..=0.44).contains(&smear.backdrop_alpha));
2103 let transition = menu_absorbed_visual_phase(0.42, 0.382);
2104 assert!((0.60..=0.75).contains(&transition.foreground_alpha));
2105 assert_eq!(transition.backdrop_alpha, 0.0);
2106 let settled = menu_absorbed_visual_phase(1.0, 1.0);
2107 assert_eq!(settled.foreground_alpha, 0.0);
2108 assert_eq!(settled.backdrop_alpha, 0.62);
2109 assert_eq!(MENU_SOURCE_FOREGROUND_HIDE_MS, 200);
2110 assert_eq!(MENU_SOURCE_FOREGROUND_RESTORE_DELAY_MS, 205);
2111 }
2112
2113 #[test]
2114 fn liquid_menu_item_builders_preserve_the_row_contract() {
2115 let item = LiquidMenuItem::new("Delete")
2116 .icon("M0 0")
2117 .checked(true)
2118 .destructive()
2119 .section_start();
2120 assert_eq!(item.label, "Delete");
2121 assert_eq!(item.icon, Some("M0 0"));
2122 assert!(item.checked);
2123 assert!(item.destructive);
2124 assert!(item.section_start);
2125 assert!(!item.header);
2126
2127 let header = LiquidMenuItem::header("Show");
2128 assert_eq!(header.label, "Show");
2129 assert!(header.header);
2130 }
2131
2132 #[test]
2133 fn claimed_menu_gesture_streams_one_release_to_an_interactive_row() {
2134 let _runtime =
2135 cranpose_core::Runtime::new(std::sync::Arc::new(cranpose_core::DefaultScheduler));
2136 let gesture = LiquidMenuGesture::new();
2137 let items = vec![LiquidMenuItem::header("Show"), LiquidMenuItem::new("Grid")];
2138 gesture.item_rect(0).set(Rect {
2139 x: 10.0,
2140 y: 20.0,
2141 width: 100.0,
2142 height: 30.0,
2143 });
2144 gesture.item_rect(1).set(Rect {
2145 x: 10.0,
2146 y: 50.0,
2147 width: 100.0,
2148 height: 40.0,
2149 });
2150
2151 gesture.begin(Point::new(80.0, 10.0));
2152 gesture.claim();
2153 gesture.move_to(Point::new(40.0, 65.0));
2154 let held = gesture.snapshot();
2155 assert!(held.active && held.claimed);
2156 assert_eq!(gesture.item_at(held.position, &items), Some(1));
2157 assert_eq!(gesture.item_at(Point::new(40.0, 35.0), &items), None);
2158
2159 gesture.release(Point::new(40.0, 65.0));
2160 let released = gesture.snapshot();
2161 assert!(!released.active);
2162 assert_eq!(released.release, Some((1, Point::new(40.0, 65.0))));
2163 gesture.release(Point::new(40.0, 65.0));
2164 assert_eq!(gesture.snapshot().release, released.release);
2165 }
2166
2167 #[test]
2168 fn committing_a_row_dismisses_unless_the_row_keeps_the_menu_open() {
2169 let taps = Rc::new(Cell::new(0usize));
2170 let dismissals = Rc::new(Cell::new(0usize));
2171 let on_item: Rc<dyn Fn(usize)> = {
2172 let taps = Rc::clone(&taps);
2173 Rc::new(move |_| taps.set(taps.get() + 1))
2174 };
2175 let on_dismiss: Rc<dyn Fn()> = {
2176 let dismissals = Rc::clone(&dismissals);
2177 Rc::new(move || dismissals.set(dismissals.get() + 1))
2178 };
2179
2180 commit_menu_row(0, false, &on_item, &on_dismiss);
2181 assert_eq!(
2182 (taps.get(), dismissals.get()),
2183 (1, 1),
2184 "an ordinary row dismisses"
2185 );
2186
2187 commit_menu_row(1, true, &on_item, &on_dismiss);
2188 assert_eq!(
2189 (taps.get(), dismissals.get()),
2190 (2, 1),
2191 "a row that keeps the menu open runs its action and dismisses nothing"
2192 );
2193 }
2194
2195 #[test]
2196 fn a_row_is_committed_exactly_once_per_tap() {
2197 let dismissals = Rc::new(Cell::new(0usize));
2198 let on_item: Rc<dyn Fn(usize)> = Rc::new(|_| {});
2199 let on_dismiss: Rc<dyn Fn()> = {
2200 let dismissals = Rc::clone(&dismissals);
2201 Rc::new(move || dismissals.set(dismissals.get() + 1))
2202 };
2203 commit_menu_row(0, false, &on_item, &on_dismiss);
2204 assert_eq!(dismissals.get(), 1);
2205 }
2206}