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
//! Repeatable directory picker widget - allows selecting multiple directories with add/remove buttons
//!
//! A widget that manages a list of directory path inputs, allowing users to add and remove entries.
//! Each entry is a full DirectoryPicker widget supporting folder browsing dialogs and drag-drop.
//!
//! Requires the `file-picker` feature.
//!
//! # Example
//!
//! ```ignore
//! use ccf_gpui_widgets::widgets::{
//!     RepeatableDirectoryPicker, RepeatableDirectoryPickerEvent
//! };
//!
//! let picker = cx.new(|cx| {
//!     RepeatableDirectoryPicker::new(cx)
//!         .with_values(vec!["/path/to/dir1".to_string()])
//!         .placeholder("Select directory...")
//!         .min_entries(1)
//! });
//!
//! cx.subscribe(&picker, |this, _, event: &RepeatableDirectoryPickerEvent, cx| {
//!     match event {
//!         RepeatableDirectoryPickerEvent::Change(values) => {
//!             println!("Directories: {:?}", values);
//!         }
//!         RepeatableDirectoryPickerEvent::EntryAdded(index) => {
//!             println!("Added entry at index {}", index);
//!         }
//!         RepeatableDirectoryPickerEvent::EntryRemoved(index) => {
//!             println!("Removed entry at index {}", index);
//!         }
//!     }
//! }).detach();
//! ```

use gpui::prelude::*;
use gpui::*;
use crate::theme::{get_theme, Theme};
use super::directory_picker::{
    DirectoryPicker, DirectoryPickerEvent,
    DirectoryPickerValidation, ValidationDisplay,
};
use super::focus_navigation::{repeatable_add_button, repeatable_remove_button};

/// Events emitted by RepeatableDirectoryPicker
#[derive(Debug, Clone)]
pub enum RepeatableDirectoryPickerEvent {
    /// Values changed (includes all current values)
    Change(Vec<String>),
    /// A new entry was added at the given index
    EntryAdded(usize),
    /// An entry was removed from the given index
    EntryRemoved(usize),
}

/// Repeatable directory picker widget
///
/// Manages a dynamic list of DirectoryPicker widgets with add/remove controls.
pub struct RepeatableDirectoryPicker {
    // Configuration (applied to all entries)
    placeholder: Option<SharedString>,
    browse_shortcut_enabled: bool,
    validation_display: ValidationDisplay,

    /// Initial values to populate on first render
    initial_values: Vec<String>,
    /// Each entry is a DirectoryPicker entity
    entries: Vec<Entity<DirectoryPicker>>,
    /// Focus handles for remove buttons (one per entry)
    remove_focus_handles: Vec<FocusHandle>,
    /// Focus handle for the add button
    add_focus_handle: FocusHandle,
    /// Whether entries have been initialized
    initialized: bool,
    /// Minimum number of entries (cannot remove below this)
    min_entries: usize,
    custom_theme: Option<Theme>,
    /// Whether the widget is enabled (interactive)
    enabled: bool,
    /// Prevents double-trigger when Space/Enter activates both on_action and on_click.
    /// See focus_navigation.rs module comment for details. DO NOT REMOVE.
    action_just_handled: bool,
}

impl RepeatableDirectoryPicker {
    /// Create a new repeatable directory picker
    pub fn new(cx: &mut Context<Self>) -> Self {
        Self {
            placeholder: None,
            browse_shortcut_enabled: true,
            validation_display: ValidationDisplay::default(),
            initial_values: Vec::new(),
            entries: Vec::new(),
            remove_focus_handles: Vec::new(),
            add_focus_handle: cx.focus_handle().tab_stop(true),
            initialized: false,
            min_entries: 1,
            custom_theme: None,
            enabled: true,
            action_just_handled: false,
        }
    }

    /// Set initial values
    #[must_use]
    pub fn with_values(mut self, values: Vec<String>) -> Self {
        self.initial_values = values;
        self
    }

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

    /// Enable or disable Cmd+O / Ctrl+O browse shortcut (builder pattern)
    ///
    /// The shortcut is enabled by default. Disable it if your application
    /// uses Cmd+O for another purpose (e.g., opening files at the app level).
    #[must_use]
    pub fn browse_shortcut(mut self, enabled: bool) -> Self {
        self.browse_shortcut_enabled = enabled;
        self
    }

    /// Set how validation feedback is displayed (builder pattern)
    ///
    /// Controls whether path coloring and/or explanation messages are shown.
    /// Default is `ValidationDisplay::Full` (show both).
    #[must_use]
    pub fn validation_display(mut self, display: ValidationDisplay) -> Self {
        self.validation_display = display;
        self
    }

    /// Set minimum number of entries (default: 1)
    #[must_use]
    pub fn min_entries(mut self, min: usize) -> Self {
        self.min_entries = min.max(1);
        self
    }

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

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

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

    /// Set enabled state programmatically
    pub fn set_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
        if self.enabled != enabled {
            self.enabled = enabled;
            // Update child entries
            for entry in &self.entries {
                entry.update(cx, |e, cx| e.set_enabled(enabled, cx));
            }
            cx.notify();
        }
    }

    /// Get all non-empty values
    pub fn values(&self, cx: &App) -> Vec<String> {
        self.entries
            .iter()
            .map(|entry| entry.read(cx).value().to_string())
            .filter(|s| !s.is_empty())
            .collect()
    }

    /// Get access to the underlying DirectoryPicker entries
    pub fn entries(&self) -> &[Entity<DirectoryPicker>] {
        &self.entries
    }

    /// Validate all entries and return their validation states
    pub fn validate_all(&self, cx: &App) -> Vec<DirectoryPickerValidation> {
        self.entries
            .iter()
            .map(|entry| entry.read(cx).validate())
            .collect()
    }

    /// Returns true if all non-empty entries are valid
    pub fn is_all_valid(&self, cx: &App) -> bool {
        self.entries
            .iter()
            .all(|entry| {
                let picker = entry.read(cx);
                picker.value().is_empty() || picker.is_valid()
            })
    }

    /// Create a new DirectoryPicker entry with current configuration
    fn create_entry(&self, value: Option<&str>, cx: &mut Context<Self>) -> Entity<DirectoryPicker> {
        let placeholder = self.placeholder.clone();
        let browse_shortcut_enabled = self.browse_shortcut_enabled;
        let validation_display = self.validation_display.clone();
        let theme = self.custom_theme;
        let enabled = self.enabled;

        let picker = cx.new(|cx| {
            let mut p = DirectoryPicker::new(cx)
                .browse_shortcut(browse_shortcut_enabled)
                .validation_display(validation_display)
                .with_enabled(enabled);

            if let Some(ph) = placeholder {
                p = p.placeholder(ph);
            }
            if let Some(th) = theme {
                p = p.theme(th);
            }
            p
        });

        if let Some(v) = value.filter(|s| !s.is_empty()) {
            picker.update(cx, |p, cx| {
                p.set_value(v, cx);
            });
        }

        // Subscribe to changes to emit our own change events
        cx.subscribe(&picker, |this, _picker, event: &DirectoryPickerEvent, cx| {
            let DirectoryPickerEvent::Change(_) = event;
            let values = this.values(cx);
            cx.emit(RepeatableDirectoryPickerEvent::Change(values));
        }).detach();

        picker
    }

    /// Initialize entries from initial values (called during first render)
    fn initialize_entries(&mut self, cx: &mut Context<Self>) {
        if self.initialized {
            return;
        }
        self.initialized = true;

        let values = std::mem::take(&mut self.initial_values);
        let values = if values.is_empty() {
            vec![String::new(); self.min_entries]
        } else if values.len() < self.min_entries {
            let mut v = values;
            v.resize(self.min_entries, String::new());
            v
        } else {
            values
        };

        for value in values {
            let entry = self.create_entry(Some(&value), cx);
            self.entries.push(entry);
            self.remove_focus_handles.push(cx.focus_handle().tab_stop(true));
        }
    }

    fn add_entry(&mut self, cx: &mut Context<Self>) {
        let index = self.entries.len();
        let entry = self.create_entry(None, cx);
        self.entries.push(entry);
        self.remove_focus_handles.push(cx.focus_handle().tab_stop(true));
        cx.emit(RepeatableDirectoryPickerEvent::EntryAdded(index));
        cx.emit(RepeatableDirectoryPickerEvent::Change(self.values(cx)));
        cx.notify();
    }

    fn remove_entry(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
        if self.entries.len() > self.min_entries && index < self.entries.len() {
            // Check if the remove button being pressed has focus
            let had_focus = self.remove_focus_handles[index].is_focused(window);

            self.entries.remove(index);
            self.remove_focus_handles.remove(index);

            // Move focus if the removed button had focus
            if had_focus {
                if self.entries.len() <= self.min_entries {
                    // No more "-" buttons visible, focus the first entry's picker
                    self.entries[0].update(cx, |picker, cx| picker.focus(cx));
                } else if index > 0 {
                    // Focus the previous entry's "-" button
                    self.remove_focus_handles[index - 1].focus(window);
                } else {
                    // Removed first entry, focus the new first entry's "-" button
                    self.remove_focus_handles[0].focus(window);
                }
            }

            cx.emit(RepeatableDirectoryPickerEvent::EntryRemoved(index));
            cx.emit(RepeatableDirectoryPickerEvent::Change(self.values(cx)));
            cx.notify();
        }
    }

    fn get_theme(&self, cx: &App) -> Theme {
        self.custom_theme.unwrap_or_else(|| get_theme(cx))
    }
}

impl EventEmitter<RepeatableDirectoryPickerEvent> for RepeatableDirectoryPicker {}

impl Render for RepeatableDirectoryPicker {
    fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
        // Initialize entries on first render
        self.initialize_entries(cx);

        let theme = self.get_theme(cx);
        let entries_count = self.entries.len();
        let can_remove = entries_count > self.min_entries;
        let add_focused = self.add_focus_handle.is_focused(window);
        let enabled = self.enabled;

        // Collect entries with their remove button focus handles
        let entry_data: Vec<_> = self.entries.iter()
            .zip(self.remove_focus_handles.iter())
            .enumerate()
            .map(|(index, (entry, focus_handle))| {
                let is_focused = focus_handle.is_focused(window);
                (index, entry.clone(), focus_handle.clone(), is_focused)
            })
            .collect();

        div()
            .flex()
            .flex_col()
            .gap_2()
            .child(
                // Entries list
                div()
                    .flex()
                    .flex_col()
                    .gap_2()
                    .children(entry_data.into_iter().map(|(index, entry, focus_handle, is_focused)| {
                        let remove_button = repeatable_remove_button(
                            format!("dir_remove_{}", index),
                            &focus_handle,
                            &theme,
                            enabled,
                            is_focused,
                            // on_action: set flag, then perform action
                            move |this: &mut Self, window, cx| {
                                this.action_just_handled = true;
                                this.remove_entry(index, window, cx);
                            },
                            // on_click: skip if action just handled, otherwise perform action
                            move |this: &mut Self, window, cx| {
                                if this.action_just_handled {
                                    this.action_just_handled = false;
                                    return;
                                }
                                this.remove_entry(index, window, cx);
                            },
                            cx,
                        );

                        div()
                            .flex()
                            .flex_row()
                            .items_center()
                            .gap_2()
                            .child(
                                // DirectoryPicker widget
                                div()
                                    .flex_1()
                                    .child(entry)
                            )
                            .when(can_remove, |d| d.child(remove_button))
                    }))
            )
            .child(
                // Add button row
                div()
                    .flex()
                    .flex_row()
                    .child(
                        repeatable_add_button(
                            "repeatable_dir_add_button",
                            &self.add_focus_handle,
                            &theme,
                            enabled,
                            add_focused,
                            // on_action: set flag, then perform action
                            |this: &mut Self, _window, cx| {
                                this.action_just_handled = true;
                                this.add_entry(cx);
                            },
                            // on_click: skip if action just handled, otherwise perform action
                            |this: &mut Self, _window, cx| {
                                if this.action_just_handled {
                                    this.action_just_handled = false;
                                    return;
                                }
                                this.add_entry(cx);
                            },
                            cx,
                        )
                    )
            )
    }
}