ccf-gpui-widgets 0.1.0

Reusable GPUI widgets for building desktop applications
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
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
//! Password input widget with visibility toggle
//!
//! A secure text input that masks its content with bullet characters and provides
//! a button to toggle password visibility. When the `secure-password` feature is
//! enabled, uses `SensitiveString` internally for automatic memory zeroization
//! and exposes `SecretString` at API boundaries.
//!
//! # Example
//!
//! ```ignore
//! use ccf_gpui_widgets::widgets::{PasswordInput, PasswordInputEvent};
//!
//! let password_input = cx.new(|cx| {
//!     PasswordInput::new(cx)
//!         .placeholder("Enter password")
//! });
//!
//! // Subscribe to events
//! cx.subscribe(&password_input, |this, _, event: &PasswordInputEvent, cx| {
//!     match event {
//!         PasswordInputEvent::Change(secret) => {
//!             // Use secret.expose_secret() to access the password
//!             println!("Password changed");
//!         }
//!         PasswordInputEvent::Enter => println!("Enter pressed"),
//!         PasswordInputEvent::Blur => println!("Focus lost"),
//!     }
//! }).detach();
//! ```

use std::time::Duration;

use gpui::prelude::*;
use gpui::*;

#[cfg(feature = "secure-password")]
use secrecy::SecretString;

use crate::theme::{get_theme_or, Theme};
use super::cursor_blink::CursorBlink;
use super::editing_core::EditingCore;
use super::focus_navigation::{FocusNext, FocusPrev, handle_tab_navigation, EnabledCursorExt};
use super::text_input::{
    MoveLeft, MoveRight, MoveWordLeft, MoveWordRight, MoveToStart, MoveToEnd,
    SelectLeft, SelectRight, SelectWordLeft, SelectWordRight, SelectToStart, SelectToEnd, SelectAll,
    DeleteBackward, DeleteForward, DeleteWordBackward, DeleteWordForward,
    Cut, Copy, Paste, Enter, Escape,
};

#[cfg(feature = "secure-password")]
use super::sensitive_string::SensitiveString;

/// Events emitted by PasswordInput
#[derive(Debug, Clone)]
pub enum PasswordInputEvent {
    /// Password value changed
    #[cfg(feature = "secure-password")]
    Change(SecretString),
    /// Password value changed (without secure-password feature)
    #[cfg(not(feature = "secure-password"))]
    Change(String),
    /// Enter key was pressed
    Enter,
    /// Input lost focus (including Escape key)
    Blur,
}

/// Character used to mask password input
const MASK_CHAR: &str = "\u{25CF}"; // ● Black circle

/// Password input widget with visibility toggle
///
/// This widget provides a secure password entry field with:
/// - Masked display by default (bullet characters)
/// - Toggle button to show/hide the actual password
/// - Full cursor/selection support
/// - When `secure-password` feature is enabled:
///   - Automatic memory zeroization when dropped
///   - `SecretString` at API boundaries
///   - Redacted Debug output
pub struct PasswordInput {
    /// Core editing logic with secure storage
    #[cfg(feature = "secure-password")]
    core: EditingCore<SensitiveString>,
    #[cfg(not(feature = "secure-password"))]
    core: EditingCore<String>,
    /// Focus handle for the text input area
    input_focus_handle: FocusHandle,
    /// Focus handle for the toggle button
    toggle_focus_handle: FocusHandle,
    /// Whether password is currently visible
    show_password: bool,
    /// Placeholder text
    placeholder: Option<SharedString>,
    /// Optional custom theme
    custom_theme: Option<Theme>,
    /// Horizontal scroll offset in pixels
    scroll_offset: f32,
    /// Visible width of the text area
    visible_width: f32,
    /// Left edge of content area in window coordinates
    content_origin_x: f32,
    /// Track previous focus state
    was_focused: bool,
    /// Whether focus-out subscription has been set up
    focus_out_subscribed: bool,
    /// Cursor blink state
    cursor_blink: CursorBlink,
    /// Whether blink timer is set up
    blink_timer_active: bool,
    /// Whether currently dragging to select text
    is_dragging: bool,
    /// Whether auto-scroll timer is active
    auto_scroll_active: bool,
    /// Current auto-scroll speed
    auto_scroll_speed: f32,
    /// Pending placeholder from builder
    pending_placeholder: Option<SharedString>,
    /// Pending value from builder
    pending_value: Option<String>,
    /// Whether the input is enabled
    enabled: bool,
}

impl EventEmitter<PasswordInputEvent> for PasswordInput {}

impl Focusable for PasswordInput {
    fn focus_handle(&self, _cx: &App) -> FocusHandle {
        self.input_focus_handle.clone()
    }
}

impl PasswordInput {
    /// Create a new password input
    pub fn new(cx: &mut Context<Self>) -> Self {
        #[cfg(feature = "secure-password")]
        let core = EditingCore::<SensitiveString>::new().with_masked(true);
        #[cfg(not(feature = "secure-password"))]
        let core = EditingCore::<String>::new().with_masked(true);

        Self {
            core,
            input_focus_handle: cx.focus_handle().tab_stop(true),
            toggle_focus_handle: cx.focus_handle().tab_stop(true),
            show_password: false,
            placeholder: None,
            custom_theme: None,
            scroll_offset: 0.0,
            visible_width: 200.0,
            content_origin_x: 0.0,
            was_focused: false,
            focus_out_subscribed: false,
            cursor_blink: CursorBlink::new(),
            blink_timer_active: false,
            is_dragging: false,
            auto_scroll_active: false,
            auto_scroll_speed: 0.0,
            pending_placeholder: None,
            pending_value: None,
            enabled: true,
        }
    }

    /// Set placeholder text shown when empty (builder pattern)
    #[must_use]
    pub fn placeholder(mut self, text: impl Into<SharedString>) -> Self {
        self.pending_placeholder = Some(text.into());
        self
    }

    /// Set an initial value (builder pattern)
    #[must_use]
    pub fn with_value(mut self, value: impl Into<String>) -> Self {
        self.pending_value = Some(value.into());
        self
    }

    /// Set a custom theme for this widget (builder pattern)
    #[must_use]
    pub fn theme(mut self, theme: Theme) -> Self {
        self.custom_theme = Some(theme);
        self
    }

    /// Set whether the input is enabled (builder pattern)
    #[must_use]
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// Apply any pending builder values (called on first render)
    fn apply_pending(&mut self) {
        if let Some(placeholder) = self.pending_placeholder.take() {
            self.placeholder = Some(placeholder);
        }
        if let Some(value) = self.pending_value.take() {
            self.core.set_content(&value);
        }
    }

    /// Get the current password value as a SecretString
    #[cfg(feature = "secure-password")]
    pub fn value(&self, _cx: &App) -> SecretString {
        // Access the sensitive string through the core and convert to SecretString
        // The core stores SensitiveString which has to_secret_string()
        // We need to get at the underlying storage
        self.create_secret_from_content()
    }

    /// Get the current password value
    #[cfg(not(feature = "secure-password"))]
    pub fn value<'a>(&'a self, _cx: &'a App) -> &'a str {
        self.core.content()
    }

    /// Create a SecretString from the current content
    #[cfg(feature = "secure-password")]
    fn create_secret_from_content(&self) -> SecretString {
        SecretString::from(self.core.content().to_string())
    }

    /// Set the password value programmatically
    pub fn set_value(&mut self, value: &str, cx: &mut Context<Self>) {
        self.core.set_content(value);
        self.scroll_offset = 0.0;
        self.emit_change(cx);
        cx.notify();
    }

    /// Set the password value from a SecretString
    #[cfg(feature = "secure-password")]
    pub fn set_value_secret(&mut self, secret: &SecretString, cx: &mut Context<Self>) {
        use secrecy::ExposeSecret;
        self.core.set_content(secret.expose_secret());
        self.scroll_offset = 0.0;
        self.emit_change(cx);
        cx.notify();
    }

    /// Get the focus handle for this input
    pub fn focus_handle(&self, _cx: &App) -> FocusHandle {
        self.input_focus_handle.clone()
    }

    /// Check if the password is currently visible (unmasked)
    pub fn is_password_visible(&self) -> bool {
        self.show_password
    }

    /// Check if the input is enabled
    pub fn is_enabled(&self) -> bool {
        self.enabled
    }

    /// Set whether the input is enabled
    pub fn set_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
        if self.enabled != enabled {
            self.enabled = enabled;
            cx.notify();
        }
    }

    fn emit_change(&self, cx: &mut Context<Self>) {
        #[cfg(feature = "secure-password")]
        cx.emit(PasswordInputEvent::Change(self.create_secret_from_content()));
        #[cfg(not(feature = "secure-password"))]
        cx.emit(PasswordInputEvent::Change(self.core.content().to_string()));
    }

    fn toggle_visibility(&mut self, cx: &mut Context<Self>) {
        self.show_password = !self.show_password;
        self.core.set_masked(!self.show_password);
        cx.notify();
    }

    /// Get the display content (masked or real)
    fn display_content(&self) -> String {
        if self.core.is_masked() {
            MASK_CHAR.repeat(self.core.content().chars().count())
        } else {
            self.core.content().to_string()
        }
    }

    /// Convert a byte index in content to a byte index in display content
    fn content_byte_to_display_byte(&self, content_pos: usize) -> usize {
        if !self.core.is_masked() || self.core.content().is_empty() {
            return content_pos;
        }
        let char_count = self.core.content()[..content_pos].chars().count();
        char_count * MASK_CHAR.len()
    }

    /// Convert a byte index in display content to a byte index in content
    fn display_byte_to_content_byte(&self, display_pos: usize) -> usize {
        if !self.core.is_masked() || self.core.content().is_empty() {
            return display_pos;
        }
        let mask_char_len = MASK_CHAR.len();
        let char_index = display_pos / mask_char_len;
        self.core.content()
            .char_indices()
            .nth(char_index)
            .map(|(i, _)| i)
            .unwrap_or(self.core.content().len())
    }

    fn reset_cursor_blink(&mut self) {
        self.cursor_blink.reset();
    }

    fn shape_line(&self, window: &Window) -> Option<ShapedLine> {
        let display = self.display_content();
        if display.is_empty() {
            return None;
        }

        let style = window.text_style();
        let font_size = window.rem_size() * 0.875;

        let run = TextRun {
            len: display.len(),
            font: style.font(),
            color: style.color,
            background_color: None,
            underline: None,
            strikethrough: None,
        };

        Some(window.text_system().shape_line(
            SharedString::from(display),
            font_size,
            &[run],
            None,
        ))
    }

    fn cursor_at_x(&self, x: f32, window: &Window) -> usize {
        let adjusted_x = x + self.scroll_offset;

        if adjusted_x <= 0.0 || self.core.content().is_empty() {
            return 0;
        }

        if let Some(line) = self.shape_line(window) {
            let display_pos = line.closest_index_for_x(px(adjusted_x));
            self.display_byte_to_content_byte(display_pos)
        } else {
            0
        }
    }

    fn x_for_cursor(&self, cursor: usize, window: &Window) -> f32 {
        if self.core.content().is_empty() || cursor == 0 {
            return 0.0;
        }

        if let Some(line) = self.shape_line(window) {
            let display_cursor = self.content_byte_to_display_byte(cursor);
            let pixels = line.x_for_index(display_cursor);
            pixels.into()
        } else {
            0.0
        }
    }

    fn ensure_cursor_visible(&mut self, window: &Window) {
        let cursor_x = self.x_for_cursor(self.core.cursor(), window);
        let content_width = self.x_for_cursor(self.core.content().len(), window);
        let margin = 2.0;
        let cursor_width = 1.0;
        let padding = 2.0;

        let actual_visible = self.visible_width - padding;

        if content_width <= actual_visible {
            self.scroll_offset = 0.0;
            return;
        }

        let visual_cursor_x = cursor_x - self.scroll_offset;

        if visual_cursor_x + cursor_width > actual_visible - margin {
            self.scroll_offset = cursor_x + cursor_width - actual_visible + margin;
        }

        if visual_cursor_x < margin {
            self.scroll_offset = (cursor_x - margin).max(0.0);
        }

        let max_scroll = (content_width + cursor_width - actual_visible + margin).max(0.0);
        self.scroll_offset = self.scroll_offset.clamp(0.0, max_scroll);
    }

    fn handle_drag_move(&mut self, mouse_x: f32, window: &Window) -> f32 {
        if !self.is_dragging {
            return 0.0;
        }

        let relative_x = mouse_x - self.content_origin_x;
        let padding = 2.0;
        let actual_visible = self.visible_width - padding;

        let scroll_speed = if relative_x < 0.0 {
            -self.calculate_scroll_speed(-relative_x)
        } else if relative_x > actual_visible {
            self.calculate_scroll_speed(relative_x - actual_visible)
        } else {
            0.0
        };

        let clamped_x = relative_x.clamp(0.0, actual_visible);
        let new_cursor = self.cursor_at_x(clamped_x, window);
        self.core.extend_selection_to(new_cursor);
        self.reset_cursor_blink();

        scroll_speed
    }

    fn calculate_scroll_speed(&self, distance: f32) -> f32 {
        let base_speed = 0.5;
        let max_speed = 20.0;
        let max_distance = 100.0;

        let normalized = (distance / max_distance).min(1.0);
        let eased = 1.0 - (1.0 - normalized).powi(2);
        base_speed + eased * (max_speed - base_speed)
    }

    fn apply_auto_scroll(&mut self, window: &Window) {
        if self.auto_scroll_speed == 0.0 {
            return;
        }

        let content_width = self.x_for_cursor(self.core.content().len(), window);
        let padding = 2.0;
        let actual_visible = self.visible_width - padding;
        let max_scroll = (content_width - actual_visible).max(0.0);

        self.scroll_offset = (self.scroll_offset + self.auto_scroll_speed).clamp(0.0, max_scroll);

        if self.auto_scroll_speed < 0.0 {
            let new_cursor = self.cursor_at_x(0.0, window);
            self.core.extend_selection_to(new_cursor);
        } else {
            let new_cursor = self.cursor_at_x(actual_visible, window);
            self.core.extend_selection_to(new_cursor);
        }
    }

    fn stop_drag(&mut self) {
        self.is_dragging = false;
        self.auto_scroll_active = false;
        self.auto_scroll_speed = 0.0;
    }

    fn spawn_auto_scroll_timer_if_needed(&mut self, scroll_speed: f32, window: &mut Window, cx: &mut Context<Self>) {
        self.auto_scroll_speed = scroll_speed;
        if scroll_speed != 0.0 && !self.auto_scroll_active {
            self.auto_scroll_active = true;
            let entity = cx.entity();
            window.spawn(cx, async move |async_cx| {
                loop {
                    smol::Timer::after(Duration::from_millis(32)).await;
                    let should_continue = async_cx
                        .update_entity(&entity, |this, cx| {
                            if !this.auto_scroll_active || !this.is_dragging {
                                this.auto_scroll_active = false;
                                return false;
                            }
                            cx.notify();
                            true
                        })
                        .unwrap_or(false);
                    if !should_continue {
                        break;
                    }
                }
            }).detach();
        }
    }

    fn on_focus(&mut self, cx: &mut Context<Self>) {
        self.reset_cursor_blink();
        cx.notify();
    }

    fn on_blur(&mut self, cx: &mut Context<Self>) {
        self.stop_drag();
        cx.emit(PasswordInputEvent::Blur);
        cx.notify();
    }

    // Clipboard operations - password content should NEVER be copied
    fn cut(&mut self, cx: &mut Context<Self>) {
        // Delete selection but don't copy to clipboard (security)
        if self.core.delete_selection() {
            self.reset_cursor_blink();
            self.emit_change(cx);
            cx.notify();
        }
    }

    fn paste(&mut self, cx: &mut Context<Self>) {
        if let Some(clipboard) = cx.read_from_clipboard() {
            if let Some(text) = clipboard.text() {
                let clean_text = text.replace(['\n', '\r'], "");
                self.core.insert_text(&clean_text);
                self.reset_cursor_blink();
                self.emit_change(cx);
                cx.notify();
            }
        }
    }

    // Action handlers
    fn handle_move_left(&mut self, cx: &mut Context<Self>) {
        self.core.move_left();
        self.reset_cursor_blink();
        cx.notify();
    }

    fn handle_move_right(&mut self, cx: &mut Context<Self>) {
        self.core.move_right();
        self.reset_cursor_blink();
        cx.notify();
    }

    fn handle_move_word_left(&mut self, cx: &mut Context<Self>) {
        self.core.move_word_left();
        self.reset_cursor_blink();
        cx.notify();
    }

    fn handle_move_word_right(&mut self, cx: &mut Context<Self>) {
        self.core.move_word_right();
        self.reset_cursor_blink();
        cx.notify();
    }

    fn handle_move_to_start(&mut self, cx: &mut Context<Self>) {
        self.core.move_to_start();
        self.reset_cursor_blink();
        cx.notify();
    }

    fn handle_move_to_end(&mut self, cx: &mut Context<Self>) {
        self.core.move_to_end();
        self.reset_cursor_blink();
        cx.notify();
    }

    fn handle_select_left(&mut self, cx: &mut Context<Self>) {
        self.core.select_left();
        self.reset_cursor_blink();
        cx.notify();
    }

    fn handle_select_right(&mut self, cx: &mut Context<Self>) {
        self.core.select_right();
        self.reset_cursor_blink();
        cx.notify();
    }

    fn handle_select_word_left(&mut self, cx: &mut Context<Self>) {
        self.core.select_word_left();
        self.reset_cursor_blink();
        cx.notify();
    }

    fn handle_select_word_right(&mut self, cx: &mut Context<Self>) {
        self.core.select_word_right();
        self.reset_cursor_blink();
        cx.notify();
    }

    fn handle_select_to_start(&mut self, cx: &mut Context<Self>) {
        self.core.select_to_start();
        self.reset_cursor_blink();
        cx.notify();
    }

    fn handle_select_to_end(&mut self, cx: &mut Context<Self>) {
        self.core.select_to_end();
        self.reset_cursor_blink();
        cx.notify();
    }

    fn handle_select_all(&mut self, cx: &mut Context<Self>) {
        self.core.select_all();
        self.reset_cursor_blink();
        cx.notify();
    }

    fn handle_delete_backward(&mut self, cx: &mut Context<Self>) {
        if self.core.delete_backward() {
            self.reset_cursor_blink();
            self.emit_change(cx);
        }
        cx.notify();
    }

    fn handle_delete_forward(&mut self, cx: &mut Context<Self>) {
        if self.core.delete_forward() {
            self.reset_cursor_blink();
            self.emit_change(cx);
        }
        cx.notify();
    }

    fn handle_delete_word_backward(&mut self, cx: &mut Context<Self>) {
        if self.core.delete_word_backward() {
            self.reset_cursor_blink();
            self.emit_change(cx);
        }
        cx.notify();
    }

    fn handle_delete_word_forward(&mut self, cx: &mut Context<Self>) {
        if self.core.delete_word_forward() {
            self.reset_cursor_blink();
            self.emit_change(cx);
        }
        cx.notify();
    }

    fn handle_insert_text(&mut self, text: &str, cx: &mut Context<Self>) {
        self.core.insert_text(text);
        self.reset_cursor_blink();
        self.emit_change(cx);
        cx.notify();
    }
}

impl Render for PasswordInput {
    fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
        // Apply any pending builder values on first render
        self.apply_pending();

        let theme = get_theme_or(cx, self.custom_theme.as_ref());
        let enabled = self.enabled;
        let input_focus_handle = self.input_focus_handle.clone().tab_stop(enabled);
        let toggle_focus_handle = self.toggle_focus_handle.clone().tab_stop(enabled);
        let input_is_focused = self.input_focus_handle.is_focused(window);
        let toggle_is_focused = self.toggle_focus_handle.is_focused(window);
        let either_focused = input_is_focused || toggle_is_focused;

        // Set up focus-out subscription on first render
        if !self.focus_out_subscribed {
            self.focus_out_subscribed = true;
            let input_fh = self.input_focus_handle.clone();
            cx.on_focus_out(&input_fh, window, |this: &mut Self, _event, window, cx| {
                // Only blur if neither input nor toggle has focus
                if !this.input_focus_handle.is_focused(window) && !this.toggle_focus_handle.is_focused(window) {
                    this.on_blur(cx);
                }
            }).detach();
        }

        // Detect focus-in
        if input_is_focused && !self.was_focused {
            self.on_focus(cx);
        }
        self.was_focused = input_is_focused;

        let render_scroll_offset = if input_is_focused { self.scroll_offset } else { 0.0 };

        // Set up blink timer when focused
        if input_is_focused && !self.blink_timer_active {
            self.blink_timer_active = true;
            let entity = cx.entity();
            let blink_period = CursorBlink::blink_period();
            window.spawn(cx, async move |async_cx| {
                loop {
                    smol::Timer::after(blink_period).await;
                    let should_continue = async_cx
                        .update_entity(&entity, |this, cx| {
                            if !this.blink_timer_active {
                                return false;
                            }
                            cx.notify();
                            true
                        })
                        .unwrap_or(false);
                    if !should_continue {
                        break;
                    }
                }
            }).detach();
        }

        if !input_is_focused {
            self.blink_timer_active = false;
        }

        // Apply auto-scroll if active
        if self.auto_scroll_active && self.is_dragging {
            self.apply_auto_scroll(window);
        }

        if input_is_focused {
            self.ensure_cursor_visible(window);
        }

        let display_content = self.display_content();
        let has_content = !self.core.content().is_empty();
        let placeholder = self.placeholder.clone();

        let cursor = self.core.cursor();
        let selection = self.core.selection();

        let cursor_x = self.x_for_cursor(cursor, window) - render_scroll_offset;
        let cursor_visible = input_is_focused && self.cursor_blink.is_visible();

        let selection_bounds: Option<(f32, f32)> = if input_is_focused {
            selection.and_then(|(start, end)| {
                if start != end {
                    let start_x = self.x_for_cursor(start, window) - render_scroll_offset;
                    let end_x = self.x_for_cursor(end, window) - render_scroll_offset;
                    Some((start_x, end_x - start_x))
                } else {
                    None
                }
            })
        } else {
            None
        };

        let scroll_offset = render_scroll_offset;

        // Colors
        let bg_color = if enabled { theme.bg_input } else { theme.disabled_bg };
        let border_color = if either_focused && enabled {
            theme.border_focus
        } else {
            theme.border_input
        };
        let separator_color = theme.text_muted;
        let button_text_color = if enabled { theme.text_muted } else { theme.disabled_text };
        let selection_color = theme.selection;
        let text_color = if enabled { theme.text_primary } else { theme.disabled_text };
        let text_placeholder = theme.text_placeholder;

        // Eye icons
        let eye_icon = if self.show_password { "\u{2296}" } else { "\u{25CE}" }; // ⊖ / ◎

        // Vertical separator
        let separator = div()
            .w(px(1.0))
            .h_full()
            .bg(rgb(separator_color));

        // Main container
        div()
            .id("ccf_password_input")
            .flex()
            .flex_row()
            .items_center()
            .h(px(28.0))
            .bg(rgb(bg_color))
            .border_1()
            .border_color(rgb(border_color))
            .rounded_md()
            .overflow_hidden()
            // Input area
            .child(
                div()
                    .id("ccf_password_input_field")
                    .key_context("CcfTextInput")
                    .track_focus(&input_focus_handle)
                    .flex_1()
                    .h_full()
                    .px_2()
                    .when(enabled, |d| d.cursor_text())
                    .when(!enabled, |d| d.cursor_default())
                    .relative()
                    .overflow_hidden()
                    // Navigation actions
                    .on_action(cx.listener(|this, _: &MoveLeft, _window, cx| {
                        if !this.enabled { return; }
                        this.handle_move_left(cx);
                    }))
                    .on_action(cx.listener(|this, _: &MoveRight, _window, cx| {
                        if !this.enabled { return; }
                        this.handle_move_right(cx);
                    }))
                    .on_action(cx.listener(|this, _: &MoveWordLeft, _window, cx| {
                        if !this.enabled { return; }
                        this.handle_move_word_left(cx);
                    }))
                    .on_action(cx.listener(|this, _: &MoveWordRight, _window, cx| {
                        if !this.enabled { return; }
                        this.handle_move_word_right(cx);
                    }))
                    .on_action(cx.listener(|this, _: &MoveToStart, _window, cx| {
                        if !this.enabled { return; }
                        this.handle_move_to_start(cx);
                    }))
                    .on_action(cx.listener(|this, _: &MoveToEnd, _window, cx| {
                        if !this.enabled { return; }
                        this.handle_move_to_end(cx);
                    }))
                    // Selection actions
                    .on_action(cx.listener(|this, _: &SelectLeft, _window, cx| {
                        if !this.enabled { return; }
                        this.handle_select_left(cx);
                    }))
                    .on_action(cx.listener(|this, _: &SelectRight, _window, cx| {
                        if !this.enabled { return; }
                        this.handle_select_right(cx);
                    }))
                    .on_action(cx.listener(|this, _: &SelectWordLeft, _window, cx| {
                        if !this.enabled { return; }
                        this.handle_select_word_left(cx);
                    }))
                    .on_action(cx.listener(|this, _: &SelectWordRight, _window, cx| {
                        if !this.enabled { return; }
                        this.handle_select_word_right(cx);
                    }))
                    .on_action(cx.listener(|this, _: &SelectToStart, _window, cx| {
                        if !this.enabled { return; }
                        this.handle_select_to_start(cx);
                    }))
                    .on_action(cx.listener(|this, _: &SelectToEnd, _window, cx| {
                        if !this.enabled { return; }
                        this.handle_select_to_end(cx);
                    }))
                    .on_action(cx.listener(|this, _: &SelectAll, _window, cx| {
                        if !this.enabled { return; }
                        this.handle_select_all(cx);
                    }))
                    // Delete actions
                    .on_action(cx.listener(|this, _: &DeleteBackward, _window, cx| {
                        if !this.enabled { return; }
                        this.handle_delete_backward(cx);
                    }))
                    .on_action(cx.listener(|this, _: &DeleteForward, _window, cx| {
                        if !this.enabled { return; }
                        this.handle_delete_forward(cx);
                    }))
                    .on_action(cx.listener(|this, _: &DeleteWordBackward, _window, cx| {
                        if !this.enabled { return; }
                        this.handle_delete_word_backward(cx);
                    }))
                    .on_action(cx.listener(|this, _: &DeleteWordForward, _window, cx| {
                        if !this.enabled { return; }
                        this.handle_delete_word_forward(cx);
                    }))
                    // Clipboard actions - Copy is disabled for security
                    .on_action(cx.listener(|this, _: &Cut, _window, cx| {
                        if !this.enabled { return; }
                        this.cut(cx);
                    }))
                    .on_action(cx.listener(|_this, _: &Copy, _window, _cx| {
                        // Intentionally empty - don't allow copying password
                    }))
                    .on_action(cx.listener(|this, _: &Paste, _window, cx| {
                        if !this.enabled { return; }
                        this.paste(cx);
                    }))
                    // Enter/Escape
                    .on_action(cx.listener(|this, _: &Enter, _window, cx| {
                        if !this.enabled { return; }
                        cx.emit(PasswordInputEvent::Enter);
                    }))
                    .on_action(cx.listener(|this, _: &Escape, _window, cx| {
                        if !this.enabled { return; }
                        this.on_blur(cx);
                    }))
                    // Focus navigation
                    .on_action(cx.listener(|_this, _: &FocusNext, window, _cx| {
                        window.focus_next();
                    }))
                    .on_action(cx.listener(|_this, _: &FocusPrev, window, _cx| {
                        window.focus_prev();
                    }))
                    // Character input
                    .on_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| {
                        if handle_tab_navigation(event, window) {
                            return;
                        }
                        if !this.enabled { return; }
                        if !event.keystroke.modifiers.alt
                            && !event.keystroke.modifiers.control
                            && !event.keystroke.modifiers.platform
                        {
                            if let Some(ref ch) = event.keystroke.key_char {
                                this.handle_insert_text(ch, cx);
                            }
                        }
                    }))
                    // Click to focus and position cursor
                    .when(enabled, |d| d.on_mouse_down(MouseButton::Left, cx.listener(|this, event: &MouseDownEvent, window, cx| {
                        let was_focused = this.input_focus_handle.is_focused(window);
                        this.input_focus_handle.focus(window);

                        if !was_focused && this.core.selection().is_some() {
                            this.reset_cursor_blink();
                            cx.notify();
                            return;
                        }

                        let click_x: f32 = event.position.x.into();
                        let relative_x = (click_x - this.content_origin_x).max(0.0);
                        let new_cursor = this.cursor_at_x(relative_x, window);

                        if event.modifiers.shift {
                            this.core.start_selection_from_cursor();
                            this.core.extend_selection_to(new_cursor);
                        } else {
                            this.core.clear_selection();
                            this.core.set_cursor(new_cursor);
                            this.core.start_selection_from_cursor();
                        }

                        this.is_dragging = true;
                        this.reset_cursor_blink();
                        cx.notify();
                    })))
                    // Drag to select
                    .when(enabled, |d| d.on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, window, cx| {
                        if !this.is_dragging {
                            return;
                        }
                        let mouse_x: f32 = event.position.x.into();
                        let scroll_speed = this.handle_drag_move(mouse_x, window);
                        this.spawn_auto_scroll_timer_if_needed(scroll_speed, window, cx);
                        cx.notify();
                    })))
                    // Mouse up ends drag
                    .when(enabled, |d| d.on_mouse_up(MouseButton::Left, cx.listener(|this, _event: &MouseUpEvent, _window, cx| {
                        this.stop_drag();
                        cx.notify();
                    })))
                    // Content
                    .child({
                        let entity = cx.entity();
                        let entity_paint = entity.clone();
                        let is_dragging = self.is_dragging;

                        div()
                            .size_full()
                            .flex()
                            .items_center()
                            .relative()
                            // Measurement canvas
                            .child(
                                canvas(
                                    move |bounds, _window, cx| {
                                        let width: f32 = bounds.size.width.into();
                                        let origin_x: f32 = bounds.origin.x.into();
                                        entity.update(cx, |this: &mut PasswordInput, _cx| {
                                            this.visible_width = width;
                                            this.content_origin_x = origin_x;
                                        });
                                    },
                                    {
                                        let entity = entity_paint;
                                        move |_bounds, _, window, _cx| {
                                            if is_dragging {
                                                let entity_move = entity.clone();
                                                window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
                                                    if phase != DispatchPhase::Capture {
                                                        return;
                                                    }
                                                    let mouse_x: f32 = event.position.x.into();
                                                    entity_move.update(cx, |this: &mut PasswordInput, cx| {
                                                        let scroll_speed = this.handle_drag_move(mouse_x, window);
                                                        this.spawn_auto_scroll_timer_if_needed(scroll_speed, window, cx);
                                                        cx.notify();
                                                    });
                                                });

                                                let entity_up = entity.clone();
                                                window.on_mouse_event(move |_event: &MouseUpEvent, phase, _window, cx| {
                                                    if phase != DispatchPhase::Capture {
                                                        return;
                                                    }
                                                    entity_up.update(cx, |this: &mut PasswordInput, cx| {
                                                        this.stop_drag();
                                                        cx.notify();
                                                    });
                                                });
                                            }
                                        }
                                    },
                                )
                                .size_full()
                                .absolute()
                            )
                            // Content layer
                            .child(
                                div()
                                    .relative()
                                    .h_full()
                                    .flex()
                                    .items_center()
                                    .min_w_0()
                                    // Selection highlight
                                    .when_some(selection_bounds, |d, (start_x, width)| {
                                        d.child(
                                            div()
                                                .absolute()
                                                .top_0()
                                                .bottom_0()
                                                .left(px(start_x))
                                                .w(px(width))
                                                .bg(rgb(selection_color))
                                        )
                                    })
                                    // Text content
                                    .child(
                                        div()
                                            .absolute()
                                            .left(px(-scroll_offset))
                                            .text_sm()
                                            .text_color(rgb(text_color))
                                            .whitespace_nowrap()
                                            .child(display_content.clone())
                                    )
                                    // Cursor
                                    .when(cursor_visible, |d| {
                                        d.child(
                                            div()
                                                .absolute()
                                                .top(px(4.))
                                                .bottom(px(4.))
                                                .left(px(cursor_x))
                                                .w(px(1.))
                                                .bg(rgb(text_color))
                                        )
                                    })
                            )
                            // Placeholder
                            .when(!has_content, |d| {
                                if let Some(ph) = placeholder {
                                    d.child(
                                        div()
                                            .absolute()
                                            .left_0()
                                            .text_sm()
                                            .text_color(rgb(text_placeholder))
                                            .child(ph)
                                    )
                                } else {
                                    d
                                }
                            })
                    })
            )
            .child(separator)
            // Toggle visibility button
            .child(
                div()
                    .id("password_toggle_button")
                    .flex()
                    .items_center()
                    .justify_center()
                    .w(px(28.0))
                    .h_full()
                    .cursor_for_enabled(enabled)
                    .text_color(rgb(button_text_color))
                    .when(toggle_is_focused && enabled, |d| d.bg(rgb(theme.bg_hover)))
                    .when(enabled, |d| d.hover(|d| d.bg(rgb(theme.bg_hover))))
                    .track_focus(&toggle_focus_handle)
                    .on_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| {
                        if handle_tab_navigation(event, window) {
                            return;
                        }
                        if matches!(event.keystroke.key.as_str(), "enter" | "space") {
                            if !this.enabled { return; }
                            this.toggle_visibility(cx);
                        }
                    }))
                    .when(enabled, |d| d.on_click(cx.listener(|this, _event, _window, cx| {
                        this.toggle_visibility(cx);
                    })))
                    .child(
                        div()
                            .text_sm()
                            .child(eye_icon)
                    )
            )
    }
}