Skip to main content

cranpose_ui/widgets/
clickable_text.rs

1//! ClickableText widget for handling clicks on annotated text.
2//!
3//! Mirrors Jetpack Compose's `ClickableText` from:
4//! `compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/ClickableText.kt`
5
6#![expect(non_snake_case, reason = "names follow Compose's casing")]
7
8use std::{cell::Cell, rc::Rc};
9
10use cranpose_core::{NodeId, remember};
11use cranpose_ui_graphics::Size;
12
13use crate::{
14    modifier::Modifier,
15    text::{AnnotatedString, TextLayoutOptions, TextOverflow, TextStyle, measure},
16    widgets::BasicTextWithOptions,
17};
18
19/// Displays annotated text and calls `on_click` with the byte offset under the pointer.
20/// Use [`LinkedText`](crate::LinkedText) for URL and custom-action annotations.
21///
22/// # Example
23///
24/// ```rust
25/// use cranpose_ui::{text::AnnotatedString, *};
26///
27/// #[composable]
28/// fn OffsetLabel() {
29///     ClickableText(
30///         AnnotatedString::from("Click a character"),
31///         Modifier::empty(),
32///         TextStyle::default(),
33///         |offset| println!("Byte offset: {offset}"),
34///     );
35/// }
36/// ```
37pub fn ClickableText(
38    text: impl Into<AnnotatedString>,
39    modifier: Modifier,
40    style: TextStyle,
41    on_click: impl Fn(usize) + 'static,
42) -> NodeId {
43    let text = text.into();
44    let text_for_click = text.clone();
45    let style_for_click = style.clone();
46    let options = TextLayoutOptions {
47        overflow: TextOverflow::Clip,
48        soft_wrap: true,
49        max_lines: usize::MAX,
50        min_lines: 1,
51    };
52    // The click finds its offset in the text wrapped as the node draws it,
53    // at the width of the node's content.
54    let size = remember(|| Rc::new(Cell::new(Size::default()))).with(Rc::clone);
55    let clickable_modifier = modifier
56        .report_size(Rc::clone(&size))
57        .clickable(move |point| {
58            on_click(measure::offset_in_drawn_text(
59                &text_for_click,
60                &style_for_click,
61                options,
62                size.get().width,
63                point,
64            ));
65        });
66
67    BasicTextWithOptions(text, clickable_modifier, style, options)
68}
69
70#[cfg(test)]
71#[path = "tests/clickable_text_tests.rs"]
72mod tests;