tessera-components 0.0.0

Basic components for tessera-ui, using md3e design principles.
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
//! A multi-line text editor component.
//!
//! ## Usage
//!
//! Use for text input fields, forms, or any place that requires editable text.
use std::sync::Arc;

use derive_setters::Setters;
use glyphon::{Action as GlyphonAction, Edit};
use tessera_ui::{
    Color, CursorEventContent, Dp, ImeRequest, Modifier, Px, PxPosition, State, accesskit::Role,
    remember, tessera, use_context, winit,
};

use crate::{
    modifier::ModifierExt,
    pipelines::text::pipeline::write_font_system,
    pos_misc::is_position_in_component,
    shape_def::{RoundedCorner, Shape},
    surface::{SurfaceArgs, surface},
    text_edit_core::{ClickType, text_edit_core},
    theme::MaterialTheme,
};

/// State structure for the text editor, managing text content, cursor,
/// selection, and editing logic.
pub use crate::text_edit_core::TextEditorController;

/// Arguments for configuring the [`text_editor`] component.
#[derive(Clone, Setters)]
pub struct TextEditorArgs {
    /// Optional modifier chain applied to the editor container.
    pub modifier: Modifier,
    /// Called when the text content changes. The closure receives the new text
    /// content and returns the updated content.
    #[setters(skip)]
    pub on_change: Arc<dyn Fn(String) -> String + Send + Sync>,
    /// Minimum width in density-independent pixels. Defaults to 120dp if not
    /// specified.
    #[setters(strip_option)]
    pub min_width: Option<Dp>,
    /// Minimum height in density-independent pixels. Defaults to line height +
    /// padding if not specified.
    #[setters(strip_option)]
    pub min_height: Option<Dp>,
    /// Background color of the text editor (RGBA). Defaults to light gray.
    #[setters(strip_option)]
    pub background_color: Option<Color>,
    /// Border width in Dp. Defaults to 1.0 Dp.
    pub border_width: Dp,
    /// Border color (RGBA). Defaults to gray.
    #[setters(strip_option)]
    pub border_color: Option<Color>,
    /// The shape of the text editor container.
    pub shape: Shape,
    /// Padding inside the text editor. Defaults to 5.0 Dp.
    pub padding: Dp,
    /// Border color when focused (RGBA). Defaults to blue.
    #[setters(strip_option)]
    pub focus_border_color: Option<Color>,
    /// Background color when focused (RGBA). Defaults to white.
    #[setters(strip_option)]
    pub focus_background_color: Option<Color>,
    /// Color for text selection highlight (RGBA). Defaults to light blue with
    /// transparency.
    #[setters(strip_option)]
    pub selection_color: Option<Color>,
    /// Optional label announced by assistive technologies.
    #[setters(strip_option, into)]
    pub accessibility_label: Option<String>,
    /// Optional description announced by assistive technologies.
    #[setters(strip_option, into)]
    pub accessibility_description: Option<String>,
    /// Initial text content.
    #[setters(strip_option, into)]
    pub initial_text: Option<String>,
    /// Font size in Dp. Defaults to 14.0.
    pub font_size: Dp,
    /// Line height in Dp. Defaults to None (1.2x font size).
    #[setters(strip_option)]
    pub line_height: Option<Dp>,
}

impl TextEditorArgs {
    /// Set the text change handler.
    pub fn on_change<F>(mut self, on_change: F) -> Self
    where
        F: Fn(String) -> String + Send + Sync + 'static,
    {
        self.on_change = Arc::new(on_change);
        self
    }

    /// Set the text change handler using a shared callback.
    pub fn on_change_shared(
        mut self,
        on_change: Arc<dyn Fn(String) -> String + Send + Sync>,
    ) -> Self {
        self.on_change = on_change;
        self
    }
}

impl Default for TextEditorArgs {
    fn default() -> Self {
        let scheme = use_context::<MaterialTheme>()
            .expect("MaterialTheme must be provided")
            .get()
            .color_scheme;
        Self {
            modifier: Modifier::new(),
            on_change: Arc::new(|_| String::new()),
            min_width: None,
            min_height: None,
            background_color: Some(scheme.surface_variant),
            border_width: Dp(1.0),
            border_color: Some(scheme.outline_variant),
            shape: Shape::RoundedRectangle {
                top_left: RoundedCorner::manual(Dp(4.0), 3.0),
                top_right: RoundedCorner::manual(Dp(4.0), 3.0),
                bottom_right: RoundedCorner::manual(Dp(4.0), 3.0),
                bottom_left: RoundedCorner::manual(Dp(4.0), 3.0),
            },
            padding: Dp(5.0),
            focus_border_color: Some(scheme.primary),
            focus_background_color: Some(scheme.surface),
            selection_color: Some(scheme.primary.with_alpha(0.35)),
            accessibility_label: None,
            accessibility_description: None,
            initial_text: None,
            font_size: Dp(14.0),
            line_height: None,
        }
    }
}

/// # text_editor
///
/// Renders a multi-line, editable text field.
///
/// # Usage
///
/// Create an interactive text editor for forms, note-taking, or other text
/// input scenarios.
///
/// # Parameters
///
/// - `args` — configures the editor's appearance and layout; see
///   [`TextEditorArgs`].
///
/// # Examples
///
/// ```
/// # use tessera_ui::tessera;
/// # #[tessera]
/// # fn component() {
/// use tessera_components::text_editor::{TextEditorArgs, text_editor};
/// use tessera_ui::Dp;
/// # use tessera_components::theme::{MaterialTheme, material_theme};
///
/// # material_theme(|| MaterialTheme::default(), || {
/// text_editor(
///     TextEditorArgs::default()
///         .padding(Dp(8.0))
///         .initial_text("Hello World"),
/// );
/// # });
/// # }
/// # component();
/// ```
#[tessera]
pub fn text_editor(args: impl Into<TextEditorArgs>) {
    let args: TextEditorArgs = args.into();
    let controller = remember(|| {
        let mut c = TextEditorController::new(args.font_size, args.line_height);
        if let Some(text) = &args.initial_text {
            c.set_text(text);
        }
        c
    });

    text_editor_with_controller(args, controller);
}

/// # text_editor_with_controller
///
/// Renders a multi-line, editable text field with an external controller.
///
/// # Usage
///
/// Use this component when you need to control the text editor state
/// externally, for example to synchronize text with other components or to
/// programmatically modify the text content or selection.
///
/// # Parameters
///
/// - `args` — configures the editor's appearance and layout; see
///   [`TextEditorArgs`].
/// - `controller` — a `TextEditorController` to manage the editor's content,
///   cursor, and selection.
///
/// # Examples
///
/// ```
/// # use tessera_ui::tessera;
/// # #[tessera]
/// # fn component() {
/// use tessera_components::{
///     text::write_font_system,
///     text_editor::{TextEditorArgs, TextEditorController, text_editor_with_controller},
/// };
/// use tessera_ui::Dp;
/// use tessera_ui::remember;
/// # use tessera_components::theme::{MaterialTheme, material_theme};
///
/// # material_theme(|| MaterialTheme::default(), || {
/// let controller = remember(|| TextEditorController::new(Dp(14.0), None));
/// controller.with_mut(|c| c.set_text("Initial text"));
///
/// text_editor_with_controller(TextEditorArgs::default().padding(Dp(8.0)), controller);
/// # });
/// # }
/// # component();
/// ```
#[tessera]
pub fn text_editor_with_controller(
    args: impl Into<TextEditorArgs>,
    controller: State<TextEditorController>,
) {
    let editor_args: TextEditorArgs = args.into();
    let on_change = editor_args.on_change.clone();

    // Update the state with the selection color from args
    if let Some(selection_color) = editor_args.selection_color {
        controller.with_mut(|c| c.set_selection_color(selection_color));
    }

    // surface layer - provides visual container and minimum size guarantee
    {
        let args_for_surface = editor_args.clone();
        surface(
            create_surface_args(&args_for_surface, &controller),
            move || {
                // Core layer - handles text rendering and editing logic
                let padding = args_for_surface.padding;
                Modifier::new().padding_all(padding).run(move || {
                    text_edit_core(controller);
                });
            },
        );
    }

    // Event handling at the outermost layer - can access full surface area

    let args_for_handler = editor_args.clone();
    input_handler(move |mut input| {
        let size = input.computed_data; // This is the full surface size
        let cursor_pos_option = input.cursor_position_rel;
        let is_cursor_in_editor = cursor_pos_option
            .map(|pos| is_position_in_component(size, pos))
            .unwrap_or(false);

        // Set text input cursor when hovering
        if is_cursor_in_editor {
            input.requests.cursor_icon = winit::window::CursorIcon::Text;
        }

        // Handle click events - now we have a full clickable area from surface
        if is_cursor_in_editor {
            // Handle mouse pressed events
            let click_events: Vec<_> = input
                .cursor_events
                .iter()
                .filter(|event| matches!(event.content, CursorEventContent::Pressed(_)))
                .collect();

            // Handle mouse released events (end of drag)
            let release_events: Vec<_> = input
                .cursor_events
                .iter()
                .filter(|event| matches!(event.content, CursorEventContent::Released(_)))
                .collect();

            if !click_events.is_empty() {
                // Request focus if not already focused
                if !controller.with(|s| s.focus_handler().is_focused()) {
                    controller.with_mut(|s| {
                        s.focus_handler_mut().request_focus();
                    });
                }

                // Handle cursor positioning for clicks
                if let Some(cursor_pos) = cursor_pos_option {
                    // Calculate the relative position within the text area
                    let padding_px: Px = args_for_handler.padding.into();
                    let border_width_px = Px(args_for_handler.border_width.to_pixels_u32() as i32); // Assuming border_width is integer pixels

                    let text_relative_x_px = cursor_pos.x - padding_px - border_width_px;
                    let text_relative_y_px = cursor_pos.y - padding_px - border_width_px;

                    // Only process if the click is within the text area (non-negative relative
                    // coords)
                    if text_relative_x_px >= Px(0) && text_relative_y_px >= Px(0) {
                        let text_relative_pos =
                            PxPosition::new(text_relative_x_px, text_relative_y_px);
                        // Determine click type and handle accordingly
                        let click_type = controller.with_mut(|s| {
                            s.handle_click(text_relative_pos, click_events[0].timestamp)
                        });

                        match click_type {
                            ClickType::Single => {
                                // Single click: position cursor
                                controller.with_mut(|s| {
                                    s.with_editor_mut(|editor| {
                                        editor.action(
                                            &mut write_font_system(),
                                            GlyphonAction::Click {
                                                x: text_relative_pos.x.0,
                                                y: text_relative_pos.y.0,
                                            },
                                        );
                                    });
                                });
                            }
                            ClickType::Double => {
                                // Double click: select word
                                controller.with_mut(|s| {
                                    s.with_editor_mut(|editor| {
                                        editor.action(
                                            &mut write_font_system(),
                                            GlyphonAction::DoubleClick {
                                                x: text_relative_pos.x.0,
                                                y: text_relative_pos.y.0,
                                            },
                                        );
                                    });
                                });
                            }
                            ClickType::Triple => {
                                // Triple click: select line
                                controller.with_mut(|s| {
                                    s.with_editor_mut(|editor| {
                                        editor.action(
                                            &mut write_font_system(),
                                            GlyphonAction::TripleClick {
                                                x: text_relative_pos.x.0,
                                                y: text_relative_pos.y.0,
                                            },
                                        );
                                    });
                                });
                            }
                        }

                        // Start potential drag operation
                        controller.with_mut(|s| s.start_drag());
                    }
                }
            }

            // Handle drag events (mouse move while dragging)
            // This happens every frame when cursor position changes during drag
            if controller.with(|s| s.is_dragging())
                && let Some(cursor_pos) = cursor_pos_option
            {
                let padding_px: Px = args_for_handler.padding.into();
                let border_width_px = Px(args_for_handler.border_width.to_pixels_u32() as i32);

                let text_relative_x_px = cursor_pos.x - padding_px - border_width_px;
                let text_relative_y_px = cursor_pos.y - padding_px - border_width_px;

                if text_relative_x_px >= Px(0) && text_relative_y_px >= Px(0) {
                    let current_pos_px = PxPosition::new(text_relative_x_px, text_relative_y_px);
                    let last_pos_px = controller.with(|s| s.last_click_position());

                    if last_pos_px != Some(current_pos_px) {
                        // Extend selection by dragging
                        controller.with_mut(|s| {
                            s.with_editor_mut(|editor| {
                                editor.action(
                                    &mut write_font_system(),
                                    GlyphonAction::Drag {
                                        x: current_pos_px.x.0,
                                        y: current_pos_px.y.0,
                                    },
                                );
                            });
                        });

                        // Update last position to current position
                        controller.with_mut(|s| {
                            s.update_last_click_position(current_pos_px);
                        });
                    }
                }
            }

            // Handle mouse release events (end drag)
            if !release_events.is_empty() {
                controller.with_mut(|s| s.stop_drag());
            }

            let scroll_events: Vec<_> = input
                .cursor_events
                .iter()
                .filter_map(|event| match &event.content {
                    CursorEventContent::Scroll(scroll_event) => Some(scroll_event),
                    _ => None,
                })
                .collect();

            // Handle scroll events (only when focused and cursor is in editor)
            if controller.with(|s| s.focus_handler().is_focused()) {
                for scroll_event in scroll_events {
                    // Convert scroll delta to lines
                    let scroll = -scroll_event.delta_y;

                    // Scroll up for positive, down for negative
                    let action = GlyphonAction::Scroll { pixels: scroll };
                    controller.with_mut(|s| {
                        s.with_editor_mut(|editor| {
                            editor.action(&mut write_font_system(), action);
                        });
                    });
                }
            }

            // Only block cursor events when focused to prevent propagation
            if controller.with(|s| s.focus_handler().is_focused()) {
                input.cursor_events.clear();
            }
        }

        // Handle keyboard events (only when focused)
        if controller.with(|s| s.focus_handler().is_focused()) {
            // Handle keyboard events
            let is_ctrl = input.key_modifiers.control_key() || input.key_modifiers.super_key();

            // Custom handling for Ctrl+A (Select All)
            let select_all_event_index = input.keyboard_events.iter().position(|key_event| {
                if let winit::keyboard::Key::Character(s) = &key_event.logical_key {
                    is_ctrl
                        && s.to_lowercase() == "a"
                        && key_event.state == winit::event::ElementState::Pressed
                } else {
                    false
                }
            });

            if let Some(_index) = select_all_event_index {
                controller.with_mut(|s| {
                    s.with_editor_mut(|editor| {
                        // Set cursor to the beginning of the document
                        editor.set_cursor(glyphon::Cursor::new(0, 0));
                        // Set selection to start from the beginning
                        editor.set_selection(glyphon::cosmic_text::Selection::Normal(
                            glyphon::Cursor::new(0, 0),
                        ));
                        // Move cursor to the end, which extends the selection (use BufferEnd for
                        // full document)
                        editor.action(
                            &mut write_font_system(),
                            GlyphonAction::Motion(glyphon::cosmic_text::Motion::BufferEnd),
                        );
                    });
                });
            } else {
                // Original logic for other keys
                let mut all_actions = Vec::new();
                controller.with_mut(|s| {
                    for key_event in input.keyboard_events.iter().cloned() {
                        if let Some(actions) = s.map_key_event_to_action(
                            key_event,
                            input.key_modifiers,
                            input.clipboard,
                        ) {
                            all_actions.extend(actions);
                        }
                    }
                });

                if !all_actions.is_empty() {
                    for action in all_actions {
                        handle_action(&controller, action, on_change.clone());
                    }
                }
            }

            // Block all keyboard events to prevent propagation
            input.keyboard_events.clear();

            // Handle IME events
            let ime_events: Vec<_> = input.ime_events.drain(..).collect();
            for event in ime_events {
                match event {
                    winit::event::Ime::Commit(text) => {
                        // Clear preedit string if it exists
                        let preedit_text = controller.with_mut(|s| s.preedit_string.take());

                        if let Some(preedit_text) = preedit_text {
                            for _ in 0..preedit_text.chars().count() {
                                handle_action(
                                    &controller,
                                    GlyphonAction::Backspace,
                                    on_change.clone(),
                                );
                            }
                        }
                        // Insert the committed text
                        for c in text.chars() {
                            handle_action(&controller, GlyphonAction::Insert(c), on_change.clone());
                        }
                    }
                    winit::event::Ime::Preedit(text, _cursor_offset) => {
                        // Remove the old preedit text if it exists
                        let old_preedit = controller.with_mut(|s| s.preedit_string.take());

                        if let Some(old_preedit) = old_preedit {
                            for _ in 0..old_preedit.chars().count() {
                                handle_action(
                                    &controller,
                                    GlyphonAction::Backspace,
                                    on_change.clone(),
                                );
                            }
                        }
                        // Insert the new preedit text
                        for c in text.chars() {
                            handle_action(&controller, GlyphonAction::Insert(c), on_change.clone());
                        }
                        controller.with_mut(|c| c.preedit_string = Some(text.to_string()));
                    }
                    _ => {}
                }
            }

            // Request IME window
            input.requests.ime_request = Some(ImeRequest::new(size.into()));
        }

        apply_text_editor_accessibility(&mut input, &args_for_handler, &controller);
    });
}

fn handle_action(
    state: &State<TextEditorController>,
    action: GlyphonAction,
    on_change: Arc<dyn Fn(String) -> String + Send + Sync>,
) {
    // Clone a temporary editor and apply action, waiting for on_change to confirm
    let mut new_editor = state.with(|c| c.editor().clone());

    // Make sure new editor own a isolated buffer
    let mut new_buffer = None;
    match new_editor.buffer_ref_mut() {
        glyphon::cosmic_text::BufferRef::Owned(_) => { /* Already owned */ }
        glyphon::cosmic_text::BufferRef::Borrowed(buffer) => {
            new_buffer = Some(buffer.clone());
        }
        glyphon::cosmic_text::BufferRef::Arc(buffer) => {
            new_buffer = Some((**buffer).clone());
        }
    }
    if let Some(buffer) = new_buffer {
        *new_editor.buffer_ref_mut() = glyphon::cosmic_text::BufferRef::Owned(buffer);
    }

    new_editor.action(&mut write_font_system(), action);
    let content_after_action = get_editor_content(&new_editor);

    state.with_mut(|c| c.with_editor_mut(|editor| editor.action(&mut write_font_system(), action)));
    let new_content = on_change(content_after_action);

    // Update editor content
    state.with_mut(|c| c.set_text(&new_content));
}

/// Create surface arguments based on editor configuration and state
fn create_surface_args(
    args: &TextEditorArgs,
    state: &State<TextEditorController>,
) -> crate::surface::SurfaceArgs {
    let style = if args.border_width.to_pixels_f32() > 0.0 {
        crate::surface::SurfaceStyle::FilledOutlined {
            fill_color: determine_background_color(args, state),
            border_color: determine_border_color(args, state)
                .expect("Border color should exist when border width is positive"),
            border_width: args.border_width,
        }
    } else {
        crate::surface::SurfaceStyle::Filled {
            color: determine_background_color(args, state),
        }
    };

    SurfaceArgs::default()
        .style(style)
        .shape(args.shape)
        .modifier(args.modifier)
}

/// Determine background color based on focus state
fn determine_background_color(args: &TextEditorArgs, state: &State<TextEditorController>) -> Color {
    if state.with(|c| c.focus_handler().is_focused()) {
        args.focus_background_color
            .or(args.background_color)
            .unwrap_or(
                use_context::<MaterialTheme>()
                    .expect("MaterialTheme must be provided")
                    .get()
                    .color_scheme
                    .surface,
            )
    } else {
        args.background_color.unwrap_or(
            use_context::<MaterialTheme>()
                .expect("MaterialTheme must be provided")
                .get()
                .color_scheme
                .surface_variant,
        )
    }
}

/// Determine border color based on focus state
fn determine_border_color(
    args: &TextEditorArgs,
    state: &State<TextEditorController>,
) -> Option<Color> {
    if state.with(|c| c.focus_handler().is_focused()) {
        args.focus_border_color.or(args.border_color).or(Some(
            use_context::<MaterialTheme>()
                .expect("MaterialTheme must be provided")
                .get()
                .color_scheme
                .primary,
        ))
    } else {
        args.border_color.or(Some(
            use_context::<MaterialTheme>()
                .expect("MaterialTheme must be provided")
                .get()
                .color_scheme
                .outline_variant,
        ))
    }
}

/// Convenience constructors for common use cases
impl TextEditorArgs {
    /// Creates a simple text editor with default styling.
    ///
    /// - Minimum width: 120dp
    /// - Background: white
    /// - Border: 1px gray, rounded rectangle
    ///
    /// # Example
    ///
    /// ```
    /// # use tessera_ui::tessera;
    /// # #[tessera]
    /// # fn component() {
    /// use tessera_components::text_editor::TextEditorArgs;
    /// # use tessera_components::theme::{MaterialTheme, material_theme};
    /// # material_theme(|| MaterialTheme::default(), || {
    /// let args = TextEditorArgs::simple();
    /// # });
    /// # }
    /// # component();
    /// ```
    pub fn simple() -> Self {
        TextEditorArgs::default()
            .min_width(Dp(120.0))
            .background_color(
                use_context::<MaterialTheme>()
                    .expect("MaterialTheme must be provided")
                    .get()
                    .color_scheme
                    .surface_variant,
            )
            .border_width(Dp(1.0))
            .border_color(
                use_context::<MaterialTheme>()
                    .expect("MaterialTheme must be provided")
                    .get()
                    .color_scheme
                    .outline_variant,
            )
            .shape(Shape::RoundedRectangle {
                top_left: RoundedCorner::manual(Dp(0.0), 3.0),
                top_right: RoundedCorner::manual(Dp(0.0), 3.0),
                bottom_right: RoundedCorner::manual(Dp(0.0), 3.0),
                bottom_left: RoundedCorner::manual(Dp(0.0), 3.0),
            })
    }

    /// Creates a text editor with an emphasized border for better visibility.
    ///
    /// - Border: 2px, blue focus border
    ///
    /// # Example
    /// ```
    /// # use tessera_ui::tessera;
    /// # #[tessera]
    /// # fn component() {
    /// use tessera_components::text_editor::TextEditorArgs;
    /// # use tessera_components::theme::{MaterialTheme, material_theme};
    /// # material_theme(|| MaterialTheme::default(), || {
    /// let args = TextEditorArgs::outlined();
    /// # });
    /// # }
    /// # component();
    /// ```
    pub fn outlined() -> Self {
        Self::simple()
            .with_border_width(Dp(1.0))
            .with_focus_border_color(Color::new(0.0, 0.5, 1.0, 1.0))
    }

    /// Creates a text editor with no border (minimal style).
    ///
    /// - Border: 0px, square corners
    ///
    /// # Example
    /// ```
    /// # use tessera_ui::tessera;
    /// # #[tessera]
    /// # fn component() {
    /// use tessera_components::text_editor::TextEditorArgs;
    /// # use tessera_components::theme::{MaterialTheme, material_theme};
    /// # material_theme(|| MaterialTheme::default(), || {
    /// let args = TextEditorArgs::minimal();
    /// # });
    /// # }
    /// # component();
    /// ```
    pub fn minimal() -> Self {
        TextEditorArgs::default()
            .min_width(Dp(120.0))
            .background_color(Color::WHITE)
            .shape(Shape::RoundedRectangle {
                top_left: RoundedCorner::manual(Dp(0.0), 3.0),
                top_right: RoundedCorner::manual(Dp(0.0), 3.0),
                bottom_right: RoundedCorner::manual(Dp(0.0), 3.0),
                bottom_left: RoundedCorner::manual(Dp(0.0), 3.0),
            })
    }
}

/// Builder methods for fluent API
impl TextEditorArgs {
    /// Sets the minimum width in Dp.
    ///
    /// # Example
    ///
    /// ```
    /// # use tessera_ui::tessera;
    /// # #[tessera]
    /// # fn component() {
    /// use tessera_components::text_editor::TextEditorArgs;
    /// use tessera_ui::Dp;
    /// # use tessera_components::theme::{MaterialTheme, material_theme};
    /// # material_theme(|| MaterialTheme::default(), || {
    /// let args = TextEditorArgs::simple().with_min_width(Dp(80.0));
    /// # });
    /// # }
    /// # component();
    /// ```
    pub fn with_min_width(mut self, min_width: Dp) -> Self {
        self.min_width = Some(min_width);
        self
    }

    /// Sets the minimum height in Dp.
    ///
    /// # Example
    ///
    /// ```
    /// # use tessera_ui::tessera;
    /// # #[tessera]
    /// # fn component() {
    /// use tessera_components::text_editor::TextEditorArgs;
    /// use tessera_ui::Dp;
    /// # use tessera_components::theme::{MaterialTheme, material_theme};
    /// # material_theme(|| MaterialTheme::default(), || {
    /// let args = TextEditorArgs::simple().with_min_height(Dp(40.0));
    /// # });
    /// # }
    /// # component();
    /// ```
    pub fn with_min_height(mut self, min_height: Dp) -> Self {
        self.min_height = Some(min_height);
        self
    }

    /// Sets the background color.
    ///
    /// # Example
    /// ```
    /// # use tessera_ui::tessera;
    /// # #[tessera]
    /// # fn component() {
    /// use tessera_components::text_editor::TextEditorArgs;
    /// use tessera_ui::Color;
    /// # use tessera_components::theme::{MaterialTheme, material_theme};
    /// # material_theme(|| MaterialTheme::default(), || {
    /// let args = TextEditorArgs::simple().with_background_color(Color::WHITE);
    /// # });
    /// # }
    /// # component();
    /// ```
    pub fn with_background_color(mut self, color: Color) -> Self {
        self.background_color = Some(color);
        self
    }

    /// Sets the border width in pixels.
    ///
    /// # Example
    ///
    /// ```
    /// # use tessera_ui::tessera;
    /// # #[tessera]
    /// # fn component() {
    /// use tessera_components::text_editor::TextEditorArgs;
    /// use tessera_ui::Dp;
    ///
    /// # use tessera_components::theme::{MaterialTheme, material_theme};
    /// # material_theme(|| MaterialTheme::default(), || {
    /// let args = TextEditorArgs::simple().with_border_width(Dp(1.0));
    /// # });
    /// # }
    /// # component();
    /// ```
    pub fn with_border_width(mut self, width: Dp) -> Self {
        self.border_width = width;
        self
    }

    /// Sets the border color.
    ///
    /// # Example
    ///
    /// ```
    /// # use tessera_ui::tessera;
    /// # #[tessera]
    /// # fn component() {
    /// use tessera_components::text_editor::TextEditorArgs;
    /// use tessera_ui::Color;
    /// # use tessera_components::theme::{MaterialTheme, material_theme};
    /// # material_theme(|| MaterialTheme::default(), || {
    /// let args = TextEditorArgs::simple().with_border_color(Color::BLACK);
    /// # });
    /// # }
    /// # component();
    /// ```
    pub fn with_border_color(mut self, color: Color) -> Self {
        self.border_color = Some(color);
        self
    }

    /// Sets the shape of the editor container.
    ///
    /// # Example
    ///
    /// ```
    /// # use tessera_ui::tessera;
    /// # #[tessera]
    /// # fn component() {
    /// use tessera_components::shape_def::{RoundedCorner, Shape};
    /// use tessera_components::text_editor::TextEditorArgs;
    /// use tessera_ui::Dp;
    /// # use tessera_components::theme::{MaterialTheme, material_theme};
    /// # material_theme(|| MaterialTheme::default(), || {
    /// let args = TextEditorArgs::simple().with_shape(Shape::RoundedRectangle {
    ///     top_left: RoundedCorner::manual(Dp(8.0), 3.0),
    ///     top_right: RoundedCorner::manual(Dp(8.0), 3.0),
    ///     bottom_right: RoundedCorner::manual(Dp(8.0), 3.0),
    ///     bottom_left: RoundedCorner::manual(Dp(8.0), 3.0),
    /// });
    /// # });
    /// # }
    /// # component();
    /// ```
    pub fn with_shape(mut self, shape: Shape) -> Self {
        self.shape = shape;
        self
    }

    /// Sets the inner padding in Dp.
    ///
    /// # Example
    ///
    /// ```
    /// # use tessera_ui::tessera;
    /// # #[tessera]
    /// # fn component() {
    /// use tessera_components::text_editor::TextEditorArgs;
    /// use tessera_ui::Dp;
    /// # use tessera_components::theme::{MaterialTheme, material_theme};
    /// # material_theme(|| MaterialTheme::default(), || {
    /// let args = TextEditorArgs::simple().with_padding(Dp(12.0));
    /// # });
    /// # }
    /// # component();
    /// ```
    pub fn with_padding(mut self, padding: Dp) -> Self {
        self.padding = padding;
        self
    }

    /// Sets the border color when focused.
    ///
    /// # Example
    ///
    /// ```
    /// # use tessera_ui::tessera;
    /// # #[tessera]
    /// # fn component() {
    /// use tessera_components::text_editor::TextEditorArgs;
    /// use tessera_ui::Color;
    /// # use tessera_components::theme::{MaterialTheme, material_theme};
    /// # material_theme(|| MaterialTheme::default(), || {
    /// let args = TextEditorArgs::simple().with_focus_border_color(Color::new(0.0, 0.5, 1.0, 1.0));
    /// # });
    /// # }
    /// # component();
    /// ```
    pub fn with_focus_border_color(mut self, color: Color) -> Self {
        self.focus_border_color = Some(color);
        self
    }

    /// Sets the background color when focused.
    ///
    /// # Example
    ///
    /// ```
    /// # use tessera_ui::tessera;
    /// # #[tessera]
    /// # fn component() {
    /// use tessera_components::text_editor::TextEditorArgs;
    /// use tessera_ui::Color;
    /// # use tessera_components::theme::{MaterialTheme, material_theme};
    /// # material_theme(|| MaterialTheme::default(), || {
    /// let args = TextEditorArgs::simple().with_focus_background_color(Color::WHITE);
    /// # });
    /// # }
    /// # component();
    /// ```
    pub fn with_focus_background_color(mut self, color: Color) -> Self {
        self.focus_background_color = Some(color);
        self
    }

    /// Sets the selection highlight color.
    ///
    /// # Example
    ///
    /// ```
    /// # use tessera_ui::tessera;
    /// # #[tessera]
    /// # fn component() {
    /// use tessera_components::text_editor::TextEditorArgs;
    /// use tessera_ui::Color;
    /// # use tessera_components::theme::{MaterialTheme, material_theme};
    /// # material_theme(|| MaterialTheme::default(), || {
    /// let args = TextEditorArgs::simple().with_selection_color(Color::new(0.5, 0.7, 1.0, 0.4));
    /// # });
    /// # }
    /// # component();
    /// ```
    pub fn with_selection_color(mut self, color: Color) -> Self {
        self.selection_color = Some(color);
        self
    }
}

fn get_editor_content(editor: &glyphon::Editor) -> String {
    editor.with_buffer(|buffer| {
        buffer
            .lines
            .iter()
            .map(|line| line.text().to_string() + line.ending().as_str())
            .collect::<String>()
    })
}

fn apply_text_editor_accessibility(
    input: &mut tessera_ui::InputHandlerInput<'_>,
    args: &TextEditorArgs,
    state: &State<TextEditorController>,
) {
    let mut builder = input.accessibility().role(Role::MultilineTextInput);

    if let Some(label) = args.accessibility_label.as_ref() {
        builder = builder.label(label.clone());
    }

    if let Some(description) = args.accessibility_description.as_ref() {
        builder = builder.description(description.clone());
    }

    let current_text = state.with(|c| get_editor_content(c.editor()));
    if !current_text.is_empty() {
        builder = builder.value(current_text);
    }

    builder.focusable().commit();
}