tessera-ui-basic-components 2.7.0

Basic components for tessera-ui
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! Core module for text editing logic and state management in Tessera UI.
//!
//! This module provides the foundational structures and functions for building text editing components,
//! including text buffer management, selection and cursor handling, rendering logic, and keyboard event mapping.
//! It is designed to be shared across UI components via the `TextEditorStateHandle` wrapper,
//! enabling consistent and thread-safe access to editor state.
//! and efficient text editing experiences.
//!
//! Typical use cases include single-line and multi-line text editors, input fields, and any UI element
//! requiring advanced text manipulation, selection, and IME support.
//!
//! The module integrates with the Tessera component system and rendering pipelines, supporting selection
//! highlighting, cursor blinking, clipboard operations, and extensible keyboard shortcuts.
//!
//! Most applications should interact with [`TextEditorState`] for state management and [`text_edit_core()`]
//! for rendering and layout within a component tree.

mod cursor;

use std::{sync::Arc, time::Instant};

use glyphon::{
    Cursor, Edit,
    cosmic_text::{self, Selection},
};
use parking_lot::RwLock;
use tessera_ui::{
    Clipboard, Color, ComputedData, DimensionValue, Dp, Px, PxPosition, focus_state::Focus,
    tessera, winit,
};
use winit::keyboard::NamedKey;

use crate::{
    pipelines::{TextCommand, TextConstraint, TextData, write_font_system},
    selection_highlight_rect::selection_highlight_rect,
    text_edit_core::cursor::CURSOR_WIDRH,
};

/// Definition of a rectangular selection highlight
#[derive(Clone, Debug)]
/// Defines a rectangular region for text selection highlighting.
///
/// Used internally to represent the geometry of a selection highlight in pixel coordinates.
pub struct RectDef {
    /// The x-coordinate (in pixels) of the rectangle's top-left corner.
    pub x: Px,
    /// The y-coordinate (in pixels) of the rectangle's top-left corner.
    pub y: Px,
    /// The width (in pixels) of the rectangle.
    pub width: Px,
    /// The height (in pixels) of the rectangle.
    pub height: Px,
}

/// Types of mouse clicks
#[derive(Debug, Clone, Copy, PartialEq)]
/// Represents the type of mouse click detected in the editor.
///
/// Used for distinguishing between single, double, and triple click actions.
pub enum ClickType {
    /// A single mouse click.
    Single,
    /// A double mouse click.
    Double,
    /// A triple mouse click.
    Triple,
}

/// Core text editing state, shared between components
/// Core state for text editing, including content, selection, cursor, and interaction state.
///
/// This struct manages the text buffer, selection, cursor position, focus, and user interaction state.
/// It is designed to be shared between UI components via a `TextEditorStateHandle`.
pub struct TextEditorStateInner {
    line_height: Px,
    pub(crate) editor: glyphon::Editor<'static>,
    blink_timer: Instant,
    focus_handler: Focus,
    pub(crate) selection_color: Color,
    pub(crate) current_selection_rects: Vec<RectDef>,
    // Click tracking for double/triple click detection
    last_click_time: Option<Instant>,
    last_click_position: Option<PxPosition>,
    click_count: u32,
    is_dragging: bool,
    // For IME
    pub(crate) preedit_string: Option<String>,
}

/// Thin handle wrapping an internal `Arc<RwLock<TextEditorState>>` and exposing `read()`/`write()`.
#[derive(Clone)]
pub struct TextEditorState {
    inner: Arc<RwLock<TextEditorStateInner>>,
}

impl TextEditorState {
    pub fn new(size: Dp, line_height: Option<Dp>) -> Self {
        Self {
            inner: Arc::new(RwLock::new(TextEditorStateInner::new(size, line_height))),
        }
    }

    pub fn read(&self) -> parking_lot::RwLockReadGuard<'_, TextEditorStateInner> {
        self.inner.read()
    }

    pub fn write(&self) -> parking_lot::RwLockWriteGuard<'_, TextEditorStateInner> {
        self.inner.write()
    }
}

impl TextEditorStateInner {
    /// Creates a new `TextEditorState` with the given font size and optional line height.
    ///
    /// # Arguments
    ///
    /// * `size` - Font size in Dp.
    /// * `line_height` - Optional line height in Dp. If `None`, uses 1.2x the font size.
    pub fn new(size: Dp, line_height: Option<Dp>) -> Self {
        Self::with_selection_color(size, line_height, Color::new(0.5, 0.7, 1.0, 0.4))
    }

    /// Creates a new `TextEditorState` with a custom selection highlight color.
    ///
    /// # Arguments
    ///
    /// * `size` - Font size in Dp.
    /// * `line_height` - Optional line height in Dp.
    /// * `selection_color` - Color used for selection highlight.
    pub fn with_selection_color(size: Dp, line_height: Option<Dp>, selection_color: Color) -> Self {
        let final_line_height = line_height.unwrap_or(Dp(size.0 * 1.2));
        let line_height_px: Px = final_line_height.into();
        let mut buffer = glyphon::Buffer::new(
            &mut write_font_system(),
            glyphon::Metrics::new(size.to_pixels_f32(), line_height_px.to_f32()),
        );
        buffer.set_wrap(&mut write_font_system(), glyphon::Wrap::Glyph);
        let editor = glyphon::Editor::new(buffer);
        Self {
            line_height: line_height_px,
            editor,
            blink_timer: Instant::now(),
            focus_handler: Focus::new(),
            selection_color,
            current_selection_rects: Vec::new(),
            last_click_time: None,
            last_click_position: None,
            click_count: 0,
            is_dragging: false,
            preedit_string: None,
        }
    }

    /// Returns the line height in pixels.
    pub fn line_height(&self) -> Px {
        self.line_height
    }

    /// Returns the current text buffer as `TextData`, applying the given layout constraints.
    ///
    /// # Arguments
    ///
    /// * `constraint` - Layout constraints for text rendering.
    pub fn text_data(&mut self, constraint: TextConstraint) -> TextData {
        self.editor.with_buffer_mut(|buffer| {
            buffer.set_size(
                &mut write_font_system(),
                constraint.max_width,
                constraint.max_height,
            );
            buffer.shape_until_scroll(&mut write_font_system(), false);
        });

        let text_buffer = match self.editor.buffer_ref() {
            glyphon::cosmic_text::BufferRef::Owned(buffer) => buffer.clone(),
            glyphon::cosmic_text::BufferRef::Borrowed(buffer) => (**buffer).to_owned(),
            glyphon::cosmic_text::BufferRef::Arc(buffer) => (**buffer).clone(),
        };

        TextData::from_buffer(text_buffer)
    }

    /// Returns a reference to the internal focus handler.
    pub fn focus_handler(&self) -> &Focus {
        &self.focus_handler
    }

    /// Returns a mutable reference to the internal focus handler.
    pub fn focus_handler_mut(&mut self) -> &mut Focus {
        &mut self.focus_handler
    }

    /// Returns a reference to the underlying `glyphon::Editor`.
    pub fn editor(&self) -> &glyphon::Editor<'static> {
        &self.editor
    }

    /// Returns a mutable reference to the underlying `glyphon::Editor`.
    pub fn editor_mut(&mut self) -> &mut glyphon::Editor<'static> {
        &mut self.editor
    }

    /// Returns the current blink timer instant (for cursor blinking).
    pub fn blink_timer(&self) -> Instant {
        self.blink_timer
    }

    /// Resets the blink timer to the current instant.
    pub fn update_blink_timer(&mut self) {
        self.blink_timer = Instant::now();
    }

    /// Returns the current selection highlight color.
    pub fn selection_color(&self) -> Color {
        self.selection_color
    }

    /// Returns a reference to the current selection rectangles.
    pub fn current_selection_rects(&self) -> &Vec<RectDef> {
        &self.current_selection_rects
    }

    /// Sets the selection highlight color.
    ///
    /// # Arguments
    ///
    /// * `color` - The new selection color.
    pub fn set_selection_color(&mut self, color: Color) {
        self.selection_color = color;
    }

    /// Handles a mouse click event and determines the click type (single, double, triple).
    ///
    /// Used for text selection and word/line selection logic.
    ///
    /// # Arguments
    ///
    /// * `position` - The position of the click in pixels.
    /// * `timestamp` - The time the click occurred.
    ///
    /// # Returns
    ///
    /// The detected ClickType.
    pub fn handle_click(&mut self, position: PxPosition, timestamp: Instant) -> ClickType {
        const DOUBLE_CLICK_TIME_MS: u128 = 500; // 500ms for double click
        const CLICK_DISTANCE_THRESHOLD: Px = Px(5); // 5 pixels tolerance for position

        let click_type = if let (Some(last_time), Some(last_pos)) =
            (self.last_click_time, self.last_click_position)
        {
            let time_diff = timestamp.duration_since(last_time).as_millis();
            let distance = (position.x - last_pos.x).abs() + (position.y - last_pos.y).abs();

            if time_diff <= DOUBLE_CLICK_TIME_MS && distance <= CLICK_DISTANCE_THRESHOLD.abs() {
                self.click_count += 1;
                match self.click_count {
                    2 => ClickType::Double,
                    3 => {
                        self.click_count = 0; // Reset after triple click
                        ClickType::Triple
                    }
                    _ => ClickType::Single,
                }
            } else {
                self.click_count = 1;
                ClickType::Single
            }
        } else {
            self.click_count = 1;
            ClickType::Single
        };

        self.last_click_time = Some(timestamp);
        self.last_click_position = Some(position);
        self.is_dragging = false;

        click_type
    }

    /// Starts a drag operation (for text selection).
    pub fn start_drag(&mut self) {
        self.is_dragging = true;
    }

    /// Returns `true` if a drag operation is in progress.
    pub fn is_dragging(&self) -> bool {
        self.is_dragging
    }

    /// Stops the current drag operation.
    pub fn stop_drag(&mut self) {
        self.is_dragging = false;
    }

    /// Returns the last click position, if any.
    pub fn last_click_position(&self) -> Option<PxPosition> {
        self.last_click_position
    }

    /// Updates the last click position (used for drag tracking).
    ///
    /// # Arguments
    ///
    /// * `position` - The new last click position.
    pub fn update_last_click_position(&mut self, position: PxPosition) {
        self.last_click_position = Some(position);
    }

    /// Map keyboard events to text editing actions
    /// Maps a keyboard event to a list of text editing actions for the editor.
    ///
    /// This function translates keyboard input (including modifiers) into editing actions
    /// such as character insertion, deletion, navigation, and clipboard operations.
    ///
    /// # Arguments
    ///
    /// * `key_event` - The keyboard event to map.
    /// * `key_modifiers` - The current keyboard modifier state.
    /// * `clipboard` - Mutable reference to the clipboard for clipboard operations.
    ///
    /// # Returns
    ///
    /// An optional vector of `glyphon::Action` to be applied to the editor.
    pub fn map_key_event_to_action(
        &mut self,
        key_event: winit::event::KeyEvent,
        key_modifiers: winit::keyboard::ModifiersState,
        clipboard: &mut Clipboard,
    ) -> Option<Vec<glyphon::Action>> {
        let editor = &mut self.editor;

        match key_event.state {
            winit::event::ElementState::Pressed => {}
            winit::event::ElementState::Released => return None,
        }

        match key_event.logical_key {
            winit::keyboard::Key::Named(named_key) => match named_key {
                NamedKey::Backspace => Some(vec![glyphon::Action::Backspace]),
                NamedKey::Delete => Some(vec![glyphon::Action::Delete]),
                NamedKey::Enter => Some(vec![glyphon::Action::Enter]),
                NamedKey::Escape => Some(vec![glyphon::Action::Escape]),
                NamedKey::Tab => Some(vec![glyphon::Action::Insert(' '); 4]),
                NamedKey::ArrowLeft => {
                    if key_modifiers.control_key() {
                        editor.set_selection(Selection::None);

                        Some(vec![glyphon::Action::Motion(cosmic_text::Motion::LeftWord)])
                    } else {
                        // if we have selected text, we need to clear it and not perform any action
                        if editor.selection_bounds().is_some() {
                            editor.set_selection(Selection::None);

                            return None;
                        }

                        Some(vec![glyphon::Action::Motion(cosmic_text::Motion::Left)])
                    }
                }
                NamedKey::ArrowRight => {
                    if key_modifiers.control_key() {
                        editor.set_selection(Selection::None);

                        Some(vec![glyphon::Action::Motion(
                            cosmic_text::Motion::RightWord,
                        )])
                    } else {
                        if editor.selection_bounds().is_some() {
                            editor.set_selection(Selection::None);

                            return None;
                        }

                        Some(vec![glyphon::Action::Motion(cosmic_text::Motion::Right)])
                    }
                }
                NamedKey::ArrowUp => {
                    // if we are on the first line, we move the cursor to the beginning of the line
                    if editor.cursor().line == 0 {
                        editor.set_cursor(Cursor::new(0, 0));

                        return None;
                    }

                    Some(vec![glyphon::Action::Motion(cosmic_text::Motion::Up)])
                }
                NamedKey::ArrowDown => {
                    let last_line_index =
                        editor.with_buffer(|buffer| buffer.lines.len().saturating_sub(1));

                    // if we are on the last line, we move the cursor to the end of the line
                    if editor.cursor().line >= last_line_index {
                        let last_col =
                            editor.with_buffer(|buffer| buffer.lines[last_line_index].text().len());

                        editor.set_cursor(Cursor::new(last_line_index, last_col));
                        return None;
                    }

                    Some(vec![glyphon::Action::Motion(cosmic_text::Motion::Down)])
                }
                NamedKey::Home => Some(vec![glyphon::Action::Motion(cosmic_text::Motion::Home)]),
                NamedKey::End => Some(vec![glyphon::Action::Motion(cosmic_text::Motion::End)]),
                NamedKey::Space => Some(vec![glyphon::Action::Insert(' ')]),
                _ => None,
            },

            winit::keyboard::Key::Character(s) => {
                let is_ctrl = key_modifiers.control_key() || key_modifiers.super_key();
                if is_ctrl {
                    match s.to_lowercase().as_str() {
                        "c" => {
                            if let Some(text) = editor.copy_selection() {
                                clipboard.set_text(&text);
                            }
                            return None;
                        }
                        "v" => {
                            if let Some(text) = clipboard.get_text() {
                                return Some(text.chars().map(glyphon::Action::Insert).collect());
                            }

                            return None;
                        }
                        "x" => {
                            if let Some(text) = editor.copy_selection() {
                                clipboard.set_text(&text);
                                // Use Backspace action to delete selection
                                return Some(vec![glyphon::Action::Backspace]);
                            }
                            return None;
                        }
                        _ => {}
                    }
                }
                Some(s.chars().map(glyphon::Action::Insert).collect::<Vec<_>>())
            }
            _ => None,
        }
    }
}

/// Compute selection rectangles for the given editor.
fn compute_selection_rects(editor: &glyphon::Editor) -> Vec<RectDef> {
    let mut selection_rects: Vec<RectDef> = Vec::new();
    let (selection_start, selection_end) = editor.selection_bounds().unwrap_or_default();

    editor.with_buffer(|buffer| {
        for run in buffer.layout_runs() {
            let line_top = Px(run.line_top as i32);
            let line_height = Px(run.line_height as i32);

            if let Some((x, w)) = run.highlight(selection_start, selection_end) {
                selection_rects.push(RectDef {
                    x: Px(x as i32),
                    y: line_top,
                    width: Px(w as i32),
                    height: line_height,
                });
            }
        }
    });

    selection_rects
}

/// Clip rects to visible area and drop those fully outside.
fn clip_and_take_visible(rects: Vec<RectDef>, visible_x1: Px, visible_y1: Px) -> Vec<RectDef> {
    let visible_x0 = Px(0);
    let visible_y0 = Px(0);

    rects
        .into_iter()
        .filter_map(|mut rect| {
            let rect_x1 = rect.x + rect.width;
            let rect_y1 = rect.y + rect.height;
            if rect_x1 <= visible_x0
                || rect.y >= visible_y1
                || rect.x >= visible_x1
                || rect_y1 <= visible_y0
            {
                None
            } else {
                let new_x = rect.x.max(visible_x0);
                let new_y = rect.y.max(visible_y0);
                let new_x1 = rect_x1.min(visible_x1);
                let new_y1 = rect_y1.min(visible_y1);
                rect.x = new_x;
                rect.y = new_y;
                rect.width = (new_x1 - new_x).max(Px(0));
                rect.height = (new_y1 - new_y).max(Px(0));
                Some(rect)
            }
        })
        .collect()
}

/// Core text editing component for rendering text, selection, and cursor.
///
/// This component is responsible for rendering the text buffer, selection highlights, and cursor.
/// It does not handle user events directly; instead, it is intended to be used inside a container
/// that manages user interaction and passes state updates via `TextEditorState`.
///
/// # Arguments
///
/// * `state` - Shared state for the text editor, typically wrapped in `Arc<RwLock<...>>`.
#[tessera]
pub fn text_edit_core(state: TextEditorState) {
    // text rendering with constraints from parent container
    {
        let state_clone = state.clone();
        measure(Box::new(move |input| {
            // Enable clipping for clip to visible area
            input.enable_clipping();

            // surface provides constraints that should be respected for text layout
            let max_width_pixels: Option<Px> = match input.parent_constraint.width {
                DimensionValue::Fixed(w) => Some(w),
                DimensionValue::Wrap { max, .. } => max,
                DimensionValue::Fill { max, .. } => max,
            };

            // For proper scrolling behavior, we need to respect height constraints
            // When max height is specified, content should be clipped and scrollable
            let max_height_pixels: Option<Px> = match input.parent_constraint.height {
                DimensionValue::Fixed(h) => Some(h), // Respect explicit fixed heights
                DimensionValue::Wrap { max, .. } => max, // Respect max height for wrapping
                DimensionValue::Fill { max, .. } => max,
            };

            let text_data = state_clone.write().text_data(TextConstraint {
                max_width: max_width_pixels.map(|px| px.to_f32()),
                max_height: max_height_pixels.map(|px| px.to_f32()),
            });

            // Simplified selection rectangle computation using helper functions to reduce complexity.
            let mut selection_rects = compute_selection_rects(state_clone.read().editor());

            // Record length before moving (used to place cursor node after rects)
            let selection_rects_len = selection_rects.len();

            // Handle selection rectangle positioning
            for (i, rect_def) in selection_rects.iter().enumerate() {
                if let Some(rect_node_id) = input.children_ids.get(i).copied() {
                    input.measure_child(rect_node_id, input.parent_constraint)?;
                    input.place_child(rect_node_id, PxPosition::new(rect_def.x, rect_def.y));
                }
            }

            // Clip to visible area and write filtered rects to state
            let visible_x1 = max_width_pixels.unwrap_or(Px(i32::MAX));
            let visible_y1 = max_height_pixels.unwrap_or(Px(i32::MAX));
            selection_rects = clip_and_take_visible(selection_rects, visible_x1, visible_y1);
            state_clone.write().current_selection_rects = selection_rects;

            // Handle cursor positioning (cursor comes after selection rects)
            if let Some(cursor_pos_raw) = state_clone.read().editor().cursor_position() {
                let cursor_pos = PxPosition::new(Px(cursor_pos_raw.0), Px(cursor_pos_raw.1));
                let cursor_node_index = selection_rects_len;
                if let Some(cursor_node_id) = input.children_ids.get(cursor_node_index).copied() {
                    input.measure_child(cursor_node_id, input.parent_constraint)?;
                    input.place_child(cursor_node_id, cursor_pos);
                }
            }

            let drawable = TextCommand {
                data: text_data.clone(),
            };
            input.metadata_mut().push_draw_command(drawable);

            // Return constrained size - respect maximum height to prevent overflow
            let constrained_height = if let Some(max_h) = max_height_pixels {
                text_data.size[1].min(max_h.abs())
            } else {
                text_data.size[1]
            };

            Ok(ComputedData {
                width: Px::from(text_data.size[0]) + CURSOR_WIDRH.to_px(), // Add padding for cursor
                height: constrained_height.into(),
            })
        }));
    }

    // Selection highlighting
    {
        let (rect_definitions, color_for_selection) = {
            let guard = state.read();
            (guard.current_selection_rects.clone(), guard.selection_color)
        };

        for def in rect_definitions {
            selection_highlight_rect(def.width, def.height, color_for_selection);
        }
    }

    // Cursor rendering (only when focused)
    if state.read().focus_handler().is_focused() {
        cursor::cursor(state.read().line_height(), state.read().blink_timer());
    }
}