BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / composer / rewrite.rs

rewrite.rs

rewrite.rs 17.8 KiB Download Raw
1use gpui_kit::component::fluent::{
2 MENU_ITEM_GAP, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X, MENU_LIST_PADDING,
3};
4use gpui_kit::component::input::{Input, InputContent, InputEvent, InputState};
5use gpui_kit::component::tooltip::PopupTriggerTooltip as _;
6use gpui_kit::component::{h_flex, v_flex};
7use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::*;
9use teams_core::{ComposeAction, ComposeAdjustment, Draft, OBJECT_MARK, TABLE_MARK, html_to_spans};
10
11use super::{COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer};
12use crate::runtime;
13use app_ui_kit::spinner::spinner;
14use crate::theme::{self, ElevatedSurface as _};
15use crate::views::widgets::symbol;
16
17pub const REWRITE_BUTTON_TAG: &str = "composer/actions/copilot";
18pub const REWRITE_PANEL_TAG: &str = "composer/copilot";
19const BUTTON_LABEL: &str = "Write with Copilot";
20const CLOSE_LABEL: &str = "Close";
21const ADJUST_LABEL: &str = "Adjust";
22const CUSTOM_LABEL: &str = "Customised";
23const CUSTOM_PLACEHOLDER: &str = "Describe how to adjust it, e.g. make it sound friendlier";
24const REPLACE_LABEL: &str = "Replace";
25const DISCLAIMER: &str = "AI-generated content may be incorrect";
26const WORKING: &str = "Copilot is writing ...";
27const FAILED: &str = "Copilot could not rewrite this:";
28const EMPTY_DRAFT: &str = "Type a message first, then let Copilot rewrite it.";
29const TEXT_ONLY: &str = "Copilot rewrites text only. Move images and tables out of the message first.";
30const BUTTON_ICON: &str = "auto_fix_high";
31const PANEL_WIDTH: f32 = 600.;
32const PANEL_PADDING: f32 = 16.;
33const PANEL_RADIUS: f32 = 10.;
34const CARD_RADIUS: f32 = 8.;
35const CHIP_HEIGHT: f32 = 32.;
36const CHIP_ICON: f32 = 16.;
37const ADJUST_MENU_WIDTH: f32 = 200.;
38const BUTTON_MIN_COMPOSER_WIDTH: f32 = 320.;
39const DEMO_DELAY: std::time::Duration = std::time::Duration::from_millis(700);
40
41#[derive(Default)]
42pub(super) struct RewritePanel {
43 open: bool,
44 adjust_menu: bool,
45 result: Option<RewriteResult>,
46 generation: u64,
47 custom_input: Option<Entity<InputState>>,
48 custom_open: bool,
49 _custom_events: Option<Subscription>,
50}
51
52impl RewritePanel {
53 pub(super) fn input_focused(&self, window: &Window, cx: &App) -> bool {
54 self.custom_input
55 .as_ref()
56 .is_some_and(|input| input.read(cx).focus_handle(cx).is_focused(window))
57 }
58}
59
60struct RewriteResult {
61 action: ComposeAction,
62 answer: RewriteAnswer,
63}
64
65enum RewriteAnswer {
66 Waiting,
67 Ready(Draft),
68 Failed(String),
69}
70
71#[derive(Clone, Copy, PartialEq, Eq)]
72enum Choice {
73 Rewrite,
74 Proofread,
75}
76
77impl Composer {
78 fn rewrite_available(&self, cx: &App) -> bool {
79 let state = self.app.read(cx);
80 self.editing.is_none()
81 && (state.mode.demo || state.engine.is_some())
82 && self
83 .conversation_id
84 .as_deref()
85 .is_some_and(|conversation_id| state.sidebar.chats.iter().any(|chat| chat.id == conversation_id))
86 }
87
88 pub(super) fn render_rewrite_button(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
89 let fits = self
90 .composer_bounds
91 .get()
92 .is_none_or(|bounds| f32::from(bounds.size.width) >= BUTTON_MIN_COMPOSER_WIDTH);
93 if !fits || !self.rewrite_available(cx) {
94 return None;
95 }
96 let open = self.rewrite.open;
97 Some(
98 div()
99 .id("composer-copilot")
100 .debug_selector(|| REWRITE_BUTTON_TAG.into())
101 .size(px(COMPOSER_BUTTON_SIZE))
102 .flex_none()
103 .flex()
104 .items_center()
105 .justify_center()
106 .rounded(px(8.))
107 .cursor_pointer()
108 .when(open, |button| button.bg(theme::popup_hover()))
109 .hover(|button| button.bg(theme::popup_hover()))
110 .popup_trigger_tooltip_text(open, BUTTON_LABEL)
111 .child(symbol(
112 BUTTON_ICON,
113 COMPOSER_ICON_SIZE,
114 if open { theme::accent_text() } else { theme::text_muted() },
115 ))
116 .on_mouse_down(MouseButton::Left, |_, window, cx| {
117 window.prevent_default();
118 cx.stop_propagation();
119 })
120 .on_click(cx.listener(|this, _, _, cx| {
121 this.rewrite.open = !this.rewrite.open;
122 this.rewrite.adjust_menu = false;
123 cx.notify();
124 })),
125 )
126 }
127
128 pub(super) fn close_rewrite(&mut self) -> bool {
129 let was_open = self.rewrite.open;
130 self.rewrite.open = false;
131 self.rewrite.adjust_menu = false;
132 self.rewrite.custom_open = false;
133 self.rewrite.result = None;
134 self.rewrite.generation += 1;
135 was_open
136 }
137
138 fn request_rewrite(&mut self, action: ComposeAction, cx: &mut Context<Self>) {
139 self.rewrite.adjust_menu = false;
140 self.rewrite.generation += 1;
141 let generation = self.rewrite.generation;
142 let draft = self.current_draft(cx);
143 let demo = self.app.read(cx).mode.demo;
144 let engine = self.app.read(cx).engine.clone();
145 let Some(chat_id) = self.conversation_id.clone() else {
146 return;
147 };
148 let refusal = if draft.is_blank() {
149 Some(EMPTY_DRAFT)
150 } else if draft.text().contains([OBJECT_MARK, TABLE_MARK]) {
151 Some(TEXT_ONLY)
152 } else {
153 None
154 };
155 if let Some(refusal) = refusal {
156 self.rewrite.result = Some(RewriteResult {
157 action,
158 answer: RewriteAnswer::Failed(refusal.to_owned()),
159 });
160 cx.notify();
161 return;
162 }
163 self.rewrite.result = Some(RewriteResult {
164 action: action.clone(),
165 answer: RewriteAnswer::Waiting,
166 });
167 cx.notify();
168 let user_html = draft.to_html();
169 let receiver = (!demo)
170 .then_some(engine)
171 .flatten()
172 .map(|engine| runtime::spawn(async move { engine.rewrite_draft(&chat_id, &user_html, action).await }));
173 let demo_answer = demo_rewrite(&draft.plain_text());
174 cx.spawn(async move |this, cx| {
175 let answer = match receiver {
176 None => {
177 cx.background_executor().timer(DEMO_DELAY).await;
178 RewriteAnswer::Ready(Draft::from_markdown(&demo_answer))
179 }
180 Some(receiver) => match receiver.await {
181 Ok(Ok(html)) => RewriteAnswer::Ready(Draft::from_spans(&html_to_spans(&html)).trimmed()),
182 Ok(Err(error)) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
183 Err(error) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
184 },
185 };
186 this.update(cx, |this, cx| {
187 if this.rewrite.generation == generation
188 && let Some(result) = this.rewrite.result.as_mut()
189 {
190 result.answer = answer;
191 cx.notify();
192 }
193 })
194 .ok();
195 })
196 .detach();
197 }
198
199 fn replace_with_rewrite(&mut self, window: &mut Window, cx: &mut Context<Self>) {
200 let Some(RewriteAnswer::Ready(draft)) = self.rewrite.result.as_ref().map(|result| &result.answer) else {
201 return;
202 };
203 let draft = draft.clone();
204 self.close_rewrite();
205 self.load_draft(draft.clone(), InputContent::new(draft.text().to_owned()), window, cx);
206 self.mention_inputs.clear();
207 self.schedule_draft_save(cx);
208 self.focus(window, cx);
209 cx.notify();
210 }
211
212 fn open_custom(&mut self, window: &mut Window, cx: &mut Context<Self>) {
213 self.rewrite.adjust_menu = false;
214 self.rewrite.custom_open = true;
215 if self.rewrite.custom_input.is_none() {
216 let input = cx.new(|cx| InputState::new(window, cx).placeholder(CUSTOM_PLACEHOLDER));
217 let subscription = cx.subscribe_in(&input, window, |this, input, event: &InputEvent, window, cx| {
218 if matches!(event, InputEvent::PressEnter { .. }) {
219 let prompt = input.read(cx).value().trim().to_owned();
220 if !prompt.is_empty() {
221 input.update(cx, |input, cx| input.set_value("", window, cx));
222 this.rewrite.custom_open = false;
223 this.request_rewrite(ComposeAction::Custom(prompt), cx);
224 }
225 }
226 });
227 self.rewrite.custom_input = Some(input);
228 self.rewrite._custom_events = Some(subscription);
229 }
230 if let Some(input) = &self.rewrite.custom_input {
231 input.update(cx, |input, cx| input.focus(window, cx));
232 }
233 cx.notify();
234 }
235
236 pub(super) fn render_rewrite_panel(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
237 if !self.rewrite.open || !self.rewrite_available(cx) {
238 return None;
239 }
240 let busy = matches!(
241 self.rewrite.result.as_ref().map(|result| &result.answer),
242 Some(RewriteAnswer::Waiting)
243 );
244 let chips = h_flex()
245 .w_full()
246 .gap(px(8.))
247 .items_center()
248 .child(self.choice_chip(Choice::Rewrite, busy, cx))
249 .child(self.choice_chip(Choice::Proofread, busy, cx))
250 .child(
251 div()
252 .relative()
253 .child(self.adjust_chip(busy, cx))
254 .children(self.render_adjust_menu(cx)),
255 )
256 .child(div().flex_1())
257 .child(
258 div()
259 .id("composer-copilot-close")
260 .size(px(CHIP_HEIGHT))
261 .flex()
262 .items_center()
263 .justify_center()
264 .rounded(px(6.))
265 .cursor_pointer()
266 .hover(|button| button.bg(theme::popup_hover()))
267 .popup_trigger_tooltip_text(false, CLOSE_LABEL)
268 .child(symbol("close", CHIP_ICON, theme::text_soft()))
269 .on_click(cx.listener(|this, _, _, cx| {
270 this.close_rewrite();
271 cx.notify();
272 })),
273 );
274 let custom = self
275 .rewrite
276 .custom_open
277 .then(|| self.rewrite.custom_input.clone())
278 .flatten()
279 .map(|input| {
280 div()
281 .w_full()
282 .px(px(12.))
283 .py(px(8.))
284 .rounded(px(CARD_RADIUS))
285 .bg(theme::surface_raised())
286 .child(Input::new(&input).appearance(false).bordered(false))
287 });
288 Some(
289 v_flex()
290 .id(REWRITE_PANEL_TAG)
291 .debug_selector(|| REWRITE_PANEL_TAG.into())
292 .absolute()
293 .bottom(relative(1.))
294 .right_0()
295 .mb(px(6.))
296 .w(px(PANEL_WIDTH))
297 .max_w(relative(1.))
298 .p(px(PANEL_PADDING))
299 .gap(px(12.))
300 .rounded(px(PANEL_RADIUS))
301 .flyout_surface()
302 .occlude()
303 .child(chips)
304 .children(custom)
305 .children(self.render_rewrite_result(cx))
306 .into_any_element(),
307 )
308 }
309
310 fn chip(id: &'static str, icon: &'static str, label: &'static str, busy: bool) -> Stateful<Div> {
311 h_flex()
312 .id(id)
313 .h(px(CHIP_HEIGHT))
314 .px(px(12.))
315 .gap(px(6.))
316 .items_center()
317 .rounded(px(6.))
318 .bg(theme::surface_raised())
319 .text_size(px(13.))
320 .font_weight(FontWeight::SEMIBOLD)
321 .text_color(theme::text())
322 .child(symbol(icon, CHIP_ICON, theme::text_soft()))
323 .child(label)
324 .when(busy, |chip| chip.opacity(0.5))
325 .when(!busy, |chip| chip.cursor_pointer().hover(|chip| chip.bg(theme::popup_hover())))
326 }
327
328 fn choice_chip(&self, choice: Choice, busy: bool, cx: &mut Context<Self>) -> Stateful<Div> {
329 let (id, icon, action) = match choice {
330 Choice::Rewrite => ("composer-copilot-rewrite", BUTTON_ICON, ComposeAction::Rewrite),
331 Choice::Proofread => ("composer-copilot-proofread", "spellcheck", ComposeAction::Proofread),
332 };
333 let label = match choice {
334 Choice::Rewrite => "Rewrite",
335 Choice::Proofread => "Proofread",
336 };
337 Self::chip(id, icon, label, busy).when(!busy, |chip| {
338 chip.on_click(cx.listener(move |this, _, _, cx| this.request_rewrite(action.clone(), cx)))
339 })
340 }
341
342 fn adjust_chip(&self, busy: bool, cx: &mut Context<Self>) -> Stateful<Div> {
343 Self::chip("composer-copilot-adjust", "more_horiz", ADJUST_LABEL, busy)
344 .child(symbol("keyboard_arrow_down", CHIP_ICON, theme::text_soft()))
345 .when(!busy, |chip| {
346 chip.on_click(cx.listener(|this, _, _, cx| {
347 this.rewrite.adjust_menu = !this.rewrite.adjust_menu;
348 cx.notify();
349 }))
350 })
351 }
352
353 fn render_adjust_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
354 if !self.rewrite.adjust_menu {
355 return None;
356 }
357 let item = |id: &'static str, label: &'static str| {
358 div()
359 .id(id)
360 .w_full()
361 .h(MENU_ITEM_HEIGHT)
362 .px(MENU_ITEM_PADDING_X)
363 .flex()
364 .items_center()
365 .rounded(px(6.))
366 .cursor_pointer()
367 .hover(|row| row.bg(theme::popup_hover()))
368 .text_size(px(13.))
369 .text_color(theme::text())
370 .child(label)
371 };
372 let custom = item("composer-copilot-custom", CUSTOM_LABEL)
373 .on_click(cx.listener(|this, _, window, cx| this.open_custom(window, cx)));
374 let adjustments = ComposeAdjustment::ALL.into_iter().map(|adjustment| {
375 item(adjustment.label(), adjustment.label()).on_click(cx.listener(move |this, _, _, cx| {
376 this.request_rewrite(ComposeAction::Adjust(adjustment), cx)
377 }))
378 });
379 Some(
380 v_flex()
381 .id("composer-copilot-adjust-menu")
382 .absolute()
383 .bottom(relative(1.))
384 .left_0()
385 .mb(px(4.))
386 .w(px(ADJUST_MENU_WIDTH))
387 .p(MENU_LIST_PADDING)
388 .gap(MENU_ITEM_GAP)
389 .rounded(px(10.))
390 .flyout_surface()
391 .occlude()
392 .on_mouse_down_out(cx.listener(|this, _, _, cx| {
393 this.rewrite.adjust_menu = false;
394 cx.notify();
395 }))
396 .child(custom)
397 .children(adjustments)
398 .into_any_element(),
399 )
400 }
401
402 fn render_rewrite_result(&self, cx: &mut Context<Self>) -> Option<Div> {
403 let result = self.rewrite.result.as_ref()?;
404 let card = v_flex()
405 .w_full()
406 .p(px(PANEL_PADDING))
407 .gap(px(12.))
408 .rounded(px(CARD_RADIUS))
409 .bg(theme::surface_raised())
410 .child(
411 div()
412 .text_size(px(12.))
413 .text_color(theme::text_soft())
414 .child(result.action.label().to_owned()),
415 );
416 Some(match &result.answer {
417 RewriteAnswer::Waiting => card.child(
418 h_flex()
419 .gap(px(8.))
420 .items_center()
421 .child(spinner(16.))
422 .child(div().text_size(px(14.)).text_color(theme::text_soft()).child(WORKING)),
423 ),
424 RewriteAnswer::Failed(reason) => {
425 card.child(div().text_size(px(14.)).text_color(theme::text_soft()).child(reason.clone()))
426 }
427 RewriteAnswer::Ready(draft) => card
428 .child(div().text_size(px(14.)).text_color(theme::text()).child(draft.plain_text()))
429 .child(
430 h_flex()
431 .w_full()
432 .items_center()
433 .justify_between()
434 .child(
435 div()
436 .id("composer-copilot-replace")
437 .h(px(CHIP_HEIGHT))
438 .px(px(24.))
439 .flex()
440 .items_center()
441 .rounded(px(6.))
442 .bg(theme::accent())
443 .text_color(theme::on_accent())
444 .text_size(px(14.))
445 .font_weight(FontWeight::SEMIBOLD)
446 .cursor_pointer()
447 .hover(|button| button.opacity(0.85))
448 .child(REPLACE_LABEL)
449 .on_click(cx.listener(|this, _, window, cx| this.replace_with_rewrite(window, cx))),
450 )
451 .child(div().text_size(px(11.)).text_color(theme::text_muted()).child(DISCLAIMER)),
452 ),
453 })
454 }
455}
456
457fn demo_rewrite(text: &str) -> String {
458 let trimmed = text.trim().trim_end_matches(['.', '!', '?']);
459 let mut characters = trimmed.chars();
460 let capitalized: String = characters
461 .next()
462 .map(|first| first.to_uppercase().chain(characters).collect())
463 .unwrap_or_default();
464 format!("{capitalized}.")
465}
466
467#[cfg(test)]
468mod tests {
469 use super::demo_rewrite;
470
471 #[test]
472 fn the_demo_answer_tidies_the_draft() {
473 assert_eq!(demo_rewrite(" hallo zusammen!! "), "Hallo zusammen.");
474 }
475}