1use std::rc::Rc;
23
24use arc_motion::{arc_spring, is_reduced_motion, motion_now};
25use arc_tokens::{ActiveArcTheme as _, Spacing, Typography};
26use gpui_kit::{
27 App, ElementId, FocusHandle, IntoElement, KeyDownEvent, ParentElement, Pixels, RenderOnce,
28 Role, SharedString, Styled, TestSupportExt as _, Window,
29 base::{Button as BaseButton, StyledExt as _},
30 div,
31 prelude::*,
32 px,
33};
34
35use super::field_message::render_field_message;
36
37type InlineSaveHandler = Rc<dyn Fn(&str) -> Result<(), SharedString>>;
38
39pub const INLINE_EDIT_SAVED_HOLD_SECS: f64 = 1.8;
41pub const INLINE_EDIT_FAIL_FLASH_SECS: f64 = 1.4;
43
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub enum InlineEditPhase {
46 Idle,
47 Saved,
48 Failed,
49}
50
51#[derive(Clone)]
52struct InlineEditInternal {
53 committed: SharedString,
54 shown: SharedString,
55 seen: SharedString,
56 editing: bool,
57 draft: String,
58 phase: InlineEditPhase,
59 error: Option<SharedString>,
60 failed_msg: Option<SharedString>,
61 direction: i8,
63 changed_at_secs: f64,
64 phase_at_secs: f64,
65 focus_handle: FocusHandle,
66}
67
68impl InlineEditInternal {
69 fn new(initial: SharedString, cx: &mut App) -> Self {
70 Self {
71 committed: initial.clone(),
72 shown: initial.clone(),
73 seen: initial,
74 editing: false,
75 draft: String::new(),
76 phase: InlineEditPhase::Idle,
77 error: None,
78 failed_msg: None,
79 direction: 1,
80 changed_at_secs: f64::NEG_INFINITY,
81 phase_at_secs: f64::NEG_INFINITY,
82 focus_handle: cx.focus_handle(),
83 }
84 }
85}
86
87pub fn inline_edit_clean(text: &str, multiline: bool) -> String {
89 if multiline {
90 text.trim().to_string()
91 } else {
92 text.split_whitespace().collect::<Vec<_>>().join(" ")
93 }
94}
95
96#[derive(IntoElement)]
98pub struct InlineEdit {
99 id: ElementId,
100 label: SharedString,
101 value: SharedString,
102 placeholder: SharedString,
103 #[allow(clippy::type_complexity)]
104 validate: Option<Rc<dyn Fn(&str) -> Option<SharedString>>>,
105 on_save: Option<InlineSaveHandler>,
106 disabled: bool,
107 width: Option<Pixels>,
108}
109
110impl InlineEdit {
111 pub fn new(
112 id: impl Into<ElementId>,
113 label: impl Into<SharedString>,
114 value: impl Into<SharedString>,
115 ) -> Self {
116 Self {
117 id: id.into(),
118 label: label.into(),
119 value: value.into(),
120 placeholder: "".into(),
121 validate: None,
122 on_save: None,
123 disabled: false,
124 width: None,
125 }
126 }
127
128 pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
129 self.placeholder = placeholder.into();
130 self
131 }
132
133 pub fn validate(mut self, validate: impl Fn(&str) -> Option<SharedString> + 'static) -> Self {
135 self.validate = Some(Rc::new(validate));
136 self
137 }
138
139 pub fn on_save(mut self, handler: impl Fn(&str) -> Result<(), SharedString> + 'static) -> Self {
142 self.on_save = Some(Rc::new(handler));
143 self
144 }
145
146 pub fn disabled(mut self, disabled: bool) -> Self {
147 self.disabled = disabled;
148 self
149 }
150
151 pub fn width(mut self, width: impl Into<Pixels>) -> Self {
152 self.width = Some(width.into());
153 self
154 }
155}
156
157impl RenderOnce for InlineEdit {
158 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
159 let theme = cx.arc_theme().clone();
160 let colors = theme.colors;
161 let motion = theme.motion;
162 let reduced = is_reduced_motion(cx);
163 let now = motion_now(cx);
164
165 let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-inline-state".into());
166 let internal = window.use_keyed_state(state_id, cx, |_, cx| {
167 InlineEditInternal::new(self.value.clone(), cx)
168 });
169
170 if !internal.read(cx).editing {
172 let seen = internal.read(cx).seen.clone();
173 if self.value != seen {
174 let cur_shown = internal.read(cx).shown.clone();
175 let cur_committed = internal.read(cx).committed.clone();
176 internal.update(cx, |s, _| {
177 s.seen = self.value.clone();
178 if self.value != cur_committed {
179 s.committed = self.value.clone();
180 if self.value != cur_shown {
181 s.shown = self.value.clone();
182 s.direction = 1;
183 s.changed_at_secs = now;
184 }
185 }
186 });
187 }
188 }
189
190 let snap_state = internal.read(cx).clone();
191 let layer_text = if snap_state.editing {
192 SharedString::from(snap_state.draft.clone())
193 } else {
194 snap_state.shown.clone()
195 };
196 let saving = false; let displayed = if layer_text.is_empty() {
198 self.placeholder.to_string()
199 } else {
200 layer_text.to_string()
201 };
202
203 let src_elapsed = if snap_state.editing {
205 f64::INFINITY
206 } else {
207 (now - snap_state.changed_at_secs).max(0.0)
208 };
209 let (text_op, text_y) = if src_elapsed >= 0.24 {
210 (1.0_f32, 0.0_f32)
211 } else {
212 window.request_animation_frame();
213 let t = (src_elapsed / 0.24).clamp(0.0, 1.0) as f32;
214 let e = if reduced {
215 t
216 } else {
217 arc_motion::CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
218 };
219 let y = if reduced {
220 0.0
221 } else {
222 (snap_state.direction as f32) * 0.3 * f32::from(Typography::TEXT_SM) * (1.0 - e)
223 };
224 (e.clamp(0.0, 1.0), y)
225 };
226
227 let saved = snap_state.phase == InlineEditPhase::Saved;
229 let failed = snap_state.phase == InlineEditPhase::Failed;
230 let phase_elapsed = (now - snap_state.phase_at_secs).max(0.0);
231 if saved && phase_elapsed < INLINE_EDIT_SAVED_HOLD_SECS {
232 window.request_animation_frame();
233 }
234 if failed && phase_elapsed < INLINE_EDIT_FAIL_FLASH_SECS {
235 window.request_animation_frame();
236 }
237 let _check_scale = if saved {
238 arc_spring(
239 (self.id.clone(), "check-sc"),
240 1.0,
241 motion.spring.snappy,
242 window,
243 cx,
244 )
245 } else {
246 0.6
247 };
248
249 let _is_focused = snap_state.focus_handle.is_focused(window);
250 let text_color = if snap_state.editing {
251 colors.foreground
252 } else if snap_state.shown.is_empty() {
253 colors.text_muted
254 } else {
255 colors.foreground
256 };
257
258 let _st_click = internal.clone();
260 let click_focus = snap_state.focus_handle.clone();
261 let disabled_click = self.disabled;
262
263 let st_key = internal.clone();
264 let key_focus = snap_state.focus_handle.clone();
265 let validate_fn = self.validate.clone();
266 let save_fn = self.on_save.clone();
267 let label_key = self.label.clone();
268 let disabled_key = self.disabled;
269
270 let submit =
271 move |st: &gpui_kit::Entity<InlineEditInternal>, window: &mut Window, cx: &mut App| {
272 let now_s = motion_now(cx);
273 let draft = st.read(cx).draft.clone();
274 let cleaned = SharedString::from(inline_edit_clean(&draft, false));
275 if let Some(validate) = &validate_fn
276 && let Some(problem) = validate(&cleaned)
277 {
278 st.update(cx, |s, _| {
279 s.error = Some(problem);
280 });
281 window.refresh();
282 return;
283 }
284 let shown = st.read(cx).shown.clone();
285 let committed = st.read(cx).committed.clone();
286 st.update(cx, |s, _| {
287 s.editing = false;
288 s.error = None;
289 if cleaned != draft {
290 s.shown = cleaned.clone();
291 s.direction = 1;
292 s.changed_at_secs = now_s;
293 }
294 });
295 window.focus(&st.read(cx).focus_handle.clone(), cx);
296 if cleaned == shown {
297 window.refresh();
298 return;
299 }
300 let result = save_fn.as_ref().map(|f| f(&cleaned)).unwrap_or(Ok(()));
302 match result {
303 Ok(()) => {
304 st.update(cx, |s, _| {
305 s.committed = cleaned.clone();
306 s.shown = cleaned.clone();
307 s.seen = cleaned.clone();
308 s.phase = InlineEditPhase::Saved;
309 s.direction = 1;
310 s.changed_at_secs = now_s;
311 s.phase_at_secs = now_s;
312 });
313 }
314 Err(msg) => {
315 st.update(cx, |s, _| {
316 s.shown = committed;
317 s.direction = -1;
318 s.changed_at_secs = now_s;
319 s.phase = InlineEditPhase::Failed;
320 s.failed_msg = Some(msg.clone());
321 s.phase_at_secs = now_s;
322 s.error = Some(msg);
323 });
324 let _ = label_key;
325 }
326 }
327 window.refresh();
328 };
329
330 let submit_for_key = submit.clone();
331
332 let editing_now = snap_state.editing;
333 let field = if editing_now {
334 div()
336 .flex_1()
337 .min_w_0()
338 .h(px(24.0))
339 .px(px(4.0))
340 .rounded(px(6.0))
341 .border_1()
342 .border_color(colors.control_fill)
343 .bg(colors.surface)
344 .text_size(Typography::TEXT_SM)
345 .text_color(colors.foreground)
346 .child(SharedString::from(displayed.clone()))
347 .into_any_element()
348 } else {
349 div().into_any_element()
350 };
351
352 let action_buttons = if editing_now {
353 let st_check = internal.clone();
354 let submit_check = submit_for_key.clone();
355 let st_cancel = internal.clone();
356 let focus_cancel = snap_state.focus_handle.clone();
357 vec![
358 BaseButton::new(ElementId::NamedChild(
359 self.id.clone().into(),
360 "save-button".into(),
361 ))
362 .accessibility_label("Save")
363 .on_click(move |_, window, cx| {
364 submit_check(&st_check, window, cx);
365 })
366 .size(px(24.0))
367 .flex()
368 .items_center()
369 .justify_center()
370 .rounded(px(6.0))
371 .text_color(colors.control_fill)
372 .cursor_pointer()
373 .hover(move |s| s.bg(colors.surface_muted))
374 .child(
375 div()
376 .text_size(Typography::TEXT_XS)
377 .child(SharedString::from("✓")),
378 ),
379 BaseButton::new(ElementId::NamedChild(
380 self.id.clone().into(),
381 "cancel-button".into(),
382 ))
383 .accessibility_label("Cancel")
384 .on_click(move |_, window, cx| {
385 let now_c = motion_now(cx);
386 st_cancel.update(cx, |s, _| {
387 s.editing = false;
388 s.error = None;
389 s.direction = -1;
390 s.changed_at_secs = now_c;
391 s.draft.clear();
392 });
393 window.focus(&focus_cancel.clone(), cx);
394 window.refresh();
395 })
396 .size(px(24.0))
397 .flex()
398 .items_center()
399 .justify_center()
400 .rounded(px(6.0))
401 .text_color(colors.text_muted)
402 .cursor_pointer()
403 .hover(move |s| s.bg(colors.surface_muted))
404 .child(
405 div()
406 .text_size(Typography::TEXT_XS)
407 .child(SharedString::from("×")),
408 ),
409 ]
410 } else {
411 vec![]
412 };
413 let _ = &field;
414
415 let display_click_st = internal.clone();
417 let display_click_focus = click_focus.clone();
418 let display_click_disabled = disabled_click || saving;
419
420 let msg_id = ElementId::NamedChild(self.id.clone().into(), "message".into());
421 let root_id = self.id.clone();
422
423 div()
424 .id(root_id)
425 .test_support()
426 .when_some(self.width, |this, w| this.w(w))
427 .when(self.width.is_none(), |this| this.w_full())
428 .flex()
429 .flex_col()
430 .gap(Spacing::S1)
431 .when(self.disabled, |this| this.opacity(0.5))
432 .child(
433 div()
434 .flex()
435 .flex_row()
436 .items_center()
437 .gap(px(4.0))
438 .child(
439 div()
440 .id(ElementId::NamedChild(
441 self.id.clone().into(),
442 "display".into(),
443 ))
444 .test_support()
445 .role(Role::Button)
446 .aria_label(self.label.clone())
447 .track_focus(&key_focus.clone())
448 .flex_1()
449 .min_w_0()
450 .px(px(if editing_now { 8.0 } else { 4.0 }))
451 .h(px(30.0))
452 .flex()
453 .flex_row()
454 .items_center()
455 .rounded(px(7.0))
456 .when(editing_now, |this| {
457 this.border_1()
458 .border_color(colors.control_fill)
459 .bg(colors.surface)
460 })
461 .when(!editing_now && !disabled_click, |this| {
462 this.cursor_pointer()
463 .hover(move |s| s.bg(colors.surface_muted))
464 })
465 .on_click(move |_, window, cx| {
466 if display_click_disabled {
467 return;
468 }
469 window.focus(&display_click_focus.clone(), cx);
470 if !display_click_st.read(cx).editing {
471 display_click_st.update(cx, |s, _| {
472 s.editing = true;
473 s.draft = s.shown.to_string();
474 s.error = None;
475 s.failed_msg = None;
476 });
477 }
478 window.refresh();
479 })
480 .on_key_down({
481 move |event: &KeyDownEvent, window, cx| {
482 let key = event.keystroke.key.as_str();
483 let mods = event.keystroke.modifiers;
484 if disabled_key {
485 return;
486 }
487 match key {
488 "enter" if editing_now => {
489 submit_for_key(&st_key, window, cx);
490 }
491 "escape" if editing_now => {
492 let now_e = motion_now(cx);
493 st_key.update(cx, |s, _| {
494 s.editing = false;
495 s.error = None;
496 s.direction = -1;
497 s.changed_at_secs = now_e;
498 s.draft.clear();
499 });
500 window.focus(&key_focus.clone(), cx);
501 window.refresh();
502 }
503 "enter" | " " | "space" if !editing_now => {
504 window.focus(&key_focus.clone(), cx);
505 st_key.update(cx, |s, _| {
506 s.editing = true;
507 s.draft = s.shown.to_string();
508 s.error = None;
509 });
510 window.refresh();
511 }
512 "backspace" if editing_now => {
513 st_key.update(cx, |s, _| {
514 s.draft.pop();
515 });
516 window.refresh();
517 }
518 "space" | " " if editing_now => {
519 st_key.update(cx, |s, _| {
520 s.draft.push(' ');
521 });
522 window.refresh();
523 }
524 k if editing_now && !mods.control && !mods.platform => {
525 let pushed = if let Some(kc) =
526 event.keystroke.key_char.as_deref()
527 && !kc.is_empty()
528 && kc.chars().all(|c| !c.is_control())
529 {
530 st_key.update(cx, |s, _| {
531 s.draft.push_str(kc);
532 });
533 true
534 } else if k.len() == 1
535 && let Some(ch) = k.chars().next()
536 && !ch.is_control()
537 {
538 let ch = if mods.shift {
539 ch.to_ascii_uppercase()
540 } else {
541 ch
542 };
543 st_key.update(cx, |s, _| {
544 s.draft.push(ch);
545 });
546 true
547 } else {
548 false
549 };
550 if pushed {
551 window.refresh();
552 }
553 }
554 _ => {}
555 }
556 }
557 })
558 .mt(px(text_y))
559 .opacity(text_op)
560 .child(
561 div()
562 .flex()
563 .flex_row()
564 .items_center()
565 .min_w_0()
566 .child(
567 div()
568 .text_size(Typography::TEXT_SM)
569 .font_medium()
570 .text_color(text_color)
571 .overflow_hidden()
572 .whitespace_nowrap()
573 .child(SharedString::from(displayed.clone())),
574 )
575 .when(editing_now, |this| {
576 this.child(
577 div()
578 .ml(px(1.5))
579 .w(px(1.5))
580 .h(px(15.0))
581 .bg(colors.control_fill),
582 )
583 }),
584 ),
585 )
586 .children(action_buttons)
587 .when(saved, |this| {
588 this.child(
589 div()
590 .w(px(16.0))
591 .h(px(16.0))
592 .flex_none()
593 .text_color(colors.success)
594 .text_size(Typography::TEXT_SM)
595 .child(SharedString::from("✓")),
596 )
597 }),
598 )
599 .child(render_field_message(
600 msg_id,
601 snap_state.error.clone().or(snap_state.failed_msg.clone()),
602 snap_state.error.is_some() || snap_state.failed_msg.is_some(),
603 window,
604 cx,
605 ))
606 }
607}
608
609#[cfg(test)]
610mod tests {
611 use std::cell::RefCell;
612
613 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
614 use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
615
616 use super::*;
617
618 struct InlineHost {
619 value: Rc<RefCell<SharedString>>,
620 events: Rc<RefCell<Vec<String>>>,
621 fail_next: Rc<RefCell<bool>>,
622 disabled: bool,
623 }
624
625 impl Render for InlineHost {
626 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
627 let events = self.events.clone();
628 let fail_next = self.fail_next.clone();
629 let value = self.value.borrow().clone();
630 let saved_value = self.value.clone();
631 div().w(px(420.0)).p(px(16.0)).child(
632 InlineEdit::new("inline-test", "Project name", value)
633 .validate(|next| {
634 if next.is_empty() {
635 Some("The name cannot be empty".into())
636 } else {
637 None
638 }
639 })
640 .disabled(self.disabled)
641 .on_save(move |next: &str| {
642 if *fail_next.borrow() {
643 *fail_next.borrow_mut() = false;
644 return Err("The server rejected the name".into());
646 }
647 events.borrow_mut().push(next.to_string());
648 *saved_value.borrow_mut() = next.into();
649 Ok(())
650 }),
651 )
652 }
653 }
654
655 fn inline_element(name: &str) -> ElementId {
656 ElementId::NamedChild(ElementId::Name("inline-test".into()).into(), name.into())
657 }
658
659 #[gpui_kit::test]
660 fn inline_edit_edits_saves_validates_and_rolls_back(cx: &mut TestAppContext) {
661 cx.update(|cx| {
662 gpui_kit::init(cx);
663 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
664 });
665
666 let host = InlineHost {
667 value: Rc::new(RefCell::new("Apollo".into())),
668 events: Rc::new(RefCell::new(Vec::new())),
669 fail_next: Rc::new(RefCell::new(false)),
670 disabled: false,
671 };
672 let events = host.events.clone();
673 let fail_next = host.fail_next.clone();
674 let (view, cx) = cx.add_window_view(|_, _| host);
675
676 cx.update(|window, cx| {
677 window.render_frame(cx);
678 let display = window.find(inline_element("display"));
679 assert_eq!(display.role(), Some(Role::Button));
680
681 if let Some(el) = window.try_find(inline_element("display")) {
683 let b = el.bounds();
684 eprintln!(
685 "CLICK-DISPLAY visible={} size=({},{})",
686 el.visible(),
687 f32::from(b.size.width),
688 f32::from(b.size.height)
689 );
690 } else {
691 eprintln!("CLICK-DISPLAY missing");
692 }
693 window.click(inline_element("display"), cx);
694 window.render_frame(cx);
695 window.press("backspace", cx);
696 window.press("enter", cx);
697 });
698 assert_eq!(events.borrow().as_slice(), ["Apoll".to_string()]);
699
700 cx.update(|window, cx| {
701 for _ in 0..3 {
702 window.render_frame(cx);
703 }
704 window.click(inline_element("display"), cx);
706 window.press("x", cx);
707 window.press("escape", cx);
708 });
709 assert_eq!(events.borrow().as_slice(), ["Apoll".to_string()]);
710 cx.executor()
712 .advance_clock(std::time::Duration::from_millis(300));
713
714 cx.update(|window, cx| {
716 window.click(inline_element("display"), cx);
717 window.render_frame(cx);
718 for _ in 0..8 {
719 window.press("backspace", cx);
720 }
721 window.press("enter", cx);
722 window.render_frame(cx);
723 });
724 assert_eq!(events.borrow().as_slice(), ["Apoll".to_string()]);
725 cx.executor()
726 .advance_clock(std::time::Duration::from_millis(300));
727
728 *fail_next.borrow_mut() = true;
730 cx.update(|window, cx| {
731 window.click(inline_element("display"), cx);
732 window.render_frame(cx);
733 window.press("backspace", cx);
734 window.press("enter", cx);
735 });
736 assert_eq!(events.borrow().as_slice(), ["Apoll".to_string()]);
737 cx.executor()
738 .advance_clock(std::time::Duration::from_millis(300));
739
740 view.update(cx, |host, cx| {
742 host.disabled = true;
743 cx.notify();
744 });
745 cx.executor()
746 .advance_clock(std::time::Duration::from_millis(300));
747 cx.update(|window, cx| {
748 for _ in 0..3 {
749 window.render_frame(cx);
750 }
751 window.click(inline_element("display"), cx);
752 window.render_frame(cx);
753 window.press("n", cx);
754 });
755 assert_eq!(events.borrow().as_slice(), ["Apoll".to_string()]);
756 }
757}