1use crate::capabilities::controls::text_util;
2use crate::capabilities::foundation::theme::use_theme;
3use gpui::{prelude::FluentBuilder as _, *};
4use std::ops::Range;
5use std::rc::Rc;
6
7use crate::capabilities::foundation::edit;
8
9actions!(inline_edit, [Save, Cancel]);
10
11pub fn init(cx: &mut App) {
12 if !crate::capabilities::foundation::initialization::begin(cx, "inline-edit") {
13 return;
14 }
15 cx.bind_keys([
16 KeyBinding::new("enter", Save, Some("InlineEdit")),
17 KeyBinding::new("escape", Cancel, Some("InlineEdit")),
18 ]);
19}
20
21#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
22pub enum InlineEditTrigger {
23 #[default]
24 Click,
25 DoubleClick,
26}
27
28#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
29pub enum InlineEditBlurBehavior {
30 #[default]
31 Save,
32 Cancel,
33}
34
35pub struct InlineEditState {
36 value: String,
37 editing: bool,
38 edit_value: String,
39 focus_handle: FocusHandle,
40 selected_range: Range<usize>,
41 selection_reversed: bool,
42 marked_range: Option<Range<usize>>,
43 last_layout: Option<ShapedLine>,
44 last_bounds: Option<Bounds<Pixels>>,
45 is_selecting: bool,
46}
47
48impl InlineEditState {
49 pub fn new(cx: &mut Context<Self>) -> Self {
50 Self {
51 value: String::new(),
52 editing: false,
53 edit_value: String::new(),
54 focus_handle: cx.focus_handle(),
55 selected_range: 0..0,
56 selection_reversed: false,
57 marked_range: None,
58 last_layout: None,
59 last_bounds: None,
60 is_selecting: false,
61 }
62 }
63
64 pub fn with_value(cx: &mut Context<Self>, value: impl Into<String>) -> Self {
65 let value = value.into();
66 Self {
67 value: value.clone(),
68 editing: false,
69 edit_value: value,
70 focus_handle: cx.focus_handle(),
71 selected_range: 0..0,
72 selection_reversed: false,
73 marked_range: None,
74 last_layout: None,
75 last_bounds: None,
76 is_selecting: false,
77 }
78 }
79
80 pub fn value(&self) -> &str {
81 &self.value
82 }
83
84 pub fn set_value(&mut self, value: impl Into<String>, cx: &mut Context<Self>) {
85 self.value = value.into();
86 self.edit_value = self.value.clone();
87 self.invalidate_layout_cache();
88 cx.notify();
89 }
90
91 pub fn is_editing(&self) -> bool {
92 self.editing
93 }
94
95 pub fn start_editing(&mut self, cx: &mut Context<Self>) {
96 if self.editing {
97 return;
98 }
99 self.editing = true;
100 self.edit_value = self.value.clone();
101 let len = self.edit_value.len();
102 self.selected_range = 0..len;
103 self.selection_reversed = false;
104 self.marked_range = None;
105 self.invalidate_layout_cache();
106 cx.notify();
107 }
108
109 pub fn save(&mut self, cx: &mut Context<Self>) {
110 if !self.editing {
111 return;
112 }
113 self.value = self.edit_value.clone();
114 self.editing = false;
115 self.selected_range = 0..0;
116 self.marked_range = None;
117 self.invalidate_layout_cache();
118 cx.notify();
119 }
120
121 pub fn cancel(&mut self, cx: &mut Context<Self>) {
122 if !self.editing {
123 return;
124 }
125 self.edit_value = self.value.clone();
126 self.editing = false;
127 self.selected_range = 0..0;
128 self.marked_range = None;
129 self.invalidate_layout_cache();
130 cx.notify();
131 }
132
133 pub fn edit_value(&self) -> &str {
134 &self.edit_value
135 }
136
137 fn cursor_offset(&self) -> usize {
138 if self.selection_reversed {
139 self.selected_range.start
140 } else {
141 self.selected_range.end
142 }
143 }
144
145 fn move_to(&mut self, offset: usize, cx: &mut Context<Self>) {
146 self.selected_range = offset..offset;
147 cx.notify();
148 }
149
150 fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
151 if self.selection_reversed {
152 self.selected_range.start = offset;
153 } else {
154 self.selected_range.end = offset;
155 }
156 if self.selected_range.end < self.selected_range.start {
157 self.selection_reversed = !self.selection_reversed;
158 self.selected_range = self.selected_range.end..self.selected_range.start;
159 }
160 cx.notify();
161 }
162
163 fn previous_boundary(&self, offset: usize) -> usize {
164 text_util::previous_grapheme_boundary(&self.edit_value, offset)
165 }
166
167 fn next_boundary(&self, offset: usize) -> usize {
168 text_util::next_grapheme_boundary(&self.edit_value, offset)
169 }
170
171 fn offset_to_utf16(&self, offset: usize) -> usize {
172 crate::capabilities::controls::text_util::offset_to_utf16(&self.edit_value, offset)
173 }
174
175 fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {
176 crate::capabilities::controls::text_util::range_to_utf16(&self.edit_value, range)
177 }
178
179 fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> {
180 crate::capabilities::controls::text_util::range_from_utf16(&self.edit_value, range_utf16)
181 }
182
183 fn invalidate_layout_cache(&mut self) {
184 self.last_layout = None;
185 self.last_bounds = None;
186 }
187
188 fn layout_matches_content(&self, layout: &ShapedLine) -> bool {
189 layout.text.as_ref() == self.edit_value.as_str()
190 }
191
192 fn index_for_mouse_position(&mut self, position: Point<Pixels>) -> usize {
193 if self.edit_value.is_empty() {
194 return 0;
195 }
196 let (Some(bounds), Some(line)) = (self.last_bounds.as_ref(), self.last_layout.as_ref())
197 else {
198 return 0;
199 };
200 if !self.layout_matches_content(line) {
201 self.invalidate_layout_cache();
202 return self.cursor_offset();
203 }
204 if position.y < bounds.top() {
205 return 0;
206 }
207 if position.y > bounds.bottom() {
208 return self.edit_value.len();
209 }
210 line.closest_index_for_x(position.x - bounds.left())
211 }
212
213 fn on_mouse_down(&mut self, event: &MouseDownEvent, cx: &mut Context<Self>) {
214 self.is_selecting = true;
215 let click_index = self.index_for_mouse_position(event.position);
216 if event.modifiers.shift {
217 self.select_to(click_index, cx);
218 } else {
219 self.move_to(click_index, cx);
220 }
221 }
222
223 fn on_mouse_up(&mut self, _: &MouseUpEvent, _cx: &mut Context<Self>) {
224 self.is_selecting = false;
225 }
226
227 fn on_mouse_move(&mut self, event: &MouseMoveEvent, cx: &mut Context<Self>) {
228 if self.is_selecting {
229 let position = self.index_for_mouse_position(event.position);
230 self.select_to(position, cx);
231 }
232 }
233
234 pub fn handle_save(&mut self, _: &Save, _: &mut Window, cx: &mut Context<Self>) {
235 self.save(cx);
236 }
237
238 pub fn handle_cancel(&mut self, _: &Cancel, _: &mut Window, cx: &mut Context<Self>) {
239 self.cancel(cx);
240 }
241
242 pub fn handle_backspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
243 if self.selected_range.is_empty() {
244 self.select_to(self.previous_boundary(self.cursor_offset()), cx);
245 }
246 self.replace_text_in_range(None, "", window, cx);
247 }
248
249 pub fn handle_delete(&mut self, window: &mut Window, cx: &mut Context<Self>) {
250 if self.selected_range.is_empty() {
251 self.select_to(self.next_boundary(self.cursor_offset()), cx);
252 }
253 self.replace_text_in_range(None, "", window, cx);
254 }
255
256 pub fn handle_left(&mut self, cx: &mut Context<Self>) {
257 if self.selected_range.is_empty() {
258 self.move_to(self.previous_boundary(self.cursor_offset()), cx);
259 } else {
260 self.move_to(self.selected_range.start, cx);
261 }
262 }
263
264 pub fn handle_right(&mut self, cx: &mut Context<Self>) {
265 if self.selected_range.is_empty() {
266 self.move_to(self.next_boundary(self.selected_range.end), cx);
267 } else {
268 self.move_to(self.selected_range.end, cx);
269 }
270 }
271
272 pub fn handle_select_all(&mut self, cx: &mut Context<Self>) {
273 self.move_to(0, cx);
274 self.select_to(self.edit_value.len(), cx);
275 }
276
277 pub fn handle_home(&mut self, cx: &mut Context<Self>) {
278 self.move_to(0, cx);
279 }
280
281 pub fn handle_end(&mut self, cx: &mut Context<Self>) {
282 self.move_to(self.edit_value.len(), cx);
283 }
284
285 pub fn handle_copy(&self, cx: &mut Context<Self>) {
286 if !self.selected_range.is_empty() {
287 cx.write_to_clipboard(ClipboardItem::new_string(
288 self.edit_value[self.selected_range.clone()].to_string(),
289 ));
290 }
291 }
292
293 pub fn handle_cut(&mut self, window: &mut Window, cx: &mut Context<Self>) {
294 if !self.selected_range.is_empty() {
295 cx.write_to_clipboard(ClipboardItem::new_string(
296 self.edit_value[self.selected_range.clone()].to_string(),
297 ));
298 self.replace_text_in_range(None, "", window, cx);
299 }
300 }
301
302 pub fn handle_paste(&mut self, window: &mut Window, cx: &mut Context<Self>) {
303 if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) {
304 let filtered = text.replace('\n', " ");
305 self.replace_text_in_range(None, &filtered, window, cx);
306 }
307 }
308}
309
310impl Focusable for InlineEditState {
311 fn focus_handle(&self, _: &App) -> FocusHandle {
312 self.focus_handle.clone()
313 }
314}
315
316impl EntityInputHandler for InlineEditState {
317 fn text_for_range(
318 &mut self,
319 range_utf16: Range<usize>,
320 actual_range: &mut Option<Range<usize>>,
321 _window: &mut Window,
322 _cx: &mut Context<Self>,
323 ) -> Option<String> {
324 let range = self.range_from_utf16(&range_utf16);
325 actual_range.replace(self.range_to_utf16(&range));
326 Some(self.edit_value[range].to_string())
327 }
328
329 fn selected_text_range(
330 &mut self,
331 _ignore_disabled_input: bool,
332 _window: &mut Window,
333 _cx: &mut Context<Self>,
334 ) -> Option<UTF16Selection> {
335 Some(UTF16Selection {
336 range: self.range_to_utf16(&self.selected_range),
337 reversed: self.selection_reversed,
338 })
339 }
340
341 fn marked_text_range(
342 &self,
343 _window: &mut Window,
344 _cx: &mut Context<Self>,
345 ) -> Option<Range<usize>> {
346 self.marked_range
347 .as_ref()
348 .map(|range| self.range_to_utf16(range))
349 }
350
351 fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {
352 self.marked_range = None;
353 self.invalidate_layout_cache();
354 }
355
356 fn replace_text_in_range(
357 &mut self,
358 range_utf16: Option<Range<usize>>,
359 new_text: &str,
360 _window: &mut Window,
361 cx: &mut Context<Self>,
362 ) {
363 let range = range_utf16
364 .as_ref()
365 .map(|range_utf16| self.range_from_utf16(range_utf16))
366 .or(self.marked_range.clone())
367 .unwrap_or(self.selected_range.clone());
368
369 self.edit_value =
370 self.edit_value[0..range.start].to_owned() + new_text + &self.edit_value[range.end..];
371 self.selected_range = range.start + new_text.len()..range.start + new_text.len();
372 self.marked_range.take();
373 self.invalidate_layout_cache();
374 cx.notify();
375 }
376
377 fn replace_and_mark_text_in_range(
378 &mut self,
379 range_utf16: Option<Range<usize>>,
380 new_text: &str,
381 new_selected_range_utf16: Option<Range<usize>>,
382 _window: &mut Window,
383 cx: &mut Context<Self>,
384 ) {
385 let range = range_utf16
386 .as_ref()
387 .map(|range_utf16| self.range_from_utf16(range_utf16))
388 .or(self.marked_range.clone())
389 .unwrap_or(self.selected_range.clone());
390
391 self.edit_value =
392 self.edit_value[0..range.start].to_owned() + new_text + &self.edit_value[range.end..];
393 if !new_text.is_empty() {
394 self.marked_range = Some(range.start..range.start + new_text.len());
395 } else {
396 self.marked_range = None;
397 }
398 self.selected_range = text_util::selection_after_replacement(
399 new_text,
400 new_selected_range_utf16.as_ref(),
401 range.start,
402 );
403
404 self.invalidate_layout_cache();
405 cx.notify();
406 }
407
408 fn bounds_for_range(
409 &mut self,
410 range_utf16: Range<usize>,
411 bounds: Bounds<Pixels>,
412 _window: &mut Window,
413 _cx: &mut Context<Self>,
414 ) -> Option<Bounds<Pixels>> {
415 if self.edit_value.is_empty() {
416 return None;
417 }
418 let layout_matches = {
419 let last_layout = self.last_layout.as_ref()?;
420 self.layout_matches_content(last_layout)
421 };
422 if !layout_matches {
423 self.invalidate_layout_cache();
424 return None;
425 }
426
427 let last_layout = self.last_layout.as_ref()?;
428 let range = self.range_from_utf16(&range_utf16);
429 Some(Bounds::from_corners(
430 point(
431 bounds.left() + last_layout.x_for_index(range.start),
432 bounds.top(),
433 ),
434 point(
435 bounds.left() + last_layout.x_for_index(range.end),
436 bounds.bottom(),
437 ),
438 ))
439 }
440
441 fn character_index_for_point(
442 &mut self,
443 point: Point<Pixels>,
444 _window: &mut Window,
445 _cx: &mut Context<Self>,
446 ) -> Option<usize> {
447 if self.edit_value.is_empty() {
448 return None;
449 }
450 let line_point = self.last_bounds?.localize(&point)?;
451 let layout_matches = {
452 let last_layout = self.last_layout.as_ref()?;
453 self.layout_matches_content(last_layout)
454 };
455 if !layout_matches {
456 self.invalidate_layout_cache();
457 return None;
458 }
459
460 let last_layout = self.last_layout.as_ref()?;
461 let utf8_index = last_layout.index_for_x(point.x - line_point.x)?;
462 Some(self.offset_to_utf16(utf8_index))
463 }
464}
465
466impl Render for InlineEditState {
467 fn render(&mut self, _: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
468 div()
469 }
470}
471
472struct InlineEditTextElement {
473 state: Entity<InlineEditState>,
474 placeholder: SharedString,
475}
476
477struct TextElementPrepaintState {
478 line: Option<ShapedLine>,
479 cursor: Option<PaintQuad>,
480 selection: Option<PaintQuad>,
481}
482
483impl IntoElement for InlineEditTextElement {
484 type Element = Self;
485
486 fn into_element(self) -> Self::Element {
487 self
488 }
489}
490
491impl Element for InlineEditTextElement {
492 type RequestLayoutState = ();
493 type PrepaintState = TextElementPrepaintState;
494
495 fn id(&self) -> Option<ElementId> {
496 None
497 }
498
499 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
500 None
501 }
502
503 fn request_layout(
504 &mut self,
505 _id: Option<&GlobalElementId>,
506 _inspector_id: Option<&InspectorElementId>,
507 window: &mut Window,
508 cx: &mut App,
509 ) -> (LayoutId, Self::RequestLayoutState) {
510 let mut style = Style::default();
511 style.size.width = relative(1.).into();
512 style.size.height = window.line_height().into();
513 (window.request_layout(style, [], cx), ())
514 }
515
516 fn prepaint(
517 &mut self,
518 _id: Option<&GlobalElementId>,
519 _inspector_id: Option<&InspectorElementId>,
520 bounds: Bounds<Pixels>,
521 _request_layout: &mut Self::RequestLayoutState,
522 window: &mut Window,
523 cx: &mut App,
524 ) -> Self::PrepaintState {
525 let state = self.state.read(cx);
526 let content = &state.edit_value;
527 let selected_range = state.selected_range.clone();
528 let cursor = state.cursor_offset();
529 let text_style = window.text_style();
530 let theme = use_theme(cx);
531
532 let (display_text, text_color) = if content.is_empty() {
533 (self.placeholder.clone(), theme.tokens.muted_foreground)
534 } else {
535 (content.clone().into(), text_style.color)
536 };
537
538 let run = TextRun {
539 len: display_text.len(),
540 font: text_style.font(),
541 color: text_color,
542 background_color: None,
543 underline: None,
544 strikethrough: None,
545 };
546
547 let runs = if let Some(marked_range) = state.marked_range.as_ref() {
548 vec![
549 TextRun {
550 len: marked_range.start,
551 ..run.clone()
552 },
553 TextRun {
554 len: marked_range.end - marked_range.start,
555 underline: Some(UnderlineStyle {
556 color: Some(run.color),
557 thickness: edit::IME_UNDERLINE_THICKNESS,
558 wavy: false,
559 }),
560 ..run.clone()
561 },
562 TextRun {
563 len: display_text.len().saturating_sub(marked_range.end),
564 ..run
565 },
566 ]
567 .into_iter()
568 .filter(|run| run.len > 0)
569 .collect()
570 } else {
571 vec![run]
572 };
573
574 let font_size = text_style.font_size.to_pixels(window.rem_size());
575 let line = window
576 .text_system()
577 .shape_line(display_text, font_size, &runs, None);
578
579 let cursor_pos = line.x_for_index(cursor);
580 let (selection, cursor_quad) = if selected_range.is_empty() {
581 (
582 None,
583 Some(fill(
584 Bounds::new(
585 point(bounds.left() + cursor_pos, bounds.top()),
586 size(edit::CARET_WIDTH, bounds.bottom() - bounds.top()),
587 ),
588 theme.tokens.primary,
589 )),
590 )
591 } else {
592 (
593 Some(fill(
594 Bounds::from_corners(
595 point(
596 bounds.left() + line.x_for_index(selected_range.start),
597 bounds.top(),
598 ),
599 point(
600 bounds.left() + line.x_for_index(selected_range.end),
601 bounds.bottom(),
602 ),
603 ),
604 theme
605 .tokens
606 .primary
607 .opacity(edit::SELECTION_HIGHLIGHT_OPACITY),
608 )),
609 None,
610 )
611 };
612
613 TextElementPrepaintState {
614 line: Some(line),
615 cursor: cursor_quad,
616 selection,
617 }
618 }
619
620 fn paint(
621 &mut self,
622 _id: Option<&GlobalElementId>,
623 _inspector_id: Option<&InspectorElementId>,
624 bounds: Bounds<Pixels>,
625 _request_layout: &mut Self::RequestLayoutState,
626 prepaint: &mut Self::PrepaintState,
627 window: &mut Window,
628 cx: &mut App,
629 ) {
630 let focus_handle = self.state.read(cx).focus_handle.clone();
631
632 window.handle_input(
633 &focus_handle,
634 ElementInputHandler::new(bounds, self.state.clone()),
635 cx,
636 );
637
638 if let Some(selection) = prepaint.selection.take() {
639 window.paint_quad(selection);
640 }
641
642 let Some(line) = prepaint.line.take() else {
643 return;
644 };
645
646 let _ = line.paint(bounds.origin, window.line_height(), window, cx);
647
648 if focus_handle.is_focused(window) {
649 if let Some(cursor) = prepaint.cursor.take() {
650 window.paint_quad(cursor);
651 }
652 }
653
654 self.state.update(cx, |state, _| {
655 state.last_layout = Some(line);
656 state.last_bounds = Some(bounds);
657 });
658 }
659}
660
661#[derive(IntoElement)]
662pub struct InlineEdit {
663 state: Entity<InlineEditState>,
664 placeholder: SharedString,
665 disabled: bool,
666 trigger: InlineEditTrigger,
667 on_save: Option<Rc<dyn Fn(&str, &mut Window, &mut App)>>,
668 on_cancel: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
669 style: StyleRefinement,
670}
671
672impl InlineEdit {
673 pub fn new(state: Entity<InlineEditState>) -> Self {
674 Self {
675 state,
676 placeholder: "Click to edit".into(),
677 disabled: false,
678 trigger: InlineEditTrigger::Click,
679 on_save: None,
680 on_cancel: None,
681 style: StyleRefinement::default(),
682 }
683 }
684
685 pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
686 self.placeholder = placeholder.into();
687 self
688 }
689
690 pub fn disabled(mut self, disabled: bool) -> Self {
691 self.disabled = disabled;
692 self
693 }
694
695 pub fn trigger(mut self, trigger: InlineEditTrigger) -> Self {
696 self.trigger = trigger;
697 self
698 }
699
700 pub fn on_save<F>(mut self, handler: F) -> Self
701 where
702 F: Fn(&str, &mut Window, &mut App) + 'static,
703 {
704 self.on_save = Some(Rc::new(handler));
705 self
706 }
707
708 pub fn on_cancel<F>(mut self, handler: F) -> Self
709 where
710 F: Fn(&mut Window, &mut App) + 'static,
711 {
712 self.on_cancel = Some(Rc::new(handler));
713 self
714 }
715}
716
717impl Styled for InlineEdit {
718 fn style(&mut self) -> &mut StyleRefinement {
719 &mut self.style
720 }
721}
722
723impl RenderOnce for InlineEdit {
724 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
725 let theme = use_theme(cx);
726 let user_style = self.style;
727 let is_editing = self.state.read(cx).is_editing();
728 let value = self.state.read(cx).value().to_string();
729 let focus_handle = self.state.read(cx).focus_handle(cx);
730 let state = self.state.clone();
731 let state_for_click = self.state.clone();
732 let state_for_double_click = self.state.clone();
733 let state_for_mouse_down = self.state.clone();
734 let state_for_mouse_up = self.state.clone();
735 let state_for_mouse_move = self.state.clone();
736 let on_save = self.on_save.clone();
737 let on_cancel = self.on_cancel.clone();
738 let trigger = self.trigger;
739 let placeholder = self.placeholder.clone();
740
741 if is_editing {
742 div()
743 .id(("inline-edit", state.entity_id()))
744 .key_context("InlineEdit")
745 .track_focus(&focus_handle)
746 .h(px(32.0))
747 .px(px(8.0))
748 .py(px(4.0))
749 .bg(theme.tokens.background)
750 .border_1()
751 .border_color(theme.tokens.ring)
752 .rounded(theme.tokens.radius_md)
753 .shadow(smallvec::smallvec![theme.tokens.focus_ring_light()])
754 .text_size(px(14.0))
755 .font_family(theme.tokens.font_family.clone())
756 .text_color(theme.tokens.foreground)
757 .on_action({
758 let state = state.clone();
759 let on_save = on_save.clone();
760 move |_: &Save, window: &mut Window, cx: &mut App| {
761 let value = state.read(cx).edit_value.clone();
762 state.update(cx, |s, cx| s.save(cx));
763 if let Some(handler) = on_save.as_ref() {
764 handler(&value, window, cx);
765 }
766 }
767 })
768 .on_action({
769 let state = state.clone();
770 let on_cancel = on_cancel.clone();
771 move |_: &Cancel, window: &mut Window, cx: &mut App| {
772 state.update(cx, |s, cx| s.cancel(cx));
773 if let Some(handler) = on_cancel.as_ref() {
774 handler(window, cx);
775 }
776 }
777 })
778 .on_key_down({
779 let state = state.clone();
780 move |event, window, cx| {
781 let key = event.keystroke.key.as_str();
782 match key {
783 "backspace" => {
784 state.update(cx, |s, cx| s.handle_backspace(window, cx));
785 cx.stop_propagation();
786 }
787 "delete" => {
788 state.update(cx, |s, cx| s.handle_delete(window, cx));
789 cx.stop_propagation();
790 }
791 "left" => {
792 state.update(cx, |s, cx| s.handle_left(cx));
793 cx.stop_propagation();
794 }
795 "right" => {
796 state.update(cx, |s, cx| s.handle_right(cx));
797 cx.stop_propagation();
798 }
799 "home" => {
800 state.update(cx, |s, cx| s.handle_home(cx));
801 cx.stop_propagation();
802 }
803 "end" => {
804 state.update(cx, |s, cx| s.handle_end(cx));
805 cx.stop_propagation();
806 }
807 "a" if event.keystroke.modifiers.platform => {
808 state.update(cx, |s, cx| s.handle_select_all(cx));
809 cx.stop_propagation();
810 }
811 "c" if event.keystroke.modifiers.platform => {
812 state.update(cx, |s, cx| s.handle_copy(cx));
813 cx.stop_propagation();
814 }
815 "x" if event.keystroke.modifiers.platform => {
816 state.update(cx, |s, cx| s.handle_cut(window, cx));
817 cx.stop_propagation();
818 }
819 "v" if event.keystroke.modifiers.platform => {
820 state.update(cx, |s, cx| s.handle_paste(window, cx));
821 cx.stop_propagation();
822 }
823 _ => {}
824 }
825 }
826 })
827 .on_mouse_down(MouseButton::Left, {
828 move |event: &MouseDownEvent, _, cx| {
829 state_for_mouse_down.update(cx, |s, cx| s.on_mouse_down(event, cx));
830 }
831 })
832 .on_mouse_up(MouseButton::Left, {
833 move |event: &MouseUpEvent, _, cx| {
834 state_for_mouse_up.update(cx, |s, cx| s.on_mouse_up(event, cx));
835 }
836 })
837 .on_mouse_move({
838 move |event: &MouseMoveEvent, _, cx| {
839 state_for_mouse_move.update(cx, |s, cx| s.on_mouse_move(event, cx));
840 }
841 })
842 .child(
843 div()
844 .size_full()
845 .flex()
846 .items_center()
847 .child(InlineEditTextElement {
848 state: state.clone(),
849 placeholder,
850 }),
851 )
852 .map(|this| {
853 let mut div = this;
854 div.style().refine(&user_style);
855 div
856 })
857 } else {
858 let display_text = if value.is_empty() {
859 self.placeholder.clone()
860 } else {
861 value.clone().into()
862 };
863
864 let text_color = if value.is_empty() {
865 theme.tokens.muted_foreground
866 } else {
867 theme.tokens.foreground
868 };
869
870 div()
871 .id(("inline-edit-display", state.entity_id()))
872 .h(px(32.0))
873 .px(px(8.0))
874 .py(px(4.0))
875 .flex()
876 .items_center()
877 .text_size(px(14.0))
878 .font_family(theme.tokens.font_family.clone())
879 .text_color(text_color)
880 .rounded(theme.tokens.radius_md)
881 .when(!self.disabled, |d| {
882 d.cursor_pointer()
883 .hover(|s| {
884 s.bg(theme.tokens.muted.opacity(0.5))
885 .border_b_1()
886 .border_color(theme.tokens.primary.opacity(0.5))
887 })
888 .when(trigger == InlineEditTrigger::Click, |d| {
889 d.on_click({
890 move |_, window, cx| {
891 state_for_click.update(cx, |s, cx| s.start_editing(cx));
892 window.focus(&state_for_click.read(cx).focus_handle(cx));
893 }
894 })
895 })
896 .when(trigger == InlineEditTrigger::DoubleClick, |d| {
897 d.on_mouse_down(MouseButton::Left, {
898 move |event: &MouseDownEvent, window: &mut Window, cx: &mut App| {
899 if event.click_count >= 2 {
900 state_for_double_click
901 .update(cx, |s, cx| s.start_editing(cx));
902 window.focus(
903 &state_for_double_click.read(cx).focus_handle(cx),
904 );
905 }
906 }
907 })
908 })
909 })
910 .when(self.disabled, |d| d.opacity(0.5))
911 .child(display_text)
912 .map(|this| {
913 let mut div = this;
914 div.style().refine(&user_style);
915 div
916 })
917 }
918 }
919}
920
921#[cfg(test)]
922mod tests {
923 use super::*;
924
925 #[gpui::test]
926 fn save_commits_edited_value_and_cancel_restores_original() {
927 let mut app = TestApp::new();
928 let state = app.update(|cx| cx.new(|cx| InlineEditState::with_value(cx, "initial")));
929
930 app.update(|cx| state.update(cx, |s, cx| s.start_editing(cx)));
931 app.update(|cx| {
932 state.update(cx, |s, _| {
933 assert!(s.is_editing());
934 assert_eq!(s.selected_range, 0.."initial".len());
936 s.edit_value = "typed".to_string();
937 })
938 });
939
940 app.update(|cx| state.update(cx, |s, cx| s.save(cx)));
941 app.update(|cx| {
942 let s = state.read(cx);
943 assert!(!s.is_editing());
944 assert_eq!(s.value(), "typed");
945 });
946
947 app.update(|cx| state.update(cx, |s, cx| s.start_editing(cx)));
948 app.update(|cx| state.update(cx, |s, _| s.edit_value = "discarded".to_string()));
949 app.update(|cx| state.update(cx, |s, cx| s.cancel(cx)));
950 app.update(|cx| {
951 let s = state.read(cx);
952 assert!(!s.is_editing());
953 assert_eq!(s.value(), "typed");
954 assert_eq!(s.edit_value(), "typed");
955 });
956 }
957
958 #[gpui::test]
959 fn set_value_while_not_editing_syncs_edit_value() {
960 let mut app = TestApp::new();
961 let state = app.update(|cx| cx.new(InlineEditState::new));
962 app.update(|cx| state.update(cx, |s, cx| s.set_value("v1", cx)));
963 app.update(|cx| {
964 let s = state.read(cx);
965 assert_eq!(s.value(), "v1");
966 assert_eq!(s.edit_value(), "v1");
967 assert!(!s.is_editing());
968 });
969 }
970}