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