cranpose-ui 0.1.164

UI primitives for Cranpose
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
//! The floating text edit menu: a liquid-glass capsule of actions above the
//! selection / caret, matched against the reference recording
//! (`example/target/text-selection/`).
//!
//! Geometry and material (all measured): a 44 dp glass capsule — weak
//! backdrop blur (content behind stays readable through the body), a whisper
//! of dark tint, a top rim highlight — holding white ~15 sp labels separated
//! by 1 dp hairlines (17 dp tall, centered). When the actions don't fit the
//! window, the overflow lives behind a trailing chevron `›` sitting in a
//! lighter glass disc that fills the capsule's end cap (pressing it flashes
//! the disc white and pages the items).
//!
//! Placement: centered over the selection, clamped to a 20 dp screen margin;
//! the capsule's bottom rides 15 dp above the selection's first line.
//!
//! Motion (from the 120 fps reference): the menu dissolves in ~70 ms the
//! moment a handle drag starts, and rematerializes in place ~250 ms after
//! release with a ~140 ms fade (no scale, no slide).

use std::{
    cell::{Cell, RefCell},
    rc::Rc,
};

use cranpose_animation::{Animatable, AnimationSpec, AnimationType, Easing};
use cranpose_core::{SideEffect, remember, with_current_composer};
use cranpose_foundation::PointerEventKind;
use cranpose_ui_graphics::{
    GraphicsLayer, LayerShape, Point, Rect, RoundedCornerShape, Size, liquid_menu_glass_effect,
};

use crate::{
    PointerInputScope, composable,
    modifier::{Color, Modifier},
    text::{AnnotatedString, TextStyle, TextUnit, measure_text},
    widgets::{
        Row, RowSpec, Text,
        box_widget::{Box, BoxSpec},
        popup::{Popup, local_popup_viewport},
    },
};

/// Capsule height (dp) — the measured 133 px @3x.
pub const MENU_HEIGHT: f32 = 44.0;
/// Minimum gap between the capsule and the window edges.
const MENU_SCREEN_MARGIN: f32 = 20.0;
/// Gap between the capsule bottom and the selection's first line top.
const MENU_GAP_ABOVE_LINE: f32 = 15.0;
/// Horizontal padding on each side of an item label.
const ITEM_PADDING: f32 = 20.0;
/// Hairline separator between labels: 1×17 dp.
const SEPARATOR_WIDTH: f32 = 1.0;
const SEPARATOR_HEIGHT: f32 = 17.0;
const MENU_FONT_SP: f32 = 15.0;

/// CompositionLocal marking the surface the floating glass sits over as
/// LIGHT. Liquid glass is transparent, so its labels and hairlines must
/// flip to dark ink over a light backdrop to stay readable — the same
/// content over a dark app keeps its near-white ink. Defaults to `false`
/// (dark surface), preserving the existing look; a light-themed screen
/// provides `true`.
pub fn local_on_light_surface() -> cranpose_core::CompositionLocal<bool> {
    use std::cell::RefCell;
    thread_local! {
        static LOCAL: RefCell<Option<cranpose_core::CompositionLocal<bool>>> =
            const { RefCell::new(None) };
    }
    LOCAL.with(|cell| {
        cell.borrow_mut()
            .get_or_insert_with(|| cranpose_core::compositionLocalOf(|| false))
            .clone()
    })
}

/// Label ink: near-white over a dark surface, near-black over a light one.
fn menu_fg(on_light: bool) -> Color {
    if on_light {
        Color(0.08, 0.08, 0.10, 1.0)
    } else {
        Color(0.96, 0.96, 0.98, 1.0)
    }
}

/// Hairline separator: a whisper of the ink polarity.
fn separator_color(on_light: bool) -> Color {
    if on_light {
        Color(0.0, 0.0, 0.0, 0.10)
    } else {
        Color(1.0, 1.0, 1.0, 0.07)
    }
}

/// The chevron disc glass fill and its pressed flash follow the polarity.
fn disc_color(on_light: bool) -> Color {
    if on_light {
        Color(0.0, 0.0, 0.0, 0.10)
    } else {
        Color(1.0, 1.0, 1.0, 0.19)
    }
}

fn disc_pressed_color(on_light: bool) -> Color {
    if on_light {
        Color(0.0, 0.0, 0.0, 0.55)
    } else {
        Color(1.0, 1.0, 1.0, 0.9)
    }
}
/// Backdrop blur behind the capsule, dp.
/// The materialize smudge radius; the effect resolves it to ~a fifth as the
/// menu sharpens (the settled reference pill keeps backdrop text readable).
const MENU_BLUR_DP: f32 = 15.0;

/// Motion (measured): ~70 ms dissolve, ~140 ms materialize arriving ~250 ms
/// after the release.
const MENU_DISSOLVE_MS: u64 = 70;
const MENU_MATERIALIZE_MS: u64 = 140;
const MENU_RETURN_DELAY_MS: u64 = 250;

fn menu_text_style(on_light: bool) -> TextStyle {
    let mut style = TextStyle::default();
    style.span_style.color = Some(menu_fg(on_light));
    style.span_style.font_size = TextUnit::Sp(MENU_FONT_SP);
    style
}

/// One tappable action.
#[derive(Clone)]
pub struct TextMenuItem {
    pub label: String,
    pub action: Rc<dyn Fn()>,
}

impl TextMenuItem {
    pub fn new(label: impl Into<String>, action: impl Fn() + 'static) -> Self {
        Self {
            label: label.into(),
            action: Rc::new(action),
        }
    }
}

impl PartialEq for TextMenuItem {
    fn eq(&self, other: &Self) -> bool {
        self.label == other.label && Rc::ptr_eq(&self.action, &other.action)
    }
}

impl std::fmt::Debug for TextMenuItem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TextMenuItem")
            .field("label", &self.label)
            .finish()
    }
}

/// Builds the consuming tap gesture for a menu button: it swallows the press,
/// any moves, and the release. It fires `action` when the finger lifts after
/// a press that started on this button, or when an already-active continuous
/// press slides onto this button and lifts. Every event is consumed so the
/// gesture can never fall through to the text field beneath the overlay.
/// Keyed by the button label so recomposition reuses the running gesture task.
pub(crate) fn menu_item_pointer_input(
    label: &str,
    action: Rc<dyn Fn()>,
    continuous_press: Rc<Cell<bool>>,
) -> Modifier {
    let key = label.to_string();
    Modifier::empty().pointer_input(key, move |scope: PointerInputScope| {
        let action = Rc::clone(&action);
        let continuous_press = Rc::clone(&continuous_press);
        async move {
            scope
                .await_pointer_event_scope(|await_scope| async move {
                    let mut pressed = false;
                    loop {
                        let event = await_scope.await_pointer_event().await;
                        match event.kind {
                            PointerEventKind::Down => {
                                pressed = true;
                                event.consume();
                            }
                            PointerEventKind::Move => {
                                event.consume();
                            }
                            PointerEventKind::Up => {
                                if pressed || continuous_press.get() {
                                    action();
                                }
                                pressed = false;
                                event.consume();
                            }
                            PointerEventKind::Cancel => {
                                pressed = false;
                                event.consume();
                            }
                            _ => {}
                        }
                    }
                })
                .await;
        }
    })
}

/// The chevron disc's press-flash + page gesture: flashes the disc white
/// while held (the reference press feedback) and advances the page on lift.
fn disc_pointer_input(
    pressed: Rc<Cell<bool>>,
    on_tap: Rc<dyn Fn()>,
    invalidate: Rc<dyn Fn()>,
) -> Modifier {
    Modifier::empty().pointer_input("menu-overflow-disc", move |scope: PointerInputScope| {
        let pressed = Rc::clone(&pressed);
        let on_tap = Rc::clone(&on_tap);
        let invalidate = Rc::clone(&invalidate);
        async move {
            scope
                .await_pointer_event_scope(|await_scope| async move {
                    let mut down = false;
                    loop {
                        let event = await_scope.await_pointer_event().await;
                        match event.kind {
                            PointerEventKind::Down => {
                                down = true;
                                pressed.set(true);
                                invalidate();
                                event.consume();
                            }
                            PointerEventKind::Move => {
                                event.consume();
                            }
                            PointerEventKind::Up => {
                                if down {
                                    on_tap();
                                }
                                down = false;
                                pressed.set(false);
                                invalidate();
                                event.consume();
                            }
                            PointerEventKind::Cancel => {
                                down = false;
                                pressed.set(false);
                                invalidate();
                                event.consume();
                            }
                            _ => {}
                        }
                    }
                })
                .await;
        }
    })
}

/// Measured width of one label cell (padding + text + padding), dp.
fn item_width(label: &str, style: &TextStyle) -> f32 {
    measure_text(&AnnotatedString::from(label), style).width + 2.0 * ITEM_PADDING
}

/// Page-relative index of the item under a live slide point, walking the
/// same measured cell widths the Row lays out (6dp of vertical grace above
/// and below the capsule).
fn slide_item_at(
    point: cranpose_ui_graphics::Point,
    origin_x: f32,
    origin_y: f32,
    page_items: &[TextMenuItem],
    style: &TextStyle,
) -> Option<usize> {
    if point.y < origin_y - 6.0 || point.y > origin_y + MENU_HEIGHT + 6.0 {
        return None;
    }
    let mut cursor = origin_x;
    for (index, item) in page_items.iter().enumerate() {
        if index > 0 {
            cursor += SEPARATOR_WIDTH;
        }
        let width = item_width(&item.label, style);
        if point.x >= cursor && point.x < cursor + width {
            return Some(index);
        }
        cursor += width;
    }
    None
}

/// Splits `items` into pages that fit `max_width`, appending the chevron
/// disc's width to any page that is followed by more items. Every page holds
/// at least one item.
fn paginate(items: &[TextMenuItem], style: &TextStyle, max_width: f32) -> Vec<Vec<usize>> {
    let widths: Vec<f32> = items
        .iter()
        .map(|item| item_width(&item.label, style))
        .collect();
    let total: f32 =
        widths.iter().sum::<f32>() + SEPARATOR_WIDTH * items.len().saturating_sub(1) as f32;
    if total <= max_width || items.len() <= 1 {
        return vec![(0..items.len()).collect()];
    }
    let disc = MENU_HEIGHT;
    let mut pages: Vec<Vec<usize>> = Vec::new();
    let mut page: Vec<usize> = Vec::new();
    let mut used = disc;
    for (index, width) in widths.iter().enumerate() {
        let extra = width
            + if page.is_empty() {
                0.0
            } else {
                SEPARATOR_WIDTH
            };
        if !page.is_empty() && used + extra > max_width {
            pages.push(std::mem::take(&mut page));
            used = disc;
        }
        used += width
            + if page.is_empty() {
                0.0
            } else {
                SEPARATOR_WIDTH
            };
        page.push(index);
    }
    if !page.is_empty() {
        pages.push(page);
    }
    pages
}

/// Animated visibility state for the menu (dissolve fast, rematerialize
/// after the measured delay).
struct MenuMotion {
    progress: RefCell<Animatable<f32>>,
    was_visible: Cell<bool>,
    page: Cell<usize>,
    disc_pressed: Rc<Cell<bool>>,
    slide_hover: Cell<Option<usize>>,
    slide_live: Rc<Cell<bool>>,
}

/// The liquid-glass text edit menu.
///
/// * `center_x` — window-space x to center the capsule on (the selection /
///   caret center); clamped to the screen margin.
/// * `line_top_y` — window-space top of the selection's first line; the
///   capsule bottom rides `MENU_GAP_ABOVE_LINE` above it.
/// * `visible` — false while a handle drag is in flight; the menu dissolves
///   and rematerializes per the measured timings (it stays mounted while
///   fading).
/// * `items` — the actions.
#[composable]
pub fn LiquidTextMenu(
    center_x: f32,
    line_top_y: f32,
    visible: bool,
    live_point: Option<cranpose_ui_graphics::Point>,
    items: Vec<TextMenuItem>,
) {
    let motion = remember(|| {
        let runtime = with_current_composer(|composer| composer.runtime_handle());
        Rc::new(MenuMotion {
            progress: RefCell::new(Animatable::new(0.0, runtime)),
            was_visible: Cell::new(false),
            page: Cell::new(0),
            disc_pressed: Rc::new(Cell::new(false)),
            slide_hover: Cell::new(None),
            slide_live: Rc::new(Cell::new(false)),
        })
    })
    .with(Rc::clone);

    if visible != motion.was_visible.get() {
        motion.was_visible.set(visible);
        let mut progress = motion.progress.borrow_mut();
        if visible {
            progress.animateTo(
                1.0,
                AnimationType::Tween(
                    AnimationSpec::tween(MENU_MATERIALIZE_MS, Easing::EaseOut)
                        .with_delay(MENU_RETURN_DELAY_MS),
                ),
            );
        } else {
            progress.animateTo(
                0.0,
                AnimationType::Tween(AnimationSpec::tween(MENU_DISSOLVE_MS, Easing::LinearEasing)),
            );
        }
    }
    let progress_state = motion.progress.borrow().state();
    let p = progress_state.value().clamp(0.0, 1.0);
    if !visible && p <= 0.01 {
        return;
    }

    let on_light = local_on_light_surface().current();
    let style = menu_text_style(on_light);
    let viewport = local_popup_viewport().current().get();
    let max_width = if viewport.width > 0.0 {
        viewport.width - 2.0 * MENU_SCREEN_MARGIN
    } else {
        f32::INFINITY
    };
    let pages = paginate(&items, &style, max_width);
    let page_index = motion.page.get().min(pages.len() - 1);
    let page = &pages[page_index];
    let has_disc = pages.len() > 1;

    let mut width: f32 = page
        .iter()
        .map(|&i| item_width(&items[i].label, &style))
        .sum();
    width += SEPARATOR_WIDTH * page.len().saturating_sub(1) as f32;
    if has_disc {
        width += MENU_HEIGHT;
    }

    let mut x = center_x - width * 0.5;
    if viewport.width > 0.0 {
        x = x.min(viewport.width - MENU_SCREEN_MARGIN - width);
    }
    x = x.max(MENU_SCREEN_MARGIN);
    let y = line_top_y - MENU_GAP_ABOVE_LINE - MENU_HEIGHT;

    let anchor = Rect {
        x,
        y,
        width: 0.0,
        height: 0.0,
    };
    let density = crate::current_density();
    let page_items: Vec<TextMenuItem> = page.iter().map(|&i| items[i].clone()).collect();

    let slide_hover = match live_point {
        Some(point) => {
            motion.slide_live.set(true);
            let hover = slide_item_at(point, x, y, &page_items, &style);
            motion.slide_hover.set(hover);
            hover
        }
        None => {
            let hover = motion.slide_hover.take();
            if motion.slide_live.replace(false) {
                if let Some(index) = hover {
                    if let Some(item) = page_items.get(index) {
                        let action = Rc::clone(&item.action);
                        SideEffect(move || action());
                    }
                }
            }
            None
        }
    };
    let disc_pressed = Rc::clone(&motion.disc_pressed);
    let page_count = pages.len();
    let motion_for_disc = Rc::clone(&motion);
    Popup(anchor, Point { x: 0.0, y: 0.0 }, move || {
        let page_items = page_items.clone();
        let disc_pressed = Rc::clone(&disc_pressed);
        let motion = Rc::clone(&motion_for_disc);
        Box(
            Modifier::empty()
                .size(Size {
                    width,
                    height: MENU_HEIGHT,
                })
                .drop_shadow(
                    LayerShape::Rounded(RoundedCornerShape::uniform(1.0e6)),
                    move |scope| {
                        scope.radius = 16.0;
                        scope.spread = -2.0;
                        scope.offset.y = 0.0;
                        scope.color = Color(1.0, 1.0, 1.0, 0.12 * p * (1.0 - p));
                        scope.cutout = true;
                    },
                )
                .graphics_layer(move || GraphicsLayer {
                    alpha: p,
                    backdrop_effect: (p > 0.001).then(|| {
                        liquid_menu_glass_effect((width, MENU_HEIGHT), MENU_BLUR_DP * density, p)
                    }),
                    shape: LayerShape::Rounded(RoundedCornerShape::uniform(1.0e6)),
                    clip: true,
                    ..Default::default()
                }),
            BoxSpec::default(),
            move || {
                let page_items = page_items.clone();
                let disc_pressed = Rc::clone(&disc_pressed);
                let motion = Rc::clone(&motion);
                Row(
                    Modifier::empty().size(Size {
                        width,
                        height: MENU_HEIGHT,
                    }),
                    RowSpec::default().vertical_alignment(
                        cranpose_ui_layout::VerticalAlignment::CenterVertically,
                    ),
                    move || {
                        for (index, item) in page_items.iter().enumerate() {
                            if index > 0 {
                                Box(
                                    Modifier::empty()
                                        .size(Size {
                                            width: SEPARATOR_WIDTH,
                                            height: SEPARATOR_HEIGHT,
                                        })
                                        .background(separator_color(on_light)),
                                    BoxSpec::default(),
                                    || {},
                                );
                            }
                            let slide_hovered = slide_hover == Some(index);
                            Text(
                                item.label.clone(),
                                Modifier::empty()
                                    .padding_each(ITEM_PADDING, 0.0, ITEM_PADDING, 2.0)
                                    .draw_behind(move |scope| {
                                        if slide_hovered {
                                            let hover = if on_light {
                                                Color(0.0, 0.0, 0.0, 0.08)
                                            } else {
                                                Color(1.0, 1.0, 1.0, 0.10)
                                            };
                                            scope.draw_round_rect(
                                                cranpose_ui_graphics::Brush::solid(hover),
                                                cranpose_ui_graphics::CornerRadii::uniform(10.0),
                                            );
                                        }
                                    })
                                    .then(menu_item_pointer_input(
                                        &item.label,
                                        Rc::clone(&item.action),
                                        Rc::clone(&motion.slide_live),
                                    )),
                                menu_text_style(on_light),
                            );
                        }
                        if page_count > 1 {
                            let pressed_now = disc_pressed.get();
                            let motion = Rc::clone(&motion);
                            let advance: Rc<dyn Fn()> = Rc::new(move || {
                                motion.page.set((motion.page.get() + 1) % page_count);
                                crate::request_render_invalidation();
                            });
                            let invalidate: Rc<dyn Fn()> =
                                Rc::new(crate::request_render_invalidation);
                            Box(
                                Modifier::empty()
                                    .size(Size {
                                        width: MENU_HEIGHT,
                                        height: MENU_HEIGHT,
                                    })
                                    .background(if pressed_now {
                                        disc_pressed_color(on_light)
                                    } else {
                                        disc_color(on_light)
                                    })
                                    .rounded_corners(MENU_HEIGHT * 0.5)
                                    .then(disc_pointer_input(
                                        Rc::clone(&disc_pressed),
                                        advance,
                                        invalidate,
                                    )),
                                BoxSpec::default()
                                    .content_alignment(cranpose_ui_layout::Alignment::CENTER),
                                move || {
                                    Text(
                                        "\u{203A}".to_string(),
                                        Modifier::empty(),
                                        menu_text_style(on_light),
                                    );
                                },
                            );
                        }
                    },
                );
            },
        );
    });
}

/// A floating Copy / Cut / Paste / Select-all menu shown just above the text
/// selection. `center_x` / `line_top_y` anchor it over the selection;
/// `visible` is false while a handle drag is in flight. `can_paste` hides the
/// Paste item when the clipboard is empty. Each action runs against the
/// focused field; the caller is expected to dismiss the menu.
#[expect(clippy::too_many_arguments)]
#[composable]
pub fn TextSelectionMenu(
    center_x: f32,
    line_top_y: f32,
    visible: bool,
    live_point: Option<cranpose_ui_graphics::Point>,
    can_paste: bool,
    on_copy: impl Fn() + 'static,
    on_cut: impl Fn() + 'static,
    on_paste: impl Fn() + 'static,
    on_select_all: impl Fn() + 'static,
) {
    let mut items = vec![
        TextMenuItem::new("Copy", on_copy),
        TextMenuItem::new("Cut", on_cut),
    ];
    if can_paste {
        items.push(TextMenuItem::new("Paste", on_paste));
    }
    items.push(TextMenuItem::new("Select all", on_select_all));
    LiquidTextMenu(center_x, line_top_y, visible, live_point, items);
}

/// A floating Paste / Select all / Undo / Redo menu shown near the collapsed
/// caret. Opened by tapping the cursor handle (there is no selection to
/// Copy/Cut, so this offers the caret-relevant actions instead).
///
/// `can_paste` hides Paste when the clipboard is empty; `can_undo`/`can_redo`
/// hide those items when the field's history has nothing to undo/redo.
#[expect(clippy::too_many_arguments)]
#[composable]
pub fn CaretActionMenu(
    center_x: f32,
    line_top_y: f32,
    visible: bool,
    can_paste: bool,
    can_undo: bool,
    can_redo: bool,
    on_paste: impl Fn() + 'static,
    on_select_all: impl Fn() + 'static,
    on_undo: impl Fn() + 'static,
    on_redo: impl Fn() + 'static,
) {
    let mut items = Vec::new();
    if can_paste {
        items.push(TextMenuItem::new("Paste", on_paste));
    }
    items.push(TextMenuItem::new("Select all", on_select_all));
    if can_undo {
        items.push(TextMenuItem::new("Undo", on_undo));
    }
    if can_redo {
        items.push(TextMenuItem::new("Redo", on_redo));
    }
    LiquidTextMenu(center_x, line_top_y, visible, None, items);
}

#[cfg(test)]
#[path = "tests/text_selection_menu_tests.rs"]
mod tests;