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
//! ClickableText widget for handling clicks on annotated text.
//!
//! Mirrors Jetpack Compose's `ClickableText` from:
//! `compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/ClickableText.kt`
#![expect(non_snake_case, reason = "names follow Compose's casing")]
use std::{cell::Cell, rc::Rc};
use cranpose_core::{NodeId, remember};
use cranpose_ui_graphics::Size;
use crate::{
modifier::Modifier,
text::{AnnotatedString, TextLayoutOptions, TextOverflow, TextStyle, measure},
widgets::BasicTextWithOptions,
};
/// Displays annotated text and calls `on_click` with the byte offset under the pointer.
/// Use [`LinkedText`](crate::LinkedText) for URL and custom-action annotations.
///
/// # Example
///
/// ```rust
/// use cranpose_ui::{text::AnnotatedString, *};
///
/// #[composable]
/// fn OffsetLabel() {
/// ClickableText(
/// AnnotatedString::from("Click a character"),
/// Modifier::empty(),
/// TextStyle::default(),
/// |offset| println!("Byte offset: {offset}"),
/// );
/// }
/// ```
pub fn ClickableText(
text: impl Into<AnnotatedString>,
modifier: Modifier,
style: TextStyle,
on_click: impl Fn(usize) + 'static,
) -> NodeId {
let text = text.into();
let text_for_click = text.clone();
let style_for_click = style.clone();
let options = TextLayoutOptions {
overflow: TextOverflow::Clip,
soft_wrap: true,
max_lines: usize::MAX,
min_lines: 1,
};
// The click finds its offset in the text wrapped as the node draws it,
// at the width of the node's content.
let size = remember(|| Rc::new(Cell::new(Size::default()))).with(Rc::clone);
let clickable_modifier = modifier
.report_size(Rc::clone(&size))
.clickable(move |point| {
on_click(measure::offset_in_drawn_text(
&text_for_click,
&style_for_click,
options,
size.get().width,
point,
));
});
BasicTextWithOptions(text, clickable_modifier, style, options)
}
#[cfg(test)]
#[path = "tests/clickable_text_tests.rs"]
mod tests;