cranpose-ui 0.1.43

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
//! Android-style cursor/selection magnifier ("loupe") shown while dragging a
//! text-field selection handle.
//!
//! When a finger drags the caret (or a selection endpoint) it sits right on top
//! of the glyphs it is trying to place, hiding them. Android floats a small
//! magnified slice of the text just above the finger so the exact caret
//! position stays visible. [`CursorMagnifier`] renders that loupe in the
//! top-level overlay via [`Popup`]: a rounded frame containing the caret's line
//! of text scaled up and translated so the caret sits at the loupe's center,
//! with a caret indicator drawn through it.
//!
//! It is touch-only by construction — the caller (`BasicTextField`) only emits
//! it while a finger is actively dragging a handle, and the field's handles are
//! themselves gated on touch input.
//!
//! ## What is simplified
//!
//! The loupe magnifies the caret's own text line (not wrapped neighbours) and
//! applies a pure scale+translate through a `graphics_layer`; it does not
//! re-render the surrounding field background or selection highlight inside the
//! lens. That is enough to keep the caret glyphs visible under the finger; a
//! fuller "screenshot the field region" lens is left for later.

#![allow(non_snake_case)]

use crate::composable;
use crate::modifier::Modifier;
use crate::text::{measure_text, AnnotatedString, TextOptions, TextOverflow, TextStyle};
use crate::text_field_modifier_node::TextFieldHandleMetrics;
use crate::widgets::box_widget::{Box, BoxSpec};
use crate::widgets::popup::Popup;
use crate::widgets::TextWithOptions;
use cranpose_ui_graphics::{Color, GraphicsLayer, Point, Rect, Size, TransformOrigin};

/// Magnification factor for the loupe (Android uses ~1.25–1.5×).
const MAGNIFICATION: f32 = 1.4;
/// Loupe frame size in logical px.
const LOUPE_WIDTH: f32 = 150.0;
const LOUPE_HEIGHT: f32 = 46.0;
/// Distance (px) between the finger/drag point and the bottom of the loupe, so
/// the finger never covers the magnified content.
const GAP_ABOVE_FINGER: f32 = 44.0;
/// 1px border ring thickness.
const BORDER_PX: f32 = 1.0;

const FRAME_FILL: Color = Color(1.0, 1.0, 1.0, 1.0);
const FRAME_BORDER: Color = Color(0.62, 0.64, 0.68, 1.0);
/// Caret indicator color (Android accent blue), matching the field handles.
const CARET_COLOR: Color = Color(0.26, 0.52, 0.96, 1.0);

/// The text of the line containing byte `offset`, and the caret's x within that
/// line (px, content space) measured with `style`.
fn caret_line(text: &str, style: &TextStyle, offset: usize) -> (String, f32) {
    let offset = offset.min(text.len());
    let before = &text[..offset];
    let line_start = before.rfind('\n').map(|i| i + 1).unwrap_or(0);
    let after = &text[offset..];
    let line_end = offset + after.find('\n').unwrap_or(after.len());
    let line = text[line_start..line_end].to_string();
    let caret_x = measure_text(&AnnotatedString::from(&text[line_start..offset]), style).width;
    (line, caret_x)
}

/// Floating magnifier loupe centered on the caret at `caret_offset`, positioned
/// just above `finger` (window coordinates of the active drag point).
///
/// * `text` / `style` — the field's current text and text style.
/// * `metrics` — live field handle metrics (used for the line height).
/// * `caret_offset` — byte offset the loupe is magnifying (the dragged caret).
/// * `finger` — window position of the finger, so the loupe floats above it.
#[composable]
pub fn CursorMagnifier(
    text: String,
    style: TextStyle,
    metrics: TextFieldHandleMetrics,
    caret_offset: usize,
    finger: Point,
) {
    let (line, caret_x) = caret_line(&text, &style, caret_offset);
    let line_height = metrics.line_height.max(1.0);
    // Full intrinsic width of the caret's line (content px, unscaled). The
    // magnified text is forced to lay out at exactly this width (see the
    // `required_size` below), so every glyph up to the caret exists in the layer
    // before the graphics-layer translation slides the caret slice into view.
    let line_width = measure_text(&AnnotatedString::from(line.as_str()), &style)
        .width
        .max(1.0);

    // Float the loupe above the finger, clamped on-screen at the top edge.
    let anchor = Rect {
        x: (finger.x - LOUPE_WIDTH / 2.0).max(0.0),
        y: (finger.y - GAP_ABOVE_FINGER - LOUPE_HEIGHT).max(0.0),
        width: 0.0,
        height: 0.0,
    };

    // Scale the caret's line about its top-left, then translate so the caret's
    // content-x lands at the loupe's horizontal center and the line is centered
    // vertically. drawn_x = MAGNIFICATION * local_x + translation_x.
    let magnified_line_height = line_height * MAGNIFICATION;
    let translation_x = LOUPE_WIDTH / 2.0 - MAGNIFICATION * caret_x;
    let translation_y = (LOUPE_HEIGHT - magnified_line_height) / 2.0;
    let text_layer = GraphicsLayer {
        transform_origin: TransformOrigin::new(0.0, 0.0),
        scale: 1.0,
        scale_x: MAGNIFICATION,
        scale_y: MAGNIFICATION,
        translation_x,
        translation_y,
        ..GraphicsLayer::default()
    };

    // Caret indicator: a thin vertical bar at the loupe center spanning the
    // magnified line height.
    let caret_top = (LOUPE_HEIGHT - magnified_line_height) / 2.0;

    Popup(anchor, Point { x: 0.0, y: 0.0 }, move || {
        let line = line.clone();
        let style = style.clone();
        let text_layer = text_layer.clone();
        // Border ring: an outer filled+rounded box, inset by BORDER_PX to the
        // fill (cranpose has no dedicated border modifier yet).
        Box(
            Modifier::empty()
                .size(Size {
                    width: LOUPE_WIDTH,
                    height: LOUPE_HEIGHT,
                })
                .background(FRAME_BORDER)
                .rounded_corners(10.0),
            BoxSpec::default(),
            move || {
                let line = line.clone();
                let style = style.clone();
                let text_layer = text_layer.clone();
                Box(
                    Modifier::empty()
                        .padding(BORDER_PX)
                        .size(Size {
                            width: LOUPE_WIDTH - 2.0 * BORDER_PX,
                            height: LOUPE_HEIGHT - 2.0 * BORDER_PX,
                        })
                        .background(FRAME_FILL)
                        .rounded_corners(9.0)
                        .clip_to_bounds(),
                    BoxSpec::default(),
                    move || {
                        // Magnified slice of the caret's text line.
                        //
                        // The loupe frame is only ~150px wide, but a wide line's
                        // caret can sit thousands of px to the right. Two things
                        // make the far-right glyphs render:
                        //
                        // 1. `required_size` forces the text to lay out at the
                        //    line's FULL intrinsic width, ignoring the loupe box's
                        //    narrow (~148px) incoming constraint. Without it the
                        //    text's placeable is clamped to the frame width, so
                        //    only the leftmost glyphs exist in the layer and the
                        //    graphics-layer translation slides an empty strip into
                        //    view — the reported blank loupe on long lines.
                        // 2. `Visible` overflow (soft-wrap OFF) keeps the text a
                        //    single unwrapped line and skips the per-node clip.
                        //
                        // The graphics layer then translates the caret slice to
                        // the frame centre and the outer box's `clip_to_bounds`
                        // trims everything outside the loupe.
                        TextWithOptions(
                            line.clone(),
                            Modifier::empty()
                                .required_size(Size {
                                    width: line_width,
                                    height: line_height,
                                })
                                .graphics_layer_value(text_layer.clone()),
                            style.clone(),
                            TextOptions {
                                overflow: TextOverflow::Visible,
                                soft_wrap: false,
                                ..TextOptions::default()
                            },
                        );
                        // Caret indicator through the loupe center.
                        Box(
                            Modifier::empty()
                                .absolute_offset(LOUPE_WIDTH / 2.0 - 1.0, caret_top)
                                .size(Size {
                                    width: 2.0,
                                    height: magnified_line_height,
                                })
                                .background(CARET_COLOR),
                            BoxSpec::default(),
                            || {},
                        );
                    },
                );
            },
        );
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::layout::LayoutEngine;
    use crate::renderer::{HeadlessRenderer, RecordedRenderScene, RenderOp};
    use crate::widgets::PopupHost;
    use cranpose_core::{location_key, Composition, MemoryApplier};

    fn render_magnifier(finger: Point, caret_offset: usize) -> RecordedRenderScene {
        let mut composition = Composition::new(MemoryApplier::new());
        let key = location_key(file!(), line!(), column!());
        let metrics = TextFieldHandleMetrics {
            focused: true,
            touch: true,
            node_origin: Point { x: 0.0, y: 40.0 },
            padding_left: 0.0,
            padding_top: 0.0,
            scroll_offset: 0.0,
            line_height: 18.0,
            wrap_width: None,
        };
        let mut content = move || {
            PopupHost(move || {
                CursorMagnifier(
                    "hello world".to_string(),
                    TextStyle::default(),
                    metrics,
                    caret_offset,
                    finger,
                );
            });
        };
        composition.render(key, &mut content).expect("render");
        for _ in 0..16 {
            if !composition.should_render() {
                break;
            }
            composition.reconcile(key, &mut content).expect("reconcile");
        }
        let root = composition.root().expect("root");
        let handle = composition.runtime_handle();
        let mut applier = composition.applier_mut();
        applier.set_runtime_handle(handle);
        let layout = applier
            .compute_layout(
                root,
                Size {
                    width: 500.0,
                    height: 500.0,
                },
            )
            .expect("layout");
        applier.clear_runtime_handle();
        drop(applier);
        HeadlessRenderer::new().render(&layout)
    }

    fn text_ops(scene: &RecordedRenderScene) -> Vec<(String, Rect)> {
        scene
            .operations()
            .iter()
            .filter_map(|op| match op {
                RenderOp::Text { value, rect, .. } => Some((value.clone(), *rect)),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn magnifier_shows_the_caret_line_floated_above_the_finger() {
        let _app_context = crate::render_state::app_context_test_scope();
        let finger = Point { x: 120.0, y: 300.0 };
        let scene = render_magnifier(finger, 3);

        let texts = text_ops(&scene);
        // The loupe magnifies the caret's whole line ("hello world" has no
        // newline, so the line is the full text).
        let line = texts
            .iter()
            .find(|(value, _)| value == "hello world")
            .expect("magnifier renders the caret's line of text");
        // The loupe floats ABOVE the finger so it never covers the caret.
        assert!(
            line.1.y < finger.y,
            "the magnified text {} must render above the finger at y={}",
            line.1.y,
            finger.y
        );
    }

    #[test]
    fn magnifier_lays_out_the_full_line_under_the_loupe_width() {
        // Regression for the "loupe blanks on wide lines" bug. The magnifier
        // draws the caret's line inside a ~150px frame and slides it with a
        // graphics-layer translation. If the text is measured against the frame's
        // narrow max-width (the old behaviour), glyphs past ~150px are never laid
        // out, so a far-right caret shows only the background. The magnifier now
        // lays the line out with `TextOverflow::Visible` + no soft-wrap, so it
        // keeps its FULL intrinsic width no matter how narrow the frame is.
        use crate::text::{measure_text_with_options, AnnotatedString, TextLayoutOptions};

        let _app_context = crate::render_state::app_context_test_scope();
        let wide_line = "abcdefghij ".repeat(30); // thousands of px wide
        let text = AnnotatedString::from(wide_line.as_str());
        let style = TextStyle::default();
        let loupe_max = Some(LOUPE_WIDTH);

        // Baseline: clamping to the loupe width (soft-wrap/clip) bounds the line
        // to the frame — this is exactly the state that blanked far-right glyphs.
        let clamped = measure_text_with_options(
            &text,
            &style,
            TextLayoutOptions {
                overflow: TextOverflow::Clip,
                soft_wrap: true,
                max_lines: 1,
                min_lines: 1,
            },
            loupe_max,
        );
        assert!(
            clamped.width <= LOUPE_WIDTH + 1.0,
            "sanity: a clamped line is bounded by the loupe width, got {}",
            clamped.width
        );

        // The magnifier's options lay the whole line out regardless of the frame.
        let full = measure_text_with_options(
            &text,
            &style,
            TextLayoutOptions {
                overflow: TextOverflow::Visible,
                soft_wrap: false,
                max_lines: 1,
                min_lines: 1,
            },
            loupe_max,
        );
        assert!(
            full.width > LOUPE_WIDTH * 3.0,
            "magnifier text must keep its full intrinsic width under the narrow \
             loupe max-width so far-right glyphs exist to draw (got {} vs loupe {LOUPE_WIDTH})",
            full.width
        );
    }

    #[test]
    fn magnifier_text_node_lays_out_at_full_width_in_the_scene() {
        // The real layout pipeline: the magnified line's Text node must lay out
        // at its full intrinsic width (via `required_size`), NOT clamped to the
        // loupe frame — otherwise only the leftmost glyphs exist in the layer and
        // a far-right caret shows an empty loupe. The recorded Text op's rect
        // width is the node's laid-out width, so it must exceed the loupe frame.
        let _app_context = crate::render_state::app_context_test_scope();
        let wide_line = "abcdefghij ".repeat(30);

        let mut composition = Composition::new(MemoryApplier::new());
        let key = location_key(file!(), line!(), column!());
        let metrics = TextFieldHandleMetrics {
            focused: true,
            touch: true,
            node_origin: Point { x: 0.0, y: 40.0 },
            padding_left: 0.0,
            padding_top: 0.0,
            scroll_offset: 0.0,
            line_height: 18.0,
            wrap_width: None,
        };
        let line_for_content = wide_line.clone();
        // Caret far to the right of the wide line — the case that used to blank.
        let caret_offset = wide_line.len() - 4;
        let mut content = move || {
            let line_for_content = line_for_content.clone();
            PopupHost(move || {
                CursorMagnifier(
                    line_for_content.clone(),
                    TextStyle::default(),
                    metrics,
                    caret_offset,
                    Point { x: 700.0, y: 400.0 },
                );
            });
        };
        composition.render(key, &mut content).expect("render");
        for _ in 0..16 {
            if !composition.should_render() {
                break;
            }
            composition.reconcile(key, &mut content).expect("reconcile");
        }
        let root = composition.root().expect("root");
        let handle = composition.runtime_handle();
        let mut applier = composition.applier_mut();
        applier.set_runtime_handle(handle);
        let layout = applier
            .compute_layout(
                root,
                Size {
                    width: 1080.0,
                    height: 800.0,
                },
            )
            .expect("layout");
        applier.clear_runtime_handle();
        drop(applier);
        let scene = HeadlessRenderer::new().render(&layout);

        let line = text_ops(&scene)
            .into_iter()
            .find(|(value, _)| value == &wide_line)
            .expect("magnifier renders the caret's line");
        assert!(
            line.1.width > LOUPE_WIDTH,
            "the magnified line's Text node must lay out at full width (got {} vs \
             loupe {LOUPE_WIDTH}); a clamped width means far-right glyphs are missing",
            line.1.width
        );
    }

    #[test]
    fn magnifier_frame_is_drawn() {
        use cranpose_ui_graphics::DrawPrimitive;
        let _app_context = crate::render_state::app_context_test_scope();
        let scene = render_magnifier(Point { x: 120.0, y: 300.0 }, 3);
        // The loupe draws its rounded frame fill and a caret indicator as rects.
        let rects = scene
            .operations()
            .iter()
            .filter(|op| {
                matches!(
                    op,
                    RenderOp::Primitive {
                        primitive: DrawPrimitive::Rect { .. } | DrawPrimitive::RoundRect { .. },
                        ..
                    }
                )
            })
            .count();
        assert!(
            rects >= 2,
            "the loupe should draw a frame and a caret indicator, got {rects} rects"
        );
    }
}