settings_ui.rs

  1use std::{
  2    num::NonZeroU32,
  3    ops::{Not, Range},
  4    rc::Rc,
  5};
  6
  7use anyhow::Context as _;
  8use editor::Editor;
  9use feature_flags::{FeatureFlag, FeatureFlagAppExt};
 10use gpui::{App, Entity, EventEmitter, FocusHandle, Focusable, ReadGlobal, ScrollHandle, actions};
 11use settings::{
 12    NumType, SettingsStore, SettingsUiEntry, SettingsUiEntryMetaData, SettingsUiItem,
 13    SettingsUiItemDynamicMap, SettingsUiItemGroup, SettingsUiItemSingle, SettingsUiItemUnion,
 14    SettingsValue,
 15};
 16use smallvec::SmallVec;
 17use ui::{
 18    ContextMenu, DropdownMenu, NumericStepper, SwitchField, ToggleButtonGroup, ToggleButtonSimple,
 19    prelude::*,
 20};
 21use workspace::{
 22    Workspace,
 23    item::{Item, ItemEvent},
 24};
 25
 26pub struct SettingsUiFeatureFlag;
 27
 28impl FeatureFlag for SettingsUiFeatureFlag {
 29    const NAME: &'static str = "settings-ui";
 30}
 31
 32actions!(
 33    zed,
 34    [
 35        /// Opens settings UI.
 36        OpenSettingsUi
 37    ]
 38);
 39
 40pub fn open_settings_editor(
 41    workspace: &mut Workspace,
 42    _: &OpenSettingsUi,
 43    window: &mut Window,
 44    cx: &mut Context<Workspace>,
 45) {
 46    // todo(settings_ui) open in a local workspace if this is remote.
 47    let existing = workspace
 48        .active_pane()
 49        .read(cx)
 50        .items()
 51        .find_map(|item| item.downcast::<SettingsPage>());
 52
 53    if let Some(existing) = existing {
 54        workspace.activate_item(&existing, true, true, window, cx);
 55    } else {
 56        let settings_page = SettingsPage::new(workspace, cx);
 57        workspace.add_item_to_active_pane(Box::new(settings_page), None, true, window, cx)
 58    }
 59}
 60
 61pub fn init(cx: &mut App) {
 62    cx.observe_new(|workspace: &mut Workspace, _, _| {
 63        workspace.register_action_renderer(|div, _, _, cx| {
 64            let settings_ui_actions = [std::any::TypeId::of::<OpenSettingsUi>()];
 65            let has_flag = cx.has_flag::<SettingsUiFeatureFlag>();
 66            command_palette_hooks::CommandPaletteFilter::update_global(cx, |filter, _| {
 67                if has_flag {
 68                    filter.show_action_types(&settings_ui_actions);
 69                } else {
 70                    filter.hide_action_types(&settings_ui_actions);
 71                }
 72            });
 73            if has_flag {
 74                div.on_action(cx.listener(open_settings_editor))
 75            } else {
 76                div
 77            }
 78        });
 79    })
 80    .detach();
 81}
 82
 83pub struct SettingsPage {
 84    focus_handle: FocusHandle,
 85    settings_tree: SettingsUiTree,
 86}
 87
 88impl SettingsPage {
 89    pub fn new(_workspace: &Workspace, cx: &mut Context<Workspace>) -> Entity<Self> {
 90        cx.new(|cx| Self {
 91            focus_handle: cx.focus_handle(),
 92            settings_tree: SettingsUiTree::new(cx),
 93        })
 94    }
 95}
 96
 97impl EventEmitter<ItemEvent> for SettingsPage {}
 98
 99impl Focusable for SettingsPage {
100    fn focus_handle(&self, _cx: &App) -> FocusHandle {
101        self.focus_handle.clone()
102    }
103}
104
105impl Item for SettingsPage {
106    type Event = ItemEvent;
107
108    fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
109        Some(Icon::new(IconName::Settings))
110    }
111
112    fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
113        "Settings".into()
114    }
115
116    fn show_toolbar(&self) -> bool {
117        false
118    }
119
120    fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
121        f(*event)
122    }
123}
124
125// We want to iterate over the side bar with root groups
126// - this is a loop over top level groups, and if any are expanded, recursively displaying their items
127// - Should be able to get all items from a group (flatten a group)
128// - Should be able to toggle/untoggle groups in UI (at least in sidebar)
129// - Search should be available
130//  - there should be an index of text -> item mappings, for using fuzzy::match
131//   - Do we want to show the parent groups when a item is matched?
132
133struct UiEntry {
134    title: SharedString,
135    path: Option<SharedString>,
136    documentation: Option<SharedString>,
137    _depth: usize,
138    // a
139    //  b     < a descendant range < a total descendant range
140    //    f   |                    |
141    //    g   |                    |
142    //  c     <                    |
143    //    d                        |
144    //    e                        <
145    descendant_range: Range<usize>,
146    total_descendant_range: Range<usize>,
147    next_sibling: Option<usize>,
148    // expanded: bool,
149    render: Option<SettingsUiItemSingle>,
150    dynamic_render: Option<SettingsUiItemUnion>,
151    generate_items: Option<(
152        SettingsUiItem,
153        fn(&serde_json::Value, &App) -> Vec<SettingsUiEntryMetaData>,
154        SmallVec<[SharedString; 1]>,
155    )>,
156}
157
158impl UiEntry {
159    fn first_descendant_index(&self) -> Option<usize> {
160        return self
161            .descendant_range
162            .is_empty()
163            .not()
164            .then_some(self.descendant_range.start);
165    }
166
167    fn nth_descendant_index(&self, tree: &[UiEntry], n: usize) -> Option<usize> {
168        let first_descendant_index = self.first_descendant_index()?;
169        let mut current_index = 0;
170        let mut current_descendant_index = Some(first_descendant_index);
171        while let Some(descendant_index) = current_descendant_index
172            && current_index < n
173        {
174            current_index += 1;
175            current_descendant_index = tree[descendant_index].next_sibling;
176        }
177        current_descendant_index
178    }
179}
180
181pub struct SettingsUiTree {
182    root_entry_indices: Vec<usize>,
183    entries: Vec<UiEntry>,
184    active_entry_index: usize,
185}
186
187fn build_tree_item(
188    tree: &mut Vec<UiEntry>,
189    entry: SettingsUiEntry,
190    depth: usize,
191    prev_index: Option<usize>,
192) {
193    // let tree: HashMap<Path, UiEntry>;
194    let index = tree.len();
195    tree.push(UiEntry {
196        title: entry.title.into(),
197        path: entry.path.map(SharedString::new_static),
198        documentation: entry.documentation.map(SharedString::new_static),
199        _depth: depth,
200        descendant_range: index + 1..index + 1,
201        total_descendant_range: index + 1..index + 1,
202        render: None,
203        next_sibling: None,
204        dynamic_render: None,
205        generate_items: None,
206    });
207    if let Some(prev_index) = prev_index {
208        tree[prev_index].next_sibling = Some(index);
209    }
210    match entry.item {
211        SettingsUiItem::Group(SettingsUiItemGroup { items: group_items }) => {
212            for group_item in group_items {
213                let prev_index = tree[index]
214                    .descendant_range
215                    .is_empty()
216                    .not()
217                    .then_some(tree[index].descendant_range.end - 1);
218                tree[index].descendant_range.end = tree.len() + 1;
219                build_tree_item(tree, group_item, depth + 1, prev_index);
220                tree[index].total_descendant_range.end = tree.len();
221            }
222        }
223        SettingsUiItem::Single(item) => {
224            tree[index].render = Some(item);
225        }
226        SettingsUiItem::Union(dynamic_render) => {
227            // todo(settings_ui) take from item and store other fields instead of clone
228            // will also require replacing usage in render_recursive so it can know
229            // which options were actually rendered
230            let options = dynamic_render.options.clone();
231            tree[index].dynamic_render = Some(dynamic_render);
232            for option in options {
233                let Some(option) = option else { continue };
234                let prev_index = tree[index]
235                    .descendant_range
236                    .is_empty()
237                    .not()
238                    .then_some(tree[index].descendant_range.end - 1);
239                tree[index].descendant_range.end = tree.len() + 1;
240                build_tree_item(tree, option, depth + 1, prev_index);
241                tree[index].total_descendant_range.end = tree.len();
242            }
243        }
244        SettingsUiItem::DynamicMap(SettingsUiItemDynamicMap {
245            item: generate_settings_ui_item,
246            determine_items,
247            defaults_path,
248        }) => {
249            tree[index].generate_items = Some((
250                generate_settings_ui_item(),
251                determine_items,
252                defaults_path
253                    .into_iter()
254                    .copied()
255                    .map(SharedString::new_static)
256                    .collect(),
257            ));
258        }
259        SettingsUiItem::None => {
260            return;
261        }
262    }
263}
264
265impl SettingsUiTree {
266    pub fn new(cx: &App) -> Self {
267        let settings_store = SettingsStore::global(cx);
268        let mut tree = vec![];
269        let mut root_entry_indices = vec![];
270        for item in settings_store.settings_ui_items() {
271            if matches!(item.item, SettingsUiItem::None)
272            // todo(settings_ui): How to handle top level single items? BaseKeymap is in this category. Probably need a way to
273            // link them to other groups
274            || matches!(item.item, SettingsUiItem::Single(_))
275            {
276                continue;
277            }
278
279            let prev_root_entry_index = root_entry_indices.last().copied();
280            root_entry_indices.push(tree.len());
281            build_tree_item(&mut tree, item, 0, prev_root_entry_index);
282        }
283
284        root_entry_indices.sort_by_key(|i| &tree[*i].title);
285
286        let active_entry_index = root_entry_indices[0];
287        Self {
288            entries: tree,
289            root_entry_indices,
290            active_entry_index,
291        }
292    }
293
294    // todo(settings_ui): Make sure `Item::None` paths are added to the paths tree,
295    // so that we can keep none/skip and still test in CI that all settings have
296    #[cfg(feature = "test-support")]
297    pub fn all_paths(&self, cx: &App) -> Vec<Vec<SharedString>> {
298        // todo(settings_ui) this needs to be implemented not in terms of JSON anymore
299        Vec::default()
300    }
301}
302
303fn render_nav(tree: &SettingsUiTree, _window: &mut Window, cx: &mut Context<SettingsPage>) -> Div {
304    let mut nav = v_flex().p_4().gap_2();
305    for &index in &tree.root_entry_indices {
306        nav = nav.child(
307            div()
308                .id(index)
309                .on_click(cx.listener(move |settings, _, _, _| {
310                    settings.settings_tree.active_entry_index = index;
311                }))
312                .child(
313                    Label::new(tree.entries[index].title.clone())
314                        .size(LabelSize::Large)
315                        .when(tree.active_entry_index == index, |this| {
316                            this.color(Color::Selected)
317                        }),
318                ),
319        );
320    }
321    nav
322}
323
324fn render_content(
325    tree: &SettingsUiTree,
326    window: &mut Window,
327    cx: &mut Context<SettingsPage>,
328) -> Div {
329    let content = v_flex().size_full().gap_4();
330
331    let mut path = smallvec::smallvec![];
332
333    return render_recursive(
334        &tree.entries,
335        tree.active_entry_index,
336        &mut path,
337        content,
338        &mut None,
339        true,
340        window,
341        cx,
342    );
343}
344
345fn render_recursive(
346    tree: &[UiEntry],
347    index: usize,
348    path: &mut SmallVec<[SharedString; 1]>,
349    mut element: Div,
350    fallback_path: &mut Option<SmallVec<[SharedString; 1]>>,
351    render_next_title: bool,
352    window: &mut Window,
353    cx: &mut App,
354) -> Div {
355    let Some(child) = tree.get(index) else {
356        return element
357            .child(Label::new(SharedString::new_static("No settings found")).color(Color::Error));
358    };
359
360    if render_next_title {
361        element = element.child(Label::new(child.title.clone()).size(LabelSize::Large));
362    }
363
364    // todo(settings_ui): subgroups?
365    let mut pushed_path = false;
366    if let Some(child_path) = child.path.as_ref() {
367        path.push(child_path.clone());
368        if let Some(fallback_path) = fallback_path.as_mut() {
369            fallback_path.push(child_path.clone());
370        }
371        pushed_path = true;
372    }
373    let settings_value = settings_value_from_settings_and_path(
374        path.clone(),
375        fallback_path.as_ref().map(|path| path.as_slice()),
376        child.title.clone(),
377        child.documentation.clone(),
378        // PERF: how to structure this better? There feels like there's a way to avoid the clone
379        // and every value lookup
380        SettingsStore::global(cx).raw_user_settings(),
381        SettingsStore::global(cx).raw_default_settings(),
382    );
383    if let Some(dynamic_render) = child.dynamic_render.as_ref() {
384        let value = settings_value.read();
385        let selected_index = (dynamic_render.determine_option)(value, cx);
386        element = element.child(div().child(render_toggle_button_group_inner(
387            settings_value.title.clone(),
388            dynamic_render.labels,
389            Some(selected_index),
390            {
391                let path = settings_value.path.clone();
392                let defaults = dynamic_render.defaults.clone();
393                move |idx, cx| {
394                    if idx == selected_index {
395                        return;
396                    }
397                    let default = defaults.get(idx).cloned().unwrap_or_default();
398                    SettingsValue::write_value(&path, default, cx);
399                }
400            },
401        )));
402        // we don't add descendants for unit options, so we adjust the selected index
403        // by the number of options we didn't add descendants for, to get the descendant index
404        let selected_descendant_index = selected_index
405            - dynamic_render.options[..selected_index]
406                .iter()
407                .filter(|option| option.is_none())
408                .count();
409        if dynamic_render.options[selected_index].is_some()
410            && let Some(descendant_index) =
411                child.nth_descendant_index(tree, selected_descendant_index)
412        {
413            element = render_recursive(
414                tree,
415                descendant_index,
416                path,
417                element,
418                fallback_path,
419                false,
420                window,
421                cx,
422            );
423        }
424    } else if let Some((settings_ui_item, generate_items, defaults_path)) =
425        child.generate_items.as_ref()
426    {
427        let generated_items = generate_items(settings_value.read(), cx);
428        let mut ui_items = Vec::with_capacity(generated_items.len());
429        for item in generated_items {
430            let settings_ui_entry = SettingsUiEntry {
431                path: None,
432                title: "",
433                documentation: None,
434                item: settings_ui_item.clone(),
435            };
436            let prev_index = if ui_items.is_empty() {
437                None
438            } else {
439                Some(ui_items.len() - 1)
440            };
441            let item_index = ui_items.len();
442            build_tree_item(
443                &mut ui_items,
444                settings_ui_entry,
445                child._depth + 1,
446                prev_index,
447            );
448            if item_index < ui_items.len() {
449                ui_items[item_index].path = None;
450                ui_items[item_index].title = item.title.clone();
451                ui_items[item_index].documentation = item.documentation.clone();
452
453                // push path instead of setting path on ui item so that the path isn't pushed to default_path as well
454                // when we recurse
455                path.push(item.path.clone());
456                element = render_recursive(
457                    &ui_items,
458                    item_index,
459                    path,
460                    element,
461                    &mut Some(defaults_path.clone()),
462                    true,
463                    window,
464                    cx,
465                );
466                path.pop();
467            }
468        }
469    } else if let Some(child_render) = child.render.as_ref() {
470        element = element.child(div().child(render_item_single(
471            settings_value,
472            child_render,
473            window,
474            cx,
475        )));
476    } else if let Some(child_index) = child.first_descendant_index() {
477        let mut index = Some(child_index);
478        while let Some(sub_child_index) = index {
479            element = render_recursive(
480                tree,
481                sub_child_index,
482                path,
483                element,
484                fallback_path,
485                true,
486                window,
487                cx,
488            );
489            index = tree[sub_child_index].next_sibling;
490        }
491    } else {
492        element = element.child(div().child(Label::new("// skipped (for now)").color(Color::Muted)))
493    }
494
495    if pushed_path {
496        path.pop();
497        if let Some(fallback_path) = fallback_path.as_mut() {
498            fallback_path.pop();
499        }
500    }
501    return element;
502}
503
504impl Render for SettingsPage {
505    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
506        let scroll_handle = window.use_state(cx, |_, _| ScrollHandle::new());
507        div()
508            .grid()
509            .grid_cols(16)
510            .p_4()
511            .bg(cx.theme().colors().editor_background)
512            .size_full()
513            .child(
514                div()
515                    .id("settings-ui-nav")
516                    .col_span(2)
517                    .h_full()
518                    .child(render_nav(&self.settings_tree, window, cx)),
519            )
520            .child(
521                div().col_span(6).h_full().child(
522                    render_content(&self.settings_tree, window, cx)
523                        .id("settings-ui-content")
524                        .track_scroll(scroll_handle.read(cx))
525                        .overflow_y_scroll(),
526                ),
527            )
528    }
529}
530
531fn element_id_from_path(path: &[SharedString]) -> ElementId {
532    if path.len() == 0 {
533        panic!("Path length must not be zero");
534    } else if path.len() == 1 {
535        ElementId::Name(path[0].clone())
536    } else {
537        ElementId::from((
538            ElementId::from(path[path.len() - 2].clone()),
539            path[path.len() - 1].clone(),
540        ))
541    }
542}
543
544fn render_item_single(
545    settings_value: SettingsValue<serde_json::Value>,
546    item: &SettingsUiItemSingle,
547    window: &mut Window,
548    cx: &mut App,
549) -> AnyElement {
550    match item {
551        SettingsUiItemSingle::Custom(_) => div()
552            .child(format!("Item: {}", settings_value.path.join(".")))
553            .into_any_element(),
554        SettingsUiItemSingle::SwitchField => {
555            render_any_item(settings_value, render_switch_field, window, cx)
556        }
557        SettingsUiItemSingle::NumericStepper(num_type) => {
558            render_any_numeric_stepper(settings_value, *num_type, window, cx)
559        }
560        SettingsUiItemSingle::ToggleGroup {
561            variants: values,
562            labels: titles,
563        } => render_toggle_button_group(settings_value, values, titles, window, cx),
564        SettingsUiItemSingle::DropDown { variants, labels } => {
565            render_dropdown(settings_value, variants, labels, window, cx)
566        }
567        SettingsUiItemSingle::TextField => render_text_field(settings_value, window, cx),
568    }
569}
570
571pub fn read_settings_value_from_path<'a>(
572    settings_contents: &'a serde_json::Value,
573    path: &[impl AsRef<str>],
574) -> Option<&'a serde_json::Value> {
575    // todo(settings_ui) make non recursive, and move to `settings` alongside SettingsValue, and add method to SettingsValue to get nested
576    let Some((key, remaining)) = path.split_first() else {
577        return Some(settings_contents);
578    };
579    let Some(value) = settings_contents.get(key.as_ref()) else {
580        return None;
581    };
582
583    read_settings_value_from_path(value, remaining)
584}
585
586fn downcast_any_item<T: serde::de::DeserializeOwned>(
587    settings_value: SettingsValue<serde_json::Value>,
588) -> SettingsValue<T> {
589    let value = settings_value.value.map(|value| {
590        serde_json::from_value::<T>(value.clone())
591            .with_context(|| format!("path: {:?}", settings_value.path.join(".")))
592            .with_context(|| format!("value is not a {}: {}", std::any::type_name::<T>(), value))
593            .unwrap()
594    });
595    // todo(settings_ui) Create test that constructs UI tree, and asserts that all elements have default values
596    let default_value = serde_json::from_value::<T>(settings_value.default_value)
597        .with_context(|| format!("path: {:?}", settings_value.path.join(".")))
598        .with_context(|| format!("value is not a {}", std::any::type_name::<T>()))
599        .unwrap();
600    let deserialized_setting_value = SettingsValue {
601        title: settings_value.title,
602        path: settings_value.path,
603        documentation: settings_value.documentation,
604        value,
605        default_value,
606    };
607    deserialized_setting_value
608}
609
610fn render_any_item<T: serde::de::DeserializeOwned>(
611    settings_value: SettingsValue<serde_json::Value>,
612    render_fn: impl Fn(SettingsValue<T>, &mut Window, &mut App) -> AnyElement + 'static,
613    window: &mut Window,
614    cx: &mut App,
615) -> AnyElement {
616    let deserialized_setting_value = downcast_any_item(settings_value);
617    render_fn(deserialized_setting_value, window, cx)
618}
619
620fn render_any_numeric_stepper(
621    settings_value: SettingsValue<serde_json::Value>,
622    num_type: NumType,
623    window: &mut Window,
624    cx: &mut App,
625) -> AnyElement {
626    match num_type {
627        NumType::U64 => render_numeric_stepper::<u64>(
628            downcast_any_item(settings_value),
629            |n| u64::saturating_sub(n, 1),
630            |n| u64::saturating_add(n, 1),
631            |n| {
632                serde_json::Number::try_from(n)
633                    .context("Failed to convert u64 to serde_json::Number")
634            },
635            window,
636            cx,
637        ),
638        NumType::U32 => render_numeric_stepper::<u32>(
639            downcast_any_item(settings_value),
640            |n| u32::saturating_sub(n, 1),
641            |n| u32::saturating_add(n, 1),
642            |n| {
643                serde_json::Number::try_from(n)
644                    .context("Failed to convert u32 to serde_json::Number")
645            },
646            window,
647            cx,
648        ),
649        NumType::F32 => render_numeric_stepper::<f32>(
650            downcast_any_item(settings_value),
651            |a| a - 1.0,
652            |a| a + 1.0,
653            |n| {
654                serde_json::Number::from_f64(n as f64)
655                    .context("Failed to convert f32 to serde_json::Number")
656            },
657            window,
658            cx,
659        ),
660        NumType::USIZE => render_numeric_stepper::<usize>(
661            downcast_any_item(settings_value),
662            |n| usize::saturating_sub(n, 1),
663            |n| usize::saturating_add(n, 1),
664            |n| {
665                serde_json::Number::try_from(n)
666                    .context("Failed to convert usize to serde_json::Number")
667            },
668            window,
669            cx,
670        ),
671        NumType::U32NONZERO => render_numeric_stepper::<NonZeroU32>(
672            downcast_any_item(settings_value),
673            |a| NonZeroU32::new(u32::saturating_sub(a.get(), 1)).unwrap_or(NonZeroU32::MIN),
674            |a| NonZeroU32::new(u32::saturating_add(a.get(), 1)).unwrap_or(NonZeroU32::MAX),
675            |n| {
676                serde_json::Number::try_from(n.get())
677                    .context("Failed to convert usize to serde_json::Number")
678            },
679            window,
680            cx,
681        ),
682    }
683}
684
685fn render_numeric_stepper<T: serde::de::DeserializeOwned + std::fmt::Display + Copy + 'static>(
686    value: SettingsValue<T>,
687    saturating_sub_1: fn(T) -> T,
688    saturating_add_1: fn(T) -> T,
689    to_serde_number: fn(T) -> anyhow::Result<serde_json::Number>,
690    _window: &mut Window,
691    _cx: &mut App,
692) -> AnyElement {
693    let id = element_id_from_path(&value.path);
694    let path = value.path.clone();
695    let num = *value.read();
696
697    NumericStepper::new(
698        id,
699        num.to_string(),
700        {
701            let path = value.path;
702            move |_, _, cx| {
703                let Some(number) = to_serde_number(saturating_sub_1(num)).ok() else {
704                    return;
705                };
706                let new_value = serde_json::Value::Number(number);
707                SettingsValue::write_value(&path, new_value, cx);
708            }
709        },
710        move |_, _, cx| {
711            let Some(number) = to_serde_number(saturating_add_1(num)).ok() else {
712                return;
713            };
714
715            let new_value = serde_json::Value::Number(number);
716
717            SettingsValue::write_value(&path, new_value, cx);
718        },
719    )
720    .style(ui::NumericStepperStyle::Outlined)
721    .into_any_element()
722}
723
724fn render_switch_field(
725    value: SettingsValue<bool>,
726    _window: &mut Window,
727    _cx: &mut App,
728) -> AnyElement {
729    let id = element_id_from_path(&value.path);
730    let path = value.path.clone();
731    SwitchField::new(
732        id,
733        value.title.clone(),
734        value.documentation.clone(),
735        match value.read() {
736            true => ToggleState::Selected,
737            false => ToggleState::Unselected,
738        },
739        move |toggle_state, _, cx| {
740            let new_value = serde_json::Value::Bool(match toggle_state {
741                ToggleState::Indeterminate => {
742                    return;
743                }
744                ToggleState::Selected => true,
745                ToggleState::Unselected => false,
746            });
747
748            SettingsValue::write_value(&path, new_value, cx);
749        },
750    )
751    .into_any_element()
752}
753
754fn render_text_field(
755    value: SettingsValue<serde_json::Value>,
756    window: &mut Window,
757    cx: &mut App,
758) -> AnyElement {
759    let value = downcast_any_item::<String>(value);
760    let path = value.path.clone();
761    let editor = window.use_state(cx, {
762        let path = path.clone();
763        move |window, cx| {
764            let mut editor = Editor::single_line(window, cx);
765
766            cx.observe_global_in::<SettingsStore>(window, move |editor, window, cx| {
767                let user_settings = SettingsStore::global(cx).raw_user_settings();
768                if let Some(value) = read_settings_value_from_path(&user_settings, &path).cloned()
769                    && let Some(value) = value.as_str()
770                {
771                    editor.set_text(value, window, cx);
772                }
773            })
774            .detach();
775
776            editor.set_text(value.read().clone(), window, cx);
777            editor
778        }
779    });
780
781    let weak_editor = editor.downgrade();
782    let theme_colors = cx.theme().colors();
783
784    div()
785        .child(editor)
786        .bg(theme_colors.editor_background)
787        .border_1()
788        .rounded_lg()
789        .border_color(theme_colors.border)
790        .on_action::<menu::Confirm>({
791            move |_, _, cx| {
792                let new_value = weak_editor.read_with(cx, |editor, cx| editor.text(cx)).ok();
793
794                if let Some(new_value) = new_value {
795                    SettingsValue::write_value(&path, serde_json::Value::String(new_value), cx);
796                }
797            }
798        })
799        .into_any_element()
800}
801
802fn render_toggle_button_group(
803    value: SettingsValue<serde_json::Value>,
804    variants: &'static [&'static str],
805    labels: &'static [&'static str],
806    _: &mut Window,
807    _: &mut App,
808) -> AnyElement {
809    let value = downcast_any_item::<String>(value);
810    let active_value = value.read();
811    let selected_idx = variants.iter().position(|v| v == &active_value);
812
813    return render_toggle_button_group_inner(value.title, labels, selected_idx, {
814        let path = value.path.clone();
815        move |variant_index, cx| {
816            SettingsValue::write_value(
817                &path,
818                serde_json::Value::String(variants[variant_index].to_string()),
819                cx,
820            );
821        }
822    });
823}
824
825fn render_dropdown(
826    value: SettingsValue<serde_json::Value>,
827    variants: &'static [&'static str],
828    labels: &'static [&'static str],
829    window: &mut Window,
830    cx: &mut App,
831) -> AnyElement {
832    let value = downcast_any_item::<String>(value);
833    let id = element_id_from_path(&value.path);
834
835    let menu = window.use_keyed_state(id.clone(), cx, |window, cx| {
836        let path = value.path.clone();
837        let handler = Rc::new(move |variant: &'static str, cx: &mut App| {
838            SettingsValue::write_value(&path, serde_json::Value::String(variant.to_string()), cx);
839        });
840
841        ContextMenu::build(window, cx, |mut menu, _, _| {
842            for (label, variant) in labels.iter().zip(variants) {
843                menu = menu.entry(*label, None, {
844                    let handler = handler.clone();
845                    move |_, cx| {
846                        handler(variant, cx);
847                    }
848                });
849            }
850
851            menu
852        })
853    });
854
855    DropdownMenu::new(id, value.read(), menu.read(cx).clone())
856        .style(ui::DropdownStyle::Outlined)
857        .into_any_element()
858}
859
860fn render_toggle_button_group_inner(
861    title: SharedString,
862    labels: &'static [&'static str],
863    selected_idx: Option<usize>,
864    on_write: impl Fn(usize, &mut App) + 'static,
865) -> AnyElement {
866    fn make_toggle_group<const LEN: usize>(
867        title: SharedString,
868        selected_idx: Option<usize>,
869        on_write: Rc<dyn Fn(usize, &mut App)>,
870        labels: &'static [&'static str],
871    ) -> AnyElement {
872        let labels_array: [&'static str; LEN] = {
873            let mut arr = ["unused"; LEN];
874            arr.copy_from_slice(labels);
875            arr
876        };
877
878        let mut idx = 0;
879        ToggleButtonGroup::single_row(
880            title,
881            labels_array.map(|label| {
882                idx += 1;
883                let on_write = on_write.clone();
884                ToggleButtonSimple::new(label, move |_, _, cx| {
885                    on_write(idx - 1, cx);
886                })
887            }),
888        )
889        .when_some(selected_idx, |this, ix| this.selected_index(ix))
890        .style(ui::ToggleButtonGroupStyle::Filled)
891        .into_any_element()
892    }
893
894    let on_write = Rc::new(on_write);
895
896    macro_rules! templ_toggl_with_const_param {
897        ($len:expr) => {
898            if labels.len() == $len {
899                return make_toggle_group::<$len>(title.clone(), selected_idx, on_write, labels);
900            }
901        };
902    }
903    templ_toggl_with_const_param!(1);
904    templ_toggl_with_const_param!(2);
905    templ_toggl_with_const_param!(3);
906    templ_toggl_with_const_param!(4);
907    templ_toggl_with_const_param!(5);
908    templ_toggl_with_const_param!(6);
909    unreachable!("Too many variants");
910}
911
912fn settings_value_from_settings_and_path(
913    path: SmallVec<[SharedString; 1]>,
914    fallback_path: Option<&[SharedString]>,
915    title: SharedString,
916    documentation: Option<SharedString>,
917    user_settings: &serde_json::Value,
918    default_settings: &serde_json::Value,
919) -> SettingsValue<serde_json::Value> {
920    let default_value = read_settings_value_from_path(default_settings, &path)
921        .or_else(|| {
922            fallback_path.and_then(|fallback_path| {
923                read_settings_value_from_path(default_settings, fallback_path)
924            })
925        })
926        .with_context(|| format!("No default value for item at path {:?}", path.join(".")))
927        .expect("Default value set for item")
928        .clone();
929
930    let value = read_settings_value_from_path(user_settings, &path).cloned();
931    let settings_value = SettingsValue {
932        default_value,
933        value,
934        documentation,
935        path,
936        // todo(settings_ui) is title required inside SettingsValue?
937        title,
938    };
939    return settings_value;
940}