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