Skip to main content

gpui_form_component/
infinite_select.rs

1//! Infinite-select runtime support for nested enum trees.
2//!
3//! This module exposes both the low-level trait and path helpers used by
4//! generated code and a higher-level `Select` entity that owns the
5//! cascading `SelectState`s for a field.
6
7mod path;
8mod state_helpers;
9mod value;
10
11pub use path::{
12    InfiniteSelectKeyPath, InfiniteSelectKeyPathParseError, InfiniteSelectKeyPathParseErrorReason,
13    InfiniteSelectPath, InfiniteSelectPathError, InfiniteSelectPathErrorReason,
14    InfiniteSelectPathSegment, build_from_key_path, build_from_path, key_path_from_value,
15    path_from_value,
16};
17use state_helpers::{
18    build_child_selects, build_levels, build_select_state, first_changed_depth, selected_index,
19};
20pub use value::{InfiniteSelectItem, InfiniteSelectValue, to_select_items};
21
22use gpui_kit::component::{
23    IndexPath,
24    form::{Field, field},
25    select::{Select as GpuiSelect, SelectDelegate, SelectEvent, SelectItem, SelectState},
26};
27use gpui_kit::{
28    App, AppContext as _, Context, Empty, Entity, EventEmitter, FocusHandle, Focusable,
29    IntoElement, ParentElement as _, Render, RenderOnce, SharedString, Styled as _, Subscription,
30    Window, div,
31};
32
33/// Options for the runtime `Select`.
34#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
35#[cfg_attr(feature = "component-shape", derive(bon::Builder))]
36pub struct InfiniteSelectOptions {
37    #[cfg_attr(feature = "component-shape", builder(default))]
38    searchable: bool,
39    max_depth: Option<usize>,
40}
41
42impl InfiniteSelectOptions {
43    /// Creates runtime options for `Select`.
44    pub const fn new(searchable: bool, max_depth: Option<usize>) -> Self {
45        Self {
46            searchable,
47            max_depth,
48        }
49    }
50}
51
52/// Event emitted by `Select` whenever the selection changes.
53#[derive(Clone)]
54pub struct InfiniteSelectEvent<T: InfiniteSelectValue> {
55    previous_value: T,
56    previous_path: InfiniteSelectPath,
57    previous_key_path: InfiniteSelectKeyPath,
58    value: T,
59    path: InfiniteSelectPath,
60    key_path: InfiniteSelectKeyPath,
61    changed_depth: usize,
62}
63
64impl<T: InfiniteSelectValue> InfiniteSelectEvent<T> {
65    /// Returns the concrete selection value before this change.
66    pub fn previous_value(&self) -> &T {
67        &self.previous_value
68    }
69
70    /// Returns the index path before this change.
71    pub fn previous_path(&self) -> &InfiniteSelectPath {
72        &self.previous_path
73    }
74
75    /// Returns the key path before this change.
76    pub fn previous_key_path(&self) -> &InfiniteSelectKeyPath {
77        &self.previous_key_path
78    }
79
80    /// Returns the rebuilt concrete selection value.
81    pub fn value(&self) -> &T {
82        &self.value
83    }
84
85    /// Consumes the event and returns the rebuilt concrete selection value.
86    pub fn into_value(self) -> T {
87        self.value
88    }
89
90    /// Returns the current index path.
91    pub fn path(&self) -> &InfiniteSelectPath {
92        &self.path
93    }
94
95    /// Returns the current key path.
96    pub fn key_path(&self) -> &InfiniteSelectKeyPath {
97        &self.key_path
98    }
99
100    /// Returns the first depth that changed for this selection event.
101    pub fn changed_depth(&self) -> usize {
102        self.changed_depth
103    }
104}
105
106/// A single rendered level of an infinite-select field.
107#[derive(Clone)]
108pub struct InfiniteSelectLevel<D>
109where
110    D: SelectDelegate + 'static,
111{
112    depth: usize,
113    label: SharedString,
114    description: SharedString,
115    select: Entity<SelectState<D>>,
116    selected_index: Option<usize>,
117    selected_key: Option<String>,
118}
119
120impl<D> InfiniteSelectLevel<D>
121where
122    D: SelectDelegate + 'static,
123{
124    /// Returns the rendered depth for this select level.
125    pub fn depth(&self) -> usize {
126        self.depth
127    }
128
129    /// Returns true when this level is the root select.
130    pub fn is_root(&self) -> bool {
131        self.depth == 0
132    }
133
134    /// Returns the field label for this level.
135    pub fn label(&self) -> &SharedString {
136        &self.label
137    }
138
139    /// Returns the field description for this level.
140    pub fn description(&self) -> &SharedString {
141        &self.description
142    }
143
144    /// Returns the backing select entity for this level.
145    pub fn select(&self) -> Entity<SelectState<D>> {
146        self.select.clone()
147    }
148
149    /// Returns the selected index for this level, when available.
150    pub fn selected_index(&self) -> Option<usize> {
151        self.selected_index
152    }
153
154    /// Returns the selected stable key for this level, when available.
155    pub fn selected_key(&self) -> Option<&str> {
156        self.selected_key.as_deref()
157    }
158
159    /// Builds a `gpui_kit::component::form::Field` for this select level.
160    pub fn to_form_field(&self) -> Field {
161        let label = self.label.clone();
162        let description = self.description.clone();
163        let select = self.select.clone();
164
165        field()
166            .label(label)
167            .description_fn(move |_, _| {
168                div()
169                    .flex()
170                    .flex_col()
171                    .gap_1()
172                    .child(div().child(description.clone()))
173            })
174            .child(GpuiSelect::new(&select))
175    }
176}
177
178/// An owned snapshot of the current infinite-select runtime state.
179#[derive(Clone)]
180pub struct InfiniteSelectSnapshot<T, D>
181where
182    D: SelectDelegate + 'static,
183{
184    value: T,
185    path: InfiniteSelectPath,
186    key_path: InfiniteSelectKeyPath,
187    levels: Vec<InfiniteSelectLevel<D>>,
188}
189
190impl<T, D> InfiniteSelectSnapshot<T, D>
191where
192    T: InfiniteSelectValue,
193    D: SelectDelegate + 'static,
194{
195    /// Returns the concrete selected value.
196    pub fn value(&self) -> &T {
197        &self.value
198    }
199
200    /// Returns the current index-based selection path.
201    pub fn path(&self) -> &InfiniteSelectPath {
202        &self.path
203    }
204
205    /// Returns the current key-based selection path.
206    pub fn key_path(&self) -> &InfiniteSelectKeyPath {
207        &self.key_path
208    }
209
210    /// Returns the rendered select levels in root-to-leaf order.
211    pub fn levels(&self) -> &[InfiniteSelectLevel<D>] {
212        &self.levels
213    }
214
215    /// Consumes the snapshot and returns the owned level list.
216    pub fn into_levels(self) -> Vec<InfiniteSelectLevel<D>> {
217        self.levels
218    }
219
220    /// Returns render-ready GPUI form fields for each select level.
221    pub fn form_fields(&self) -> Vec<Field> {
222        self.levels
223            .iter()
224            .map(InfiniteSelectLevel::to_form_field)
225            .collect()
226    }
227}
228
229/// Runtime state for a cascading infinite-select field.
230pub struct InfiniteSelectState<T, D = Vec<InfiniteSelectItem<T>>>
231where
232    T: InfiniteSelectValue,
233    D: SelectDelegate<Item = InfiniteSelectItem<T>> + From<Vec<InfiniteSelectItem<T>>> + 'static,
234{
235    value: T,
236    path: InfiniteSelectPath,
237    key_path: InfiniteSelectKeyPath,
238    master_select: Entity<SelectState<D>>,
239    child_selects: Vec<Entity<SelectState<D>>>,
240    options: InfiniteSelectOptions,
241    _master_subscription: Subscription,
242    _child_subscriptions: Vec<Subscription>,
243}
244
245impl<T, D> Focusable for InfiniteSelectState<T, D>
246where
247    T: InfiniteSelectValue,
248    D: SelectDelegate<Item = InfiniteSelectItem<T>> + From<Vec<InfiniteSelectItem<T>>> + 'static,
249{
250    fn focus_handle(&self, cx: &App) -> FocusHandle {
251        self.master_select.read(cx).focus_handle(cx)
252    }
253}
254
255impl<T, D> EventEmitter<InfiniteSelectEvent<T>> for InfiniteSelectState<T, D>
256where
257    T: InfiniteSelectValue,
258    D: SelectDelegate<Item = InfiniteSelectItem<T>> + From<Vec<InfiniteSelectItem<T>>> + 'static,
259{
260}
261
262impl<T, D> InfiniteSelectState<T, D>
263where
264    T: InfiniteSelectValue,
265    D: SelectDelegate<Item = InfiniteSelectItem<T>> + From<Vec<InfiniteSelectItem<T>>> + 'static,
266{
267    /// Creates a new state from `T::default()`.
268    pub fn new_default(window: &mut Window, cx: &mut Context<Self>) -> Self {
269        Self::new(T::default(), window, cx)
270    }
271
272    /// Creates a new state from the given initial value.
273    pub fn new(initial_value: T, window: &mut Window, cx: &mut Context<Self>) -> Self {
274        Self::new_with_options(initial_value, InfiniteSelectOptions::default(), window, cx)
275    }
276
277    /// Creates a new state with explicit options.
278    pub fn new_with_options(
279        initial_value: T,
280        options: InfiniteSelectOptions,
281        window: &mut Window,
282        cx: &mut Context<Self>,
283    ) -> Self {
284        let path = path_from_value(&initial_value);
285        let key_path = key_path_from_value(&initial_value);
286        let root_selected = path.get(0);
287        let master_select = cx.new(|cx| {
288            build_select_state::<T, D>(
289                to_select_items::<T>(cx),
290                root_selected,
291                options.searchable,
292                window,
293                cx,
294            )
295        });
296        let master_subscription = cx.subscribe_in(&master_select, window, Self::on_select_event);
297
298        let mut this = Self {
299            value: initial_value,
300            path,
301            key_path,
302            master_select,
303            child_selects: Vec::new(),
304            options,
305            _master_subscription: master_subscription,
306            _child_subscriptions: Vec::new(),
307        };
308        this.rebuild_child_selects(window, cx);
309        this
310    }
311
312    /// Returns the current concrete selection.
313    pub fn value(&self) -> &T {
314        &self.value
315    }
316
317    /// Returns the current index-based selection path.
318    pub fn path(&self) -> &InfiniteSelectPath {
319        &self.path
320    }
321
322    /// Returns the current key-based selection path.
323    pub fn key_path(&self) -> &InfiniteSelectKeyPath {
324        &self.key_path
325    }
326
327    /// Returns the selected index at the given depth.
328    pub fn selected_index_at_depth(&self, depth: usize) -> Option<usize> {
329        self.path.get(depth)
330    }
331
332    /// Returns the selected key at the given depth.
333    pub fn selected_key_at_depth(&self, depth: usize) -> Option<&str> {
334        self.key_path.get(depth)
335    }
336
337    /// Returns the current rendered select levels in root-to-leaf order.
338    pub fn levels(&self, cx: &impl std::borrow::Borrow<App>) -> Vec<InfiniteSelectLevel<D>> {
339        build_levels(
340            &self.value,
341            &self.path,
342            &self.key_path,
343            &self.master_select,
344            &self.child_selects,
345            cx,
346        )
347    }
348
349    /// Returns an owned snapshot of the value, paths, and rendered levels.
350    pub fn snapshot(&self, cx: &impl std::borrow::Borrow<App>) -> InfiniteSelectSnapshot<T, D> {
351        InfiniteSelectSnapshot {
352            value: self.value.clone(),
353            path: self.path.clone(),
354            key_path: self.key_path.clone(),
355            levels: self.levels(cx),
356        }
357    }
358
359    /// Returns render-ready GPUI form fields for each visible select level.
360    pub fn form_fields(&self, cx: &impl std::borrow::Borrow<App>) -> Vec<Field> {
361        self.levels(cx)
362            .into_iter()
363            .map(|level| level.to_form_field())
364            .collect()
365    }
366
367    /// Returns the root select entity.
368    pub fn master_select(&self) -> Entity<SelectState<D>> {
369        self.master_select.clone()
370    }
371
372    /// Returns the currently visible child selects.
373    pub fn child_selects(&self) -> Vec<Entity<SelectState<D>>> {
374        self.child_selects.clone()
375    }
376
377    /// Programmatically sets the current selection.
378    pub fn set_value(&mut self, value: T, window: &mut Window, cx: &mut Context<Self>) {
379        self.apply_selection(value, None, false, window, cx);
380    }
381
382    /// Programmatically sets the current selection from an index path.
383    pub fn set_path(
384        &mut self,
385        path: &InfiniteSelectPath,
386        window: &mut Window,
387        cx: &mut Context<Self>,
388    ) -> Result<(), InfiniteSelectPathError> {
389        let value = build_from_path::<T>(path)?;
390        self.apply_selection(value, None, false, window, cx);
391        Ok(())
392    }
393
394    /// Programmatically sets the current selection from a key path.
395    pub fn set_key_path(
396        &mut self,
397        key_path: &InfiniteSelectKeyPath,
398        window: &mut Window,
399        cx: &mut Context<Self>,
400    ) -> Result<(), InfiniteSelectPathError> {
401        let value = build_from_key_path::<T>(key_path)?;
402        self.apply_selection(value, None, false, window, cx);
403        Ok(())
404    }
405
406    /// Programmatically changes one selection index and resets deeper levels to defaults.
407    pub fn set_selected_index_at_depth(
408        &mut self,
409        depth: usize,
410        index: usize,
411        window: &mut Window,
412        cx: &mut Context<Self>,
413    ) -> Result<(), InfiniteSelectPathError> {
414        if depth > self.path.len() {
415            return Err(InfiniteSelectPathError::missing_selection_options(
416                depth,
417                InfiniteSelectPathSegment::Index(index),
418            ));
419        }
420
421        let mut path = self.path.clone();
422        path.set(depth, index);
423        self.set_path(&path, window, cx)
424    }
425
426    /// Programmatically changes one selection key and resets deeper levels to defaults.
427    pub fn set_selected_key_at_depth(
428        &mut self,
429        depth: usize,
430        key: impl Into<String>,
431        window: &mut Window,
432        cx: &mut Context<Self>,
433    ) -> Result<(), InfiniteSelectPathError> {
434        let key = key.into();
435        if depth > self.key_path.len() {
436            return Err(InfiniteSelectPathError::missing_selection_options(
437                depth,
438                InfiniteSelectPathSegment::Key(key),
439            ));
440        }
441
442        let mut key_path = self.key_path.clone();
443        key_path.set(depth, key);
444        self.set_key_path(&key_path, window, cx)
445    }
446
447    fn resolved_max_depth(&self) -> usize {
448        match self.options.max_depth {
449            Some(max_depth) => max_depth.clamp(1, T::depth()),
450            None => T::depth(),
451        }
452    }
453
454    fn on_select_event(
455        &mut self,
456        this: &Entity<SelectState<D>>,
457        event: &SelectEvent<D>,
458        window: &mut Window,
459        cx: &mut Context<Self>,
460    ) {
461        let SelectEvent::Confirm(Some(selected)) = event else {
462            return;
463        };
464
465        let changed_depth = self
466            .select_depth(this)
467            .or_else(|| Some(first_changed_depth(&self.path, &selected.selection_path())));
468
469        self.apply_selection(selected.clone(), changed_depth, true, window, cx);
470    }
471
472    fn select_depth(&self, this: &Entity<SelectState<D>>) -> Option<usize> {
473        if &self.master_select == this {
474            Some(0)
475        } else {
476            self.child_selects
477                .iter()
478                .position(|child| child == this)
479                .map(|position| position + 1)
480        }
481    }
482
483    fn apply_selection(
484        &mut self,
485        value: T,
486        changed_depth: Option<usize>,
487        emit: bool,
488        window: &mut Window,
489        cx: &mut Context<Self>,
490    ) {
491        let new_path = path_from_value(&value);
492        let new_key_path = key_path_from_value(&value);
493        let changed_depth =
494            changed_depth.unwrap_or_else(|| first_changed_depth(&self.path, &new_path));
495
496        let previous_value = std::mem::replace(&mut self.value, value);
497        let previous_path = std::mem::replace(&mut self.path, new_path);
498        let previous_key_path = std::mem::replace(&mut self.key_path, new_key_path);
499        self.sync_master_select(window, cx);
500        self.rebuild_child_selects(window, cx);
501        if emit {
502            cx.emit(InfiniteSelectEvent {
503                previous_value,
504                previous_path,
505                previous_key_path,
506                value: self.value.clone(),
507                path: self.path.clone(),
508                key_path: self.key_path.clone(),
509                changed_depth,
510            });
511        }
512        cx.notify();
513    }
514
515    fn sync_master_select(&mut self, window: &mut Window, cx: &mut Context<Self>) {
516        let selected_index = selected_index(self.path.get(0).unwrap_or(0));
517        self.master_select.update(cx, |state, cx| {
518            state.set_selected_index(selected_index, window, cx);
519        });
520    }
521
522    fn rebuild_child_selects(&mut self, window: &mut Window, cx: &mut Context<Self>) {
523        let child_selects = build_child_selects::<T, D>(
524            &self.value,
525            &self.path,
526            self.resolved_max_depth(),
527            self.options.searchable,
528            window,
529            cx,
530        );
531
532        self._child_subscriptions = child_selects
533            .iter()
534            .map(|child| cx.subscribe_in(child, window, Self::on_select_event))
535            .collect();
536        self.child_selects = child_selects;
537    }
538}
539
540/// Render wrapper used by generated form code for infinite-select fields.
541#[cfg_attr(
542    feature = "component-shape",
543    derive(component_shape_gpui::GpuiComponentShape)
544)]
545#[cfg_attr(
546    feature = "component-shape",
547    gpui_component_shape(
548        state = InfiniteSelectState<T, D>,
549        new = InfiniteSelectState::<T, D>::new_default,
550        value = T,
551        field_suffix = "infinite_select",
552        value_binding
553    )
554)]
555#[derive(IntoElement)]
556pub struct InfiniteSelect<T, D = Vec<InfiniteSelectItem<T>>>
557where
558    T: InfiniteSelectValue,
559    D: SelectDelegate<Item = InfiniteSelectItem<T>> + From<Vec<InfiniteSelectItem<T>>> + 'static,
560{
561    state: Entity<InfiniteSelectState<T, D>>,
562}
563
564#[cfg(feature = "component-shape")]
565impl<T, D> gpui_form_runtime::shape::GpuiFormComponentShapePolicy for InfiniteSelect<T, D>
566where
567    T: InfiniteSelectValue,
568    D: SelectDelegate<Item = InfiniteSelectItem<T>> + From<Vec<InfiniteSelectItem<T>>> + 'static,
569{
570    type ValueStoragePolicy = gpui_form_runtime::shape::DirectValueStorage;
571}
572
573impl<T, D> InfiniteSelect<T, D>
574where
575    T: InfiniteSelectValue,
576    D: SelectDelegate<Item = InfiniteSelectItem<T>> + From<Vec<InfiniteSelectItem<T>>> + 'static,
577{
578    #[cfg(feature = "component-shape")]
579    pub fn searchable(searchable: bool) -> InfiniteSelectOptions {
580        InfiniteSelectOptions::builder()
581            .searchable(searchable)
582            .build()
583    }
584
585    #[cfg(feature = "component-shape")]
586    pub fn from(options: InfiniteSelectOptions) -> InfiniteSelectOptions {
587        options
588    }
589
590    pub fn new(state: &Entity<InfiniteSelectState<T, D>>) -> Self {
591        Self {
592            state: state.clone(),
593        }
594    }
595}
596
597#[cfg(feature = "component-shape")]
598impl<T, D> component_shape_gpui::GpuiComponentShapeBuilder<InfiniteSelect<T, D>>
599    for InfiniteSelectOptions
600where
601    T: InfiniteSelectValue,
602    D: SelectDelegate<Item = InfiniteSelectItem<T>> + From<Vec<InfiniteSelectItem<T>>> + 'static,
603{
604    fn build(
605        self,
606        window: &mut Window,
607        cx: &mut Context<'_, InfiniteSelectState<T, D>>,
608    ) -> InfiniteSelectState<T, D> {
609        InfiniteSelectState::<T, D>::new_with_options(T::default(), self, window, cx)
610    }
611}
612
613impl<T, D> RenderOnce for InfiniteSelect<T, D>
614where
615    T: InfiniteSelectValue,
616    D: SelectDelegate<Item = InfiniteSelectItem<T>> + From<Vec<InfiniteSelectItem<T>>> + 'static,
617{
618    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
619        div().children(self.state.read(cx).form_fields(cx))
620    }
621}
622
623#[cfg(feature = "component-shape")]
624impl<T, D> gpui_form_runtime::shape::GpuiComponentStateValueBinding<T> for InfiniteSelectState<T, D>
625where
626    T: InfiniteSelectValue,
627    D: SelectDelegate<Item = InfiniteSelectItem<T>> + From<Vec<InfiniteSelectItem<T>>> + 'static,
628{
629    type Event = InfiniteSelectEvent<T>;
630
631    fn seed_value_binding_state(
632        state: &mut Self,
633        value: Option<&T>,
634        window: &mut Window,
635        cx: &mut Context<'_, Self>,
636    ) {
637        if let Some(value) = value {
638            state.set_value(value.clone(), window, cx);
639        }
640    }
641
642    fn value_change(
643        _state: &Self,
644        event: &Self::Event,
645    ) -> gpui_form_runtime::shape::ValueChange<T> {
646        gpui_form_runtime::shape::ValueChange::Set(event.value().clone())
647    }
648}
649
650impl<T, D> Render for InfiniteSelectState<T, D>
651where
652    T: InfiniteSelectValue,
653    D: SelectDelegate<Item = InfiniteSelectItem<T>> + From<Vec<InfiniteSelectItem<T>>> + 'static,
654{
655    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
656        Empty
657    }
658}