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
use piet::HitTestPoint;
use unicode_segmentation::UnicodeSegmentation;
use web_sys::CanvasRenderingContext2d;
use super::hit_test_line_position;
pub(crate) fn get_grapheme_boundaries(
ctx: &CanvasRenderingContext2d,
text: &str,
grapheme_position: usize,
) -> Option<GraphemeBoundaries> {
let mut graphemes = UnicodeSegmentation::grapheme_indices(text, true);
let (text_position, _) = graphemes.nth(grapheme_position)?;
let (next_text_position, _) = graphemes.next().unwrap_or_else(|| (text.len(), ""));
let curr_edge = hit_test_line_position(ctx, text, text_position);
let next_edge = hit_test_line_position(ctx, text, next_text_position);
let res = GraphemeBoundaries {
curr_idx: text_position,
next_idx: next_text_position,
leading: curr_edge,
trailing: next_edge,
};
Some(res)
}
pub(crate) fn point_x_in_grapheme(
point_x: f64,
grapheme_boundaries: &GraphemeBoundaries,
) -> Option<HitTestPoint> {
let leading = grapheme_boundaries.leading;
let trailing = grapheme_boundaries.trailing;
let curr_idx = grapheme_boundaries.curr_idx;
let next_idx = grapheme_boundaries.next_idx;
if point_x >= leading && point_x <= trailing {
let midpoint = leading + ((trailing - leading) / 2.0);
let is_inside = true;
let idx = if point_x >= midpoint {
next_idx
} else {
curr_idx
};
Some(HitTestPoint::new(idx, is_inside))
} else {
None
}
}
#[derive(Debug, Default, PartialEq)]
pub(crate) struct GraphemeBoundaries {
pub curr_idx: usize,
pub next_idx: usize,
pub leading: f64,
pub trailing: f64,
}