fc_ui/capabilities/controls/
textarea.rs1use crate::capabilities::controls::input::InputVariant;
4pub use crate::capabilities::controls::textarea_state::wire_actions;
5use crate::capabilities::controls::textarea_state::TextareaEvent;
6use crate::capabilities::controls::textarea_state::TextareaState;
7use crate::capabilities::foundation::theme::use_theme;
8use gpui::{prelude::FluentBuilder as _, *};
9use std::rc::Rc;
10
11pub fn init(cx: &mut App) {
13 if !crate::capabilities::foundation::initialization::begin(cx, "textarea") {
14 return;
15 }
16 crate::capabilities::controls::textarea_state::init(cx);
17}
18
19#[derive(IntoElement)]
20pub struct Textarea {
21 state: Entity<TextareaState>,
22 placeholder: SharedString,
23 variant: InputVariant,
24 disabled: bool,
25 error: bool,
26 rows: usize,
27 min_rows: Option<usize>,
28 max_rows: Option<usize>,
29 auto_grow: bool,
30 initial_value: Option<SharedString>,
31
32 on_change: Option<Rc<dyn Fn(SharedString, &mut App)>>,
33 on_enter: Option<Rc<dyn Fn(SharedString, &mut App)>>,
34 on_shift_enter: Option<Rc<dyn Fn(SharedString, &mut App)>>,
35 on_focus: Option<Rc<dyn Fn(SharedString, &mut App)>>,
36 on_blur: Option<Rc<dyn Fn(SharedString, &mut App)>>,
37
38 style: StyleRefinement,
39}
40
41impl Textarea {
42 pub fn new(state: &Entity<TextareaState>) -> Self {
43 Self {
44 state: state.clone(),
45 placeholder: "".into(),
46 variant: InputVariant::Default,
47 disabled: false,
48 error: false,
49 rows: 3,
50 min_rows: None,
51 max_rows: None,
52 auto_grow: false,
53 initial_value: None,
54 on_change: None,
55 on_enter: None,
56 on_shift_enter: None,
57 on_focus: None,
58 on_blur: None,
59 style: StyleRefinement::default(),
60 }
61 }
62
63 pub fn value(mut self, value: impl Into<SharedString>) -> Self {
64 self.initial_value = Some(value.into());
65 self
66 }
67
68 pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
69 self.placeholder = placeholder.into();
70 self
71 }
72
73 pub fn variant(mut self, variant: InputVariant) -> Self {
74 self.variant = variant;
75 self
76 }
77
78 pub fn disabled(mut self, disabled: bool) -> Self {
79 self.disabled = disabled;
80 self
81 }
82
83 pub fn error(mut self, error: bool) -> Self {
84 self.error = error;
85 self
86 }
87
88 pub fn rows(mut self, rows: usize) -> Self {
89 self.rows = rows.max(1);
90 self
91 }
92
93 pub fn min_rows(mut self, min_rows: usize) -> Self {
94 self.min_rows = Some(min_rows.max(1));
95 self
96 }
97
98 pub fn max_rows(mut self, max_rows: usize) -> Self {
99 self.max_rows = Some(max_rows.max(1));
100 self
101 }
102
103 pub fn auto_grow(mut self, auto_grow: bool) -> Self {
104 self.auto_grow = auto_grow;
105 self
106 }
107
108 pub fn on_change<F>(mut self, callback: F) -> Self
109 where
110 F: Fn(SharedString, &mut App) + 'static,
111 {
112 self.on_change = Some(Rc::new(callback));
113 self
114 }
115
116 pub fn on_enter<F>(mut self, callback: F) -> Self
117 where
118 F: Fn(SharedString, &mut App) + 'static,
119 {
120 self.on_enter = Some(Rc::new(callback));
121 self
122 }
123
124 pub fn on_shift_enter<F>(mut self, callback: F) -> Self
125 where
126 F: Fn(SharedString, &mut App) + 'static,
127 {
128 self.on_shift_enter = Some(Rc::new(callback));
129 self
130 }
131
132 pub fn on_focus<F>(mut self, callback: F) -> Self
133 where
134 F: Fn(SharedString, &mut App) + 'static,
135 {
136 self.on_focus = Some(Rc::new(callback));
137 self
138 }
139
140 pub fn on_blur<F>(mut self, callback: F) -> Self
141 where
142 F: Fn(SharedString, &mut App) + 'static,
143 {
144 self.on_blur = Some(Rc::new(callback));
145 self
146 }
147
148 fn install_event_subscription(&self, cx: &mut App) {
149 let on_change = self.on_change.clone();
150 let on_enter = self.on_enter.clone();
151 let on_shift_enter = self.on_shift_enter.clone();
152 let on_focus = self.on_focus.clone();
153 let on_blur = self.on_blur.clone();
154
155 let has_callbacks = on_change.is_some()
156 || on_enter.is_some()
157 || on_shift_enter.is_some()
158 || on_focus.is_some()
159 || on_blur.is_some();
160 let subscription = has_callbacks.then(|| {
161 cx.subscribe(
162 &self.state,
163 move |emitter, event: &TextareaEvent, cx| match event {
164 TextareaEvent::Change => {
165 if let Some(callback) = on_change.as_ref() {
166 callback(emitter.read(cx).content.clone(), cx);
167 }
168 }
169 TextareaEvent::Enter => {
170 if let Some(callback) = on_enter.as_ref() {
171 callback(emitter.read(cx).content.clone(), cx);
172 }
173 }
174 TextareaEvent::ShiftEnter => {
175 if let Some(callback) = on_shift_enter.as_ref() {
176 callback(emitter.read(cx).content.clone(), cx);
177 }
178 }
179 TextareaEvent::Focus => {
180 if let Some(callback) = on_focus.as_ref() {
181 callback(emitter.read(cx).content.clone(), cx);
182 }
183 }
184 TextareaEvent::Blur => {
185 if let Some(callback) = on_blur.as_ref() {
186 callback(emitter.read(cx).content.clone(), cx);
187 }
188 }
189 TextareaEvent::Tab | TextareaEvent::ShiftTab => {}
190 },
191 )
192 });
193
194 self.state.update(cx, |state, _| {
195 state.replace_event_subscription(subscription);
196 });
197 }
198
199 fn calculate_height(&self, window: &Window, cx: &App) -> Pixels {
200 let line_height = window.line_height().to_f64() as f32;
201 let padding_y = 8.0;
202 let base_height = self.rows as f32 * line_height + padding_y * 2.0;
203
204 if self.auto_grow {
205 let visual_lines = self.state.read(cx).visual_line_count_for_layout().max(1);
206 let content_height = visual_lines as f32 * line_height + padding_y * 2.0;
207
208 let final_height = if let Some(min_rows) = self.min_rows {
209 let min_height = min_rows as f32 * line_height + padding_y * 2.0;
210 content_height.max(min_height)
211 } else {
212 content_height.max(base_height)
213 };
214
215 if let Some(max_rows) = self.max_rows {
216 let max_height = max_rows as f32 * line_height + padding_y * 2.0;
217 px(final_height.min(max_height))
218 } else {
219 px(final_height)
220 }
221 } else {
222 px(base_height)
223 }
224 }
225}
226
227impl Styled for Textarea {
228 fn style(&mut self) -> &mut StyleRefinement {
229 &mut self.style
230 }
231}
232
233impl RenderOnce for Textarea {
234 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
235 let theme = use_theme(cx);
236 let height = self.calculate_height(window, cx);
237
238 self.state.update(cx, |state, cx| {
240 state.disabled = self.disabled;
241 state.placeholder = self.placeholder.clone();
242
243 if !state.initialized {
244 state.initialized = true;
245 if let Some(value) = self.initial_value.clone() {
246 state.set_value(value, window, cx);
247 }
248 }
249 });
250
251 self.install_event_subscription(cx);
252
253 let (bg_color, border_color, text_color) = if self.disabled {
254 (
255 theme.tokens.muted.opacity(0.5),
256 theme.tokens.border,
257 theme.tokens.muted_foreground,
258 )
259 } else if self.error {
260 match self.variant {
261 InputVariant::Default => (
262 theme.tokens.background,
263 theme.tokens.destructive,
264 theme.tokens.foreground,
265 ),
266 InputVariant::Outline => (
267 theme.tokens.background,
268 theme.tokens.destructive,
269 theme.tokens.foreground,
270 ),
271 InputVariant::Ghost => (
272 gpui::transparent_black(),
273 theme.tokens.destructive.opacity(0.3),
274 theme.tokens.foreground,
275 ),
276 }
277 } else {
278 match self.variant {
279 InputVariant::Default => (
280 theme.tokens.background,
281 theme.tokens.input,
282 theme.tokens.foreground,
283 ),
284 InputVariant::Outline => (
285 theme.tokens.background,
286 theme.tokens.border,
287 theme.tokens.foreground,
288 ),
289 InputVariant::Ghost => (
290 gpui::transparent_black(),
291 theme.tokens.border.opacity(0.3),
292 theme.tokens.foreground,
293 ),
294 }
295 };
296
297 let is_focused = self.state.read(cx).focus_handle(cx).is_focused(window);
298 let user_style = self.style;
299
300 wire_actions(&self.state, window, cx)
301 .w_full()
302 .h(height)
303 .flex_shrink_0()
304 .when(self.auto_grow, |this| this.min_h(height))
305 .px(px(12.0))
306 .py(px(8.0))
307 .bg(bg_color)
308 .border_1()
309 .border_color(border_color)
310 .rounded(theme.tokens.radius_md)
311 .text_size(px(14.0))
312 .font_family(theme.tokens.font_mono.clone())
313 .text_color(text_color)
314 .when(!self.disabled, |this| {
315 this.hover(|style| {
316 style.border_color(if self.error {
317 theme.tokens.destructive
318 } else {
319 theme.tokens.ring
320 })
321 })
322 })
323 .when(is_focused && !self.disabled, |this| {
324 this.border_color(if self.error {
325 theme.tokens.destructive
326 } else {
327 theme.tokens.ring
328 })
329 })
330 .when(!self.disabled, |this| this.cursor(gpui::CursorStyle::IBeam))
331 .map(|this| {
332 let mut div = this;
333 div.style().refine(&user_style);
334 div
335 })
336 .child(self.state.clone())
337 }
338}
339
340#[cfg(test)]
341mod tests {
342 use super::*;
343 use crate::capabilities::foundation::theme::{install_theme, Theme};
344 use std::{cell::Cell, rc::Rc};
345
346 struct TextareaRenderTestView {
347 state: Entity<TextareaState>,
348 callback_calls: Option<Rc<Cell<usize>>>,
349 }
350
351 impl Render for TextareaRenderTestView {
352 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
353 Textarea::new(&self.state).when_some(self.callback_calls.clone(), |textarea, calls| {
354 textarea.on_change(move |_, _| calls.set(calls.get() + 1))
355 })
356 }
357 }
358
359 #[gpui::test]
360 fn repeated_render_replaces_textarea_event_subscription() {
361 let mut app = TestApp::new();
362 app.update(|cx| install_theme(cx, Theme::light()));
363 let stale_calls = Rc::new(Cell::new(0));
364 let current_calls = Rc::new(Cell::new(0));
365 let mut window = app.open_window(|_, cx| TextareaRenderTestView {
366 state: cx.new(TextareaState::new),
367 callback_calls: Some(stale_calls.clone()),
368 });
369
370 window.draw();
371 window.update(|view, _, cx| {
372 view.callback_calls = Some(current_calls.clone());
373 cx.notify();
374 });
375 window.draw();
376 window.update(|view, _, cx| {
377 view.state
378 .update(cx, |_, cx| cx.emit(TextareaEvent::Change));
379 });
380 assert_eq!(stale_calls.get(), 0);
381 assert_eq!(current_calls.get(), 1);
382
383 window.update(|view, _, cx| {
384 view.callback_calls = None;
385 cx.notify();
386 });
387 window.draw();
388 window.update(|view, _, cx| {
389 view.state
390 .update(cx, |_, cx| cx.emit(TextareaEvent::Change));
391 });
392 assert_eq!(current_calls.get(), 1);
393 }
394
395 struct BareTextareaTestView {
396 state: Entity<TextareaState>,
397 }
398
399 impl Render for BareTextareaTestView {
400 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
401 wire_actions(&self.state, window, cx)
402 .h(px(96.0))
403 .px(px(12.0))
404 .rounded(px(8.0))
405 .child(self.state.clone())
406 }
407 }
408
409 #[gpui::test]
410 fn wire_actions_gives_custom_textarea_containers_full_keyboard_editing() {
411 let mut app = TestApp::new();
412 app.update(|cx| {
413 install_theme(cx, Theme::light());
414 crate::capabilities::controls::textarea_state::init(cx);
415 });
416 let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).value("hello")));
417 let mut window = app.open_window(|_, _| BareTextareaTestView {
418 state: state.clone(),
419 });
420
421 window.draw();
422 window.update(|_, window, cx| state.read(cx).focus_handle(cx).focus(window));
423 window.draw();
424 let handle: AnyWindowHandle = window.handle().into();
425 app.raw_context_mut()
426 .simulate_keystrokes(handle, "backspace");
427 app.flush();
428
429 app.update(|cx| {
430 assert_eq!(state.read(cx).content(), "hell");
431 });
432 }
433}