BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-component / src / setting / fields / string.rs

string.rs

string.rs 3.0 KiB Download Raw
1use std::rc::Rc;
2
3use gpui::{
4 AnyElement, App, AppContext as _, Entity, IntoElement, SharedString, StyleRefinement, Styled,
5 Window, prelude::FluentBuilder as _,
6};
7
8use crate::{
9 AxisExt as _, Sizable, StyledExt,
10 input::{Input, InputEvent, InputState},
11 setting::{
12 AnySettingField, RenderOptions,
13 fields::{SettingFieldRender, get_value, set_value},
14 },
15};
16
17pub(crate) struct StringField<T> {
18 _marker: std::marker::PhantomData<T>,
19}
20
21impl<T> StringField<T> {
22 pub(crate) fn new() -> Self {
23 Self {
24 _marker: std::marker::PhantomData,
25 }
26 }
27}
28
29struct State {
30 input: Entity<InputState>,
31 _subscription: gpui::Subscription,
32}
33
34impl<T> SettingFieldRender for StringField<T>
35where
36 T: Into<SharedString> + From<SharedString> + Clone + 'static,
37{
38 fn render(
39 &self,
40 field: Rc<dyn AnySettingField>,
41 options: &RenderOptions,
42 style: &StyleRefinement,
43 window: &mut Window,
44 cx: &mut App,
45 ) -> AnyElement {
46 let value = get_value::<T>(&field, cx);
47 let value: SharedString = value.into();
48 let set_value = set_value::<T>(&field, cx);
49
50 let state_entity = window.use_keyed_state(
51 SharedString::from(format!(
52 "string-state-{}-{}-{}",
53 options.page_ix(),
54 options.group_ix(),
55 options.item_ix()
56 )),
57 cx,
58 {
59 let value = value.clone();
60 |window, cx| {
61 let input = cx.new(|cx| InputState::new(window, cx).default_value(value));
62 let _subscription = cx.subscribe(&input, {
63 move |_, input, event: &InputEvent, cx| match event {
64 InputEvent::Change => {
65 let value = input.read(cx).value();
66 set_value(value.into(), cx);
67 }
68 _ => {}
69 }
70 });
71
72 State {
73 input,
74 _subscription,
75 }
76 }
77 },
78 );
79
80 // Sync the displayed value when the underlying setting changed externally
81 state_entity.update(cx, |state, cx| {
82 if state.input.read(cx).value() != value {
83 state.input.update(cx, |input, cx| {
84 input.set_value(value.clone(), window, cx);
85 });
86 }
87 });
88
89 let state = state_entity.read(cx);
90
91 Input::new(&state.input)
92 .disabled(options.is_disabled())
93 .with_size(options.size())
94 .map(|this| {
95 if options.layout().is_horizontal() {
96 this.w_64()
97 } else {
98 this.w_full()
99 }
100 })
101 .refine_style(style)
102 .into_any_element()
103 }
104}