1use crate::{
2 EditAction, Point, Rect, TextAlignment, TextEdit, TextPosition, VisualTextLine,
3 selection_drag_axis,
4};
5use std::{ops::Range, sync::Arc, time::Duration};
6use unicode_bidi::{BidiInfo, Direction, get_base_direction};
7use unicode_segmentation::UnicodeSegmentation;
8use xrack_runtime::{Node, TextWrap, combo_editable, is_text_input};
9
10#[doc(hidden)]
12pub fn text_editor_viewport(node: &Node, bounds: Rect) -> Rect {
13 use crate::linear::Padding;
14 if is_text_input(node.kind) || combo_editable(node) {
15 return Padding::for_editor(node).inner_rect(bounds);
16 }
17 let inset = node
19 .length("padding")
20 .unwrap_or(Padding::EDITOR_DEFAULT)
21 .max(0.0);
22 let x = inset.min(bounds.width * 0.5);
23 Rect::new(
24 bounds.x + x,
25 bounds.y,
26 bounds.width - 2.0 * x,
27 bounds.height,
28 )
29}
30
31#[doc(hidden)]
32pub fn text_editor_line_bounds(viewport: Rect, line_height: f32) -> Rect {
33 Rect::new(
34 viewport.x,
35 viewport.y + ((viewport.height - line_height) * 0.5).max(0.0),
36 viewport.width,
37 line_height.min(viewport.height),
38 )
39}
40
41#[derive(Clone, Copy, Debug)]
42pub enum TextAreaMotion {
43 Left,
44 Right,
45 WordLeft,
46 WordRight,
47 Up,
48 Down,
49 Home,
50 End,
51 PageUp,
52 PageDown,
53}
54
55impl TextAreaMotion {
56 #[doc(hidden)]
57 pub fn from_word_action(action: EditAction<'_>) -> Option<(Self, bool)> {
58 match action {
59 EditAction::WordLeft(selecting) => Some((Self::WordLeft, selecting)),
60 EditAction::WordRight(selecting) => Some((Self::WordRight, selecting)),
61 _ => None,
62 }
63 }
64
65 pub fn from_navigation(key: crate::NavigationKey, shortcut: bool) -> Option<Self> {
66 use crate::NavigationKey;
67 Some(match key {
68 NavigationKey::Left if !shortcut => Self::Left,
69 NavigationKey::Right if !shortcut => Self::Right,
70 NavigationKey::Home if !shortcut => Self::Home,
71 NavigationKey::End if !shortcut => Self::End,
72 NavigationKey::Up => Self::Up,
73 NavigationKey::Down => Self::Down,
74 NavigationKey::PageUp => Self::PageUp,
75 NavigationKey::PageDown => Self::PageDown,
76 _ => return None,
77 })
78 }
79}
80
81#[derive(Clone)]
83pub struct TextAreaLayout {
84 pub area: Rect,
85 pub line_height: f32,
86 pub lines: Arc<[Range<usize>]>,
87 pub max_scroll: Point,
88 visual: Option<Arc<[VisualTextLine]>>,
89 offsets: Option<Arc<[f32]>>,
90}
91
92pub(crate) fn grapheme_boundaries(text: &str) -> Vec<usize> {
93 text.grapheme_indices(true)
94 .map(|(byte, _)| byte)
95 .chain(std::iter::once(text.len()))
96 .collect()
97}
98
99pub(crate) fn fitting_prefix(
100 start: usize,
101 last: usize,
102 mut fits: impl FnMut(usize) -> bool,
103) -> usize {
104 let mut fit = start;
105 let mut probe = (start + 1).min(last);
106 while probe > fit && fits(probe) {
107 fit = probe;
108 probe = (start + (fit - start).saturating_mul(2)).min(last);
109 }
110 while probe > fit + 1 {
111 let middle = fit + (probe - fit) / 2;
112 if fits(middle) {
113 fit = middle;
114 } else {
115 probe = middle;
116 }
117 }
118 fit
119}
120
121pub(crate) fn paragraphs(text: &str) -> impl Iterator<Item = Range<usize>> {
122 let mut separators = text.match_indices(['\r', '\n']).peekable();
123 let mut start = Some(0);
124 std::iter::from_fn(move || {
125 let begin = start.take()?;
126 let Some((end, separator)) = separators.next() else {
127 return Some(begin..text.len());
128 };
129 let crlf = separator == "\r" && separators.next_if_eq(&(end + 1, "\n")).is_some();
130 start = Some(end + if crlf { 2 } else { 1 });
131 Some(begin..end)
132 })
133}
134
135impl TextAreaLayout {
136 pub fn new(
137 text: &str,
138 area: Rect,
139 line_height: f32,
140 wrap: TextWrap,
141 advance: impl Fn(&str) -> f32,
142 word_break: impl Fn(&str) -> usize,
143 ) -> Self {
144 let lines = Self::wrap_lines(text, area.width, wrap, &advance, word_break, false);
145 let width = lines
146 .iter()
147 .map(|line| advance(&text[line.clone()]))
148 .fold(0.0, f32::max);
149 Self::from_lines(area, line_height, lines, width, None)
150 }
151
152 pub fn shaped(
153 text: &str,
154 area: Rect,
155 line_height: f32,
156 wrap: TextWrap,
157 advance: impl Fn(&str) -> f32,
158 word_break: impl Fn(&str) -> usize,
159 shape: impl Fn(&str) -> VisualTextLine,
160 ) -> Self {
161 let has_bidi = wrap == TextWrap::WordWrap && BidiInfo::new(text, None).has_rtl();
162 let lines = Self::wrap_lines(text, area.width, wrap, &advance, word_break, has_bidi);
163 let visual: Arc<[_]> = lines
164 .iter()
165 .map(|line| shape(&text[line.clone()]))
166 .collect();
167 let width = visual.iter().map(VisualTextLine::width).fold(0.0, f32::max);
168 Self::from_lines(area, line_height, lines, width, Some(visual))
169 }
170
171 fn wrap_lines(
172 text: &str,
173 width: f32,
174 wrap: TextWrap,
175 advance: impl Fn(&str) -> f32,
176 word_break: impl Fn(&str) -> usize,
177 has_bidi: bool,
178 ) -> Vec<Range<usize>> {
179 let mut lines = Vec::new();
180 let mut paragraph = |range: Range<usize>| {
181 let content = &text[range.clone()];
182 if content.is_empty() || wrap == TextWrap::NoWrap || width <= 0.0 {
183 lines.push(range);
184 return;
185 }
186 let breaks = grapheme_boundaries(content);
187 let mut start = 0;
188 while start < breaks.len() - 1 {
189 let next = match wrap {
190 TextWrap::CharWrap => fitting_prefix(start, breaks.len() - 1, |index| {
191 advance(&content[breaks[start]..breaks[index]]) <= width
192 })
193 .max(start + 1),
194 TextWrap::WordWrap => {
195 let tail = &content[breaks[start]..];
196 let prefix = if has_bidi {
197 logical_word_prefix(tail, width, &advance)
198 } else {
199 word_break(tail)
200 };
201 if prefix == 0 && has_bidi {
202 fitting_prefix(start, breaks.len() - 1, |index| {
203 advance(&content[breaks[start]..breaks[index]]) <= width
204 })
205 .max(start + 1)
206 } else {
207 let end = breaks[start].saturating_add(prefix);
208 breaks
209 .partition_point(|&byte| byte <= end)
210 .saturating_sub(1)
211 .max(start + 1)
212 }
213 }
214 TextWrap::NoWrap => unreachable!(),
215 };
216 lines.push(range.start + breaks[start]..range.start + breaks[next]);
217 start = next;
218 }
219 };
220 for range in paragraphs(text) {
221 paragraph(range);
222 }
223 lines
224 }
225
226 fn from_lines(
227 area: Rect,
228 line_height: f32,
229 lines: Vec<Range<usize>>,
230 width: f32,
231 visual: Option<Arc<[VisualTextLine]>>,
232 ) -> Self {
233 let max_scroll = Point {
234 x: (width + 1.0 - area.width).max(0.0),
235 y: (lines.len() as f32 * line_height - area.height).max(0.0),
236 };
237 Self {
238 area,
239 line_height,
240 lines: lines.into(),
241 max_scroll,
242 visual,
243 offsets: None,
244 }
245 }
246
247 pub fn aligned(
248 mut self,
249 text: &str,
250 alignment: TextAlignment,
251 advance: impl Fn(&str) -> f32,
252 ) -> Self {
253 self.offsets = alignment.has_offset().then(|| {
254 self.lines
255 .iter()
256 .enumerate()
257 .map(|(index, line)| {
258 let value = &text[line.clone()];
259 let (width, rtl) = self.visual_line(index).map_or_else(
260 || (advance(value), get_base_direction(value) == Direction::Rtl),
261 |line| (line.width(), line.is_rtl()),
262 );
263 alignment.offset((self.area.width - width - 1.0).max(0.0), rtl)
264 })
265 .collect()
266 });
267 self
268 }
269
270 pub fn line_offset(&self, index: usize) -> f32 {
271 self.offsets.as_ref().map_or(0.0, |offsets| offsets[index])
272 }
273
274 pub fn visual_line(&self, index: usize) -> Option<&VisualTextLine> {
275 self.visual.as_ref()?.get(index)
276 }
277
278 pub fn with_viewport(mut self, area: Rect) -> Self {
279 debug_assert_eq!(area.width, self.area.width);
280 self.area = area;
281 self.max_scroll.y = (self.lines.len() as f32 * self.line_height - area.height).max(0.0);
282 self
283 }
284
285 pub fn clamp_scroll(&self, scroll: Point) -> Point {
286 Point {
287 x: scroll.x.clamp(0.0, self.max_scroll.x),
288 y: scroll.y.clamp(0.0, self.max_scroll.y),
289 }
290 }
291
292 #[doc(hidden)]
294 pub fn selection_drag(
295 &self,
296 point: Point,
297 scroll: Point,
298 elapsed: Duration,
299 ) -> (Point, Point, bool) {
300 let (x, scroll_x, horizontal) = selection_drag_axis(
301 point.x,
302 self.area.x,
303 self.area.width,
304 scroll.x,
305 self.max_scroll.x,
306 elapsed,
307 );
308 let (y, scroll_y, vertical) = selection_drag_axis(
309 point.y,
310 self.area.y,
311 self.area.height,
312 scroll.y,
313 self.max_scroll.y,
314 elapsed,
315 );
316 (
317 Point { x, y },
318 Point {
319 x: scroll_x,
320 y: scroll_y,
321 },
322 horizontal || vertical,
323 )
324 }
325
326 pub fn keep_visible(&self, scroll: Point, caret: Point) -> Point {
327 self.clamp_scroll(Point {
328 x: scroll.x.max(caret.x + 1.0 - self.area.width).min(caret.x),
329 y: scroll
330 .y
331 .max(caret.y + self.line_height - self.area.height)
332 .min(caret.y),
333 })
334 }
335
336 pub fn visible_lines(&self, scroll: Point) -> Range<usize> {
337 let top = (scroll.y / self.line_height).floor() as usize;
338 let bottom = ((scroll.y + self.area.height) / self.line_height).ceil() as usize;
339 top.min(self.lines.len())..bottom.min(self.lines.len())
340 }
341
342 pub fn line_index(&self, position: TextPosition) -> usize {
343 let line = self
344 .lines
345 .partition_point(|line| line.start <= position.offset)
346 .saturating_sub(1);
347 if position.trailing && line > 0 && self.lines[line - 1].end == position.offset {
348 line - 1
349 } else {
350 line
351 }
352 }
353
354 pub fn caret_point(
355 &self,
356 text: &str,
357 position: TextPosition,
358 advance: impl Fn(&str) -> f32,
359 ) -> Point {
360 let line = self.line_index(position);
361 let range = &self.lines[line];
362 let end = position.offset.clamp(range.start, range.end);
363 Point {
364 x: self.line_offset(line)
365 + self.visual_line(line).map_or_else(
366 || advance(&text[range.start..end]),
367 |visual| {
368 visual.caret_x(TextPosition {
369 offset: end - range.start,
370 trailing: position.trailing,
371 })
372 },
373 ),
374 y: line as f32 * self.line_height,
375 }
376 }
377
378 fn position_on_line(
379 &self,
380 text: &str,
381 line: usize,
382 x: f32,
383 advance: impl Fn(&str) -> f32,
384 ) -> TextPosition {
385 let range = &self.lines[line];
386 let x = x - self.line_offset(line);
387 if let Some(visual) = self.visual_line(line) {
388 return line_offset(visual.hit(x), range.start);
389 }
390 let content = &text[range.clone()];
391 let breaks = grapheme_boundaries(content);
392 let after = breaks.partition_point(|&byte| advance(&content[..byte]) < x);
393 let right = breaks[after.min(breaks.len() - 1)];
394 let left = breaks[after.saturating_sub(1).min(breaks.len() - 1)];
395 let offset = if x - advance(&content[..left]) <= advance(&content[..right]) - x {
396 left
397 } else {
398 right
399 };
400 TextPosition {
401 offset: range.start + offset,
402 trailing: offset != 0 && offset == content.len(),
403 }
404 }
405
406 pub fn hit(
407 &self,
408 text: &str,
409 point: Point,
410 scroll: Point,
411 advance: impl Fn(&str) -> f32,
412 ) -> TextPosition {
413 let line = ((point.y - self.area.y + scroll.y) / self.line_height).floor() as usize;
414 self.position_on_line(
415 text,
416 line.min(self.lines.len() - 1),
417 point.x - self.area.x + scroll.x,
418 advance,
419 )
420 }
421
422 pub fn move_caret(
423 &self,
424 text: &str,
425 editor: &mut TextEdit,
426 motion: TextAreaMotion,
427 selecting: bool,
428 advance: impl Fn(&str) -> f32,
429 ) {
430 let caret = editor.position(text);
431 let line = self.line_index(caret);
432 let range = &self.lines[line];
433 match motion {
434 TextAreaMotion::Left
435 | TextAreaMotion::Right
436 | TextAreaMotion::WordLeft
437 | TextAreaMotion::WordRight => {
438 let right = matches!(motion, TextAreaMotion::Right | TextAreaMotion::WordRight);
439 let word = matches!(motion, TextAreaMotion::WordLeft | TextAreaMotion::WordRight);
440 let fallback = match (word, right) {
441 (true, true) => EditAction::WordRight(selecting),
442 (true, false) => EditAction::WordLeft(selecting),
443 (false, true) => EditAction::Right(selecting),
444 (false, false) => EditAction::Left(selecting),
445 };
446 let Some(visual) = self
447 .visual_line(line)
448 .filter(|visual| !word || visual.graphemes().iter().any(|cell| cell.rtl))
449 else {
450 editor.apply_multiline(text, fallback);
451 return;
452 };
453 let selection = editor.selection(text);
454 if !selecting && !selection.is_empty() {
455 let edge = if right {
456 selection.end
457 } else {
458 selection.start
459 };
460 let selected_line = self.line_index(TextPosition {
461 offset: edge,
462 trailing: right,
463 });
464 let start = self.lines[selected_line].start;
465 let bytes =
466 selection.start.saturating_sub(start)..selection.end.saturating_sub(start);
467 if let Some(position) = self
468 .visual_line(selected_line)
469 .and_then(|visual| visual.selection_edge(bytes, right))
470 {
471 editor.place_caret(text, line_offset(position, start), false);
472 return;
473 }
474 }
475 let local = TextPosition {
476 offset: caret.offset - range.start,
477 trailing: caret.trailing,
478 };
479 let step = |visual: &VisualTextLine, position, range: &Range<usize>| {
480 if word {
481 visual.word_step(&text[range.clone()], position, right)
482 } else {
483 visual.step(position, right)
484 }
485 };
486 let position = step(visual, local, range)
487 .map(|position| line_offset(position, range.start))
488 .or_else(|| {
489 let next = if right != visual.is_rtl() {
490 line.checked_add(1)
491 } else {
492 line.checked_sub(1)
493 }?;
494 let next_visual = self.visual_line(next)?;
495 let edge = next_visual.edge(!right);
496 let position = if word {
497 step(next_visual, edge, &self.lines[next]).unwrap_or(edge)
498 } else {
499 edge
500 };
501 Some(line_offset(position, self.lines[next].start))
502 });
503 if let Some(position) = position {
504 editor.place_caret(text, position, selecting);
505 }
506 }
507 TextAreaMotion::Home | TextAreaMotion::End => {
508 let end = matches!(motion, TextAreaMotion::End);
509 let position = self.visual_line(line).map_or(
510 TextPosition {
511 offset: if end { range.end } else { range.start },
512 trailing: end,
513 },
514 |visual| line_offset(visual.edge(end != visual.is_rtl()), range.start),
515 );
516 editor.place_caret(text, position, selecting);
517 }
518 _ => {
519 let page = (self.area.height / self.line_height).floor().max(1.0) as usize;
520 let next = match motion {
521 TextAreaMotion::Up => line.saturating_sub(1),
522 TextAreaMotion::Down => (line + 1).min(self.lines.len() - 1),
523 TextAreaMotion::PageUp => line.saturating_sub(page),
524 TextAreaMotion::PageDown => (line + page).min(self.lines.len() - 1),
525 TextAreaMotion::Home
526 | TextAreaMotion::End
527 | TextAreaMotion::Left
528 | TextAreaMotion::Right
529 | TextAreaMotion::WordLeft
530 | TextAreaMotion::WordRight => unreachable!(),
531 };
532 let x = editor
533 .preferred_x()
534 .unwrap_or_else(|| self.caret_point(text, caret, &advance).x);
535 let position = self.position_on_line(text, next, x, advance);
536 editor.place_caret(text, position, selecting);
537 editor.set_preferred_x(x);
538 }
539 }
540 }
541}
542
543fn line_offset(mut position: TextPosition, start: usize) -> TextPosition {
544 position.offset += start;
545 position
546}
547
548fn logical_word_prefix(text: &str, width: f32, advance: impl Fn(&str) -> f32) -> usize {
549 text.split_word_bound_indices()
550 .map(|(index, word)| index + word.len())
551 .take_while(|&end| advance(&text[..end]) <= width)
552 .last()
553 .unwrap_or(0)
554}
555
556#[cfg(test)]
557mod tests {
558 use super::*;
559
560 fn advance(text: &str) -> f32 {
561 text.graphemes(true).count() as f32
562 }
563
564 #[test]
565 fn edge_drag_clamps_the_hit_and_scrolls_only_while_there_is_overflow() {
566 let geometry = TextAreaLayout::new(
567 "abcdefghijklmnopqrst\nsecond line\nthird line",
568 Rect::new(10.0, 20.0, 8.0, 12.0),
569 10.0,
570 TextWrap::NoWrap,
571 advance,
572 str::len,
573 );
574 let outside = Point { x: 30.0, y: 70.0 };
575 let (edge, offset, pending) =
576 geometry.selection_drag(outside, Point::default(), Duration::ZERO);
577 assert!(geometry.area.contains(edge));
578 assert_eq!(offset, Point::default());
579 assert!(pending);
580 let (_, offset, _) = geometry.selection_drag(outside, offset, Duration::from_millis(16));
581 assert!(offset.x > 0.0 && offset.y > offset.x);
582 let (_, end, pending) = geometry.selection_drag(outside, offset, Duration::from_secs(1));
583 assert_eq!(end, geometry.max_scroll);
584 assert!(!pending);
585 let (_, unchanged, pending) =
586 geometry.selection_drag(Point { x: 12.0, y: 24.0 }, end, Duration::from_millis(16));
587 assert_eq!(unchanged, end);
588 assert!(!pending);
589 let (_, start, pending) =
590 geometry.selection_drag(Point::default(), end, Duration::from_secs(1));
591 assert_eq!(start, Point::default());
592 assert!(!pending);
593 }
594
595 #[test]
596 fn wrapping_preserves_graphemes_empty_lines_and_soft_wrap_affinity() {
597 let text = "ab👩🚀c\r\n\n末\n";
598 let layout = TextAreaLayout::new(
599 text,
600 Rect::new(0.0, 0.0, 2.0, 20.0),
601 10.0,
602 TextWrap::CharWrap,
603 advance,
604 str::len,
605 );
606 assert_eq!(
607 layout
608 .lines
609 .iter()
610 .map(|range| &text[range.clone()])
611 .collect::<Vec<_>>(),
612 ["ab", "👩🚀c", "", "末", ""]
613 );
614 let upstream = layout.hit(text, Point { x: 2.0, y: 1.0 }, Point::default(), advance);
615 let downstream = layout.hit(text, Point { x: 0.0, y: 11.0 }, Point::default(), advance);
616 assert_eq!(upstream.offset, downstream.offset);
617 assert!(upstream.trailing);
618 assert!(!downstream.trailing);
619 assert_eq!(
620 layout.caret_point(text, upstream, advance),
621 Point { x: 2.0, y: 0.0 }
622 );
623 assert_eq!(
624 layout.caret_point(text, downstream, advance),
625 Point { x: 0.0, y: 10.0 }
626 );
627 assert_eq!(layout.visible_lines(Point { x: 0.0, y: 25.0 }), 2..5);
628 }
629
630 #[test]
631 fn vertical_selection_keeps_the_preferred_column_through_short_lines() {
632 let text = "abcdefghij\nx\nabcdefghij";
633 let layout = TextAreaLayout::new(
634 text,
635 Rect::new(0.0, 0.0, 100.0, 20.0),
636 10.0,
637 TextWrap::NoWrap,
638 advance,
639 str::len,
640 );
641 let mut editor = TextEdit::default();
642 editor.place_caret(
643 text,
644 TextPosition {
645 offset: 7,
646 trailing: false,
647 },
648 false,
649 );
650 layout.move_caret(text, &mut editor, TextAreaMotion::Down, true, advance);
651 assert_eq!(editor.caret(text), 12);
652 layout.move_caret(text, &mut editor, TextAreaMotion::Down, true, advance);
653 assert_eq!(editor.selection(text), 7..20);
654 let caret = layout.caret_point(text, editor.position(text), advance);
655 assert_eq!(layout.keep_visible(Point::default(), caret).y, 10.0);
656 assert_eq!(
657 editor.apply_multiline(text, EditAction::Insert("甲\r\n乙")),
658 Some("abcdefg甲\n乙hij".into())
659 );
660 assert_eq!(
661 TextEdit::default().apply("", EditAction::Insert("甲\r\n乙")),
662 Some("甲乙".into())
663 );
664 }
665}