BlueGit

ict rusty-teams

Files

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

rewrite.rs

rewrite.rs 17.7 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(BUTTON_ICON, COMPOSER_ICON_SIZE, theme::accent_text()))
112 .on_mouse_down(MouseButton::Left, |_, window, cx| {
113 window.prevent_default();
114 cx.stop_propagation();
115 })
116 .on_click(cx.listener(|this, _, _, cx| {
117 this.rewrite.open = !this.rewrite.open;
118 this.rewrite.adjust_menu = false;
119 cx.notify();
120 })),
121 )
122 }
123
124 pub(super) fn close_rewrite(&mut self) -> bool {
125 let was_open = self.rewrite.open;
126 self.rewrite.open = false;
127 self.rewrite.adjust_menu = false;
128 self.rewrite.custom_open = false;
129 self.rewrite.result = None;
130 self.rewrite.generation += 1;
131 was_open
132 }
133
134 fn request_rewrite(&mut self, action: ComposeAction, cx: &mut Context<Self>) {
135 self.rewrite.adjust_menu = false;
136 self.rewrite.generation += 1;
137 let generation = self.rewrite.generation;
138 let draft = self.current_draft(cx);
139 let demo = self.app.read(cx).mode.demo;
140 let engine = self.app.read(cx).engine.clone();
141 let Some(chat_id) = self.conversation_id.clone() else {
142 return;
143 };
144 let refusal = if draft.is_blank() {
145 Some(EMPTY_DRAFT)
146 } else if draft.text().contains([OBJECT_MARK, TABLE_MARK]) {
147 Some(TEXT_ONLY)
148 } else {
149 None
150 };
151 if let Some(refusal) = refusal {
152 self.rewrite.result = Some(RewriteResult {
153 action,
154 answer: RewriteAnswer::Failed(refusal.to_owned()),
155 });
156 cx.notify();
157 return;
158 }
159 self.rewrite.result = Some(RewriteResult {
160 action: action.clone(),
161 answer: RewriteAnswer::Waiting,
162 });
163 cx.notify();
164 let user_html = draft.to_html();
165 let receiver = (!demo)
166 .then_some(engine)
167 .flatten()
168 .map(|engine| runtime::spawn(async move { engine.rewrite_draft(&chat_id, &user_html, action).await }));
169 let demo_answer = demo_rewrite(&draft.plain_text());
170 cx.spawn(async move |this, cx| {
171 let answer = match receiver {
172 None => {
173 cx.background_executor().timer(DEMO_DELAY).await;
174 RewriteAnswer::Ready(Draft::from_markdown(&demo_answer))
175 }
176 Some(receiver) => match receiver.await {
177 Ok(Ok(html)) => RewriteAnswer::Ready(Draft::from_spans(&html_to_spans(&html)).trimmed()),
178 Ok(Err(error)) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
179 Err(error) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
180 },
181 };
182 this.update(cx, |this, cx| {
183 if this.rewrite.generation == generation
184 && let Some(result) = this.rewrite.result.as_mut()
185 {
186 result.answer = answer;
187 cx.notify();
188 }
189 })
190 .ok();
191 })
192 .detach();
193 }
194
195 fn replace_with_rewrite(&mut self, window: &mut Window, cx: &mut Context<Self>) {
196 let Some(RewriteAnswer::Ready(draft)) = self.rewrite.result.as_ref().map(|result| &result.answer) else {
197 return;
198 };
199 let draft = draft.clone();
200 self.close_rewrite();
201 self.load_draft(draft.clone(), InputContent::new(draft.text().to_owned()), window, cx);
202 self.mention_inputs.clear();
203 self.schedule_draft_save(cx);
204 self.focus(window, cx);
205 cx.notify();
206 }
207
208 fn open_custom(&mut self, window: &mut Window, cx: &mut Context<Self>) {
209 self.rewrite.adjust_menu = false;
210 self.rewrite.custom_open = true;
211 if self.rewrite.custom_input.is_none() {
212 let input = cx.new(|cx| InputState::new(window, cx).placeholder(CUSTOM_PLACEHOLDER));
213 let subscription = cx.subscribe_in(&input, window, |this, input, event: &InputEvent, window, cx| {
214 if matches!(event, InputEvent::PressEnter { .. }) {
215 let prompt = input.read(cx).value().trim().to_owned();
216 if !prompt.is_empty() {
217 input.update(cx, |input, cx| input.set_value("", window, cx));
218 this.rewrite.custom_open = false;
219 this.request_rewrite(ComposeAction::Custom(prompt), cx);
220 }
221 }
222 });
223 self.rewrite.custom_input = Some(input);
224 self.rewrite._custom_events = Some(subscription);
225 }
226 if let Some(input) = &self.rewrite.custom_input {
227 input.update(cx, |input, cx| input.focus(window, cx));
228 }
229 cx.notify();
230 }
231
232 pub(super) fn render_rewrite_panel(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
233 if !self.rewrite.open || !self.rewrite_available(cx) {
234 return None;
235 }
236 let busy = matches!(
237 self.rewrite.result.as_ref().map(|result| &result.answer),
238 Some(RewriteAnswer::Waiting)
239 );
240 let chips = h_flex()
241 .w_full()
242 .gap(px(8.))
243 .items_center()
244 .child(self.choice_chip(Choice::Rewrite, busy, cx))
245 .child(self.choice_chip(Choice::Proofread, busy, cx))
246 .child(
247 div()
248 .relative()
249 .child(self.adjust_chip(busy, cx))
250 .children(self.render_adjust_menu(cx)),
251 )
252 .child(div().flex_1())
253 .child(
254 div()
255 .id("composer-copilot-close")
256 .size(px(CHIP_HEIGHT))
257 .flex()
258 .items_center()
259 .justify_center()
260 .rounded(px(6.))
261 .cursor_pointer()
262 .hover(|button| button.bg(theme::popup_hover()))
263 .popup_trigger_tooltip_text(false, CLOSE_LABEL)
264 .child(symbol("close", CHIP_ICON, theme::text_soft()))
265 .on_click(cx.listener(|this, _, _, cx| {
266 this.close_rewrite();
267 cx.notify();
268 })),
269 );
270 let custom = self
271 .rewrite
272 .custom_open
273 .then(|| self.rewrite.custom_input.clone())
274 .flatten()
275 .map(|input| {
276 div()
277 .w_full()
278 .px(px(12.))
279 .py(px(8.))
280 .rounded(px(CARD_RADIUS))
281 .bg(theme::surface_raised())
282 .child(Input::new(&input).appearance(false).bordered(false))
283 });
284 Some(
285 v_flex()
286 .id(REWRITE_PANEL_TAG)
287 .debug_selector(|| REWRITE_PANEL_TAG.into())
288 .absolute()
289 .bottom(relative(1.))
290 .right_0()
291 .mb(px(6.))
292 .w(px(PANEL_WIDTH))
293 .max_w(relative(1.))
294 .p(px(PANEL_PADDING))
295 .gap(px(12.))
296 .rounded(px(PANEL_RADIUS))
297 .flyout_surface()
298 .occlude()
299 .child(chips)
300 .children(custom)
301 .children(self.render_rewrite_result(cx))
302 .into_any_element(),
303 )
304 }
305
306 fn chip(id: &'static str, icon: &'static str, label: &'static str, busy: bool) -> Stateful<Div> {
307 h_flex()
308 .id(id)
309 .h(px(CHIP_HEIGHT))
310 .px(px(12.))
311 .gap(px(6.))
312 .items_center()
313 .rounded(px(6.))
314 .bg(theme::surface_raised())
315 .text_size(px(13.))
316 .font_weight(FontWeight::SEMIBOLD)
317 .text_color(theme::text())
318 .child(symbol(icon, CHIP_ICON, theme::text_soft()))
319 .child(label)
320 .when(busy, |chip| chip.opacity(0.5))
321 .when(!busy, |chip| chip.cursor_pointer().hover(|chip| chip.bg(theme::popup_hover())))
322 }
323
324 fn choice_chip(&self, choice: Choice, busy: bool, cx: &mut Context<Self>) -> Stateful<Div> {
325 let (id, icon, action) = match choice {
326 Choice::Rewrite => ("composer-copilot-rewrite", BUTTON_ICON, ComposeAction::Rewrite),
327 Choice::Proofread => ("composer-copilot-proofread", "spellcheck", ComposeAction::Proofread),
328 };
329 let label = match choice {
330 Choice::Rewrite => "Rewrite",
331 Choice::Proofread => "Proofread",
332 };
333 Self::chip(id, icon, label, busy).when(!busy, |chip| {
334 chip.on_click(cx.listener(move |this, _, _, cx| this.request_rewrite(action.clone(), cx)))
335 })
336 }
337
338 fn adjust_chip(&self, busy: bool, cx: &mut Context<Self>) -> Stateful<Div> {
339 Self::chip("composer-copilot-adjust", "more_horiz", ADJUST_LABEL, busy)
340 .child(symbol("keyboard_arrow_down", CHIP_ICON, theme::text_soft()))
341 .when(!busy, |chip| {
342 chip.on_click(cx.listener(|this, _, _, cx| {
343 this.rewrite.adjust_menu = !this.rewrite.adjust_menu;
344 cx.notify();
345 }))
346 })
347 }
348
349 fn render_adjust_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
350 if !self.rewrite.adjust_menu {
351 return None;
352 }
353 let item = |id: &'static str, label: &'static str| {
354 div()
355 .id(id)
356 .w_full()
357 .h(MENU_ITEM_HEIGHT)
358 .px(MENU_ITEM_PADDING_X)
359 .flex()
360 .items_center()
361 .rounded(px(6.))
362 .cursor_pointer()
363 .hover(|row| row.bg(theme::popup_hover()))
364 .text_size(px(13.))
365 .text_color(theme::text())
366 .child(label)
367 };
368 let custom = item("composer-copilot-custom", CUSTOM_LABEL)
369 .on_click(cx.listener(|this, _, window, cx| this.open_custom(window, cx)));
370 let adjustments = ComposeAdjustment::ALL.into_iter().map(|adjustment| {
371 item(adjustment.label(), adjustment.label()).on_click(cx.listener(move |this, _, _, cx| {
372 this.request_rewrite(ComposeAction::Adjust(adjustment), cx)
373 }))
374 });
375 Some(
376 v_flex()
377 .id("composer-copilot-adjust-menu")
378 .absolute()
379 .bottom(relative(1.))
380 .left_0()
381 .mb(px(4.))
382 .w(px(ADJUST_MENU_WIDTH))
383 .p(MENU_LIST_PADDING)
384 .gap(MENU_ITEM_GAP)
385 .rounded(px(10.))
386 .flyout_surface()
387 .occlude()
388 .on_mouse_down_out(cx.listener(|this, _, _, cx| {
389 this.rewrite.adjust_menu = false;
390 cx.notify();
391 }))
392 .child(custom)
393 .children(adjustments)
394 .into_any_element(),
395 )
396 }
397
398 fn render_rewrite_result(&self, cx: &mut Context<Self>) -> Option<Div> {
399 let result = self.rewrite.result.as_ref()?;
400 let card = v_flex()
401 .w_full()
402 .p(px(PANEL_PADDING))
403 .gap(px(12.))
404 .rounded(px(CARD_RADIUS))
405 .bg(theme::surface_raised())
406 .child(
407 div()
408 .text_size(px(12.))
409 .text_color(theme::text_soft())
410 .child(result.action.label().to_owned()),
411 );
412 Some(match &result.answer {
413 RewriteAnswer::Waiting => card.child(
414 h_flex()
415 .gap(px(8.))
416 .items_center()
417 .child(spinner(16.))
418 .child(div().text_size(px(14.)).text_color(theme::text_soft()).child(WORKING)),
419 ),
420 RewriteAnswer::Failed(reason) => {
421 card.child(div().text_size(px(14.)).text_color(theme::text_soft()).child(reason.clone()))
422 }
423 RewriteAnswer::Ready(draft) => card
424 .child(div().text_size(px(14.)).text_color(theme::text()).child(draft.plain_text()))
425 .child(
426 h_flex()
427 .w_full()
428 .items_center()
429 .justify_between()
430 .child(
431 div()
432 .id("composer-copilot-replace")
433 .h(px(CHIP_HEIGHT))
434 .px(px(24.))
435 .flex()
436 .items_center()
437 .rounded(px(6.))
438 .bg(theme::accent())
439 .text_color(theme::on_accent())
440 .text_size(px(14.))
441 .font_weight(FontWeight::SEMIBOLD)
442 .cursor_pointer()
443 .hover(|button| button.opacity(0.85))
444 .child(REPLACE_LABEL)
445 .on_click(cx.listener(|this, _, window, cx| this.replace_with_rewrite(window, cx))),
446 )
447 .child(div().text_size(px(11.)).text_color(theme::text_muted()).child(DISCLAIMER)),
448 ),
449 })
450 }
451}
452
453fn demo_rewrite(text: &str) -> String {
454 let trimmed = text.trim().trim_end_matches(['.', '!', '?']);
455 let mut characters = trimmed.chars();
456 let capitalized: String = characters
457 .next()
458 .map(|first| first.to_uppercase().chain(characters).collect())
459 .unwrap_or_default();
460 format!("{capitalized}.")
461}
462
463#[cfg(test)]
464mod tests {
465 use super::demo_rewrite;
466
467 #[test]
468 fn the_demo_answer_tidies_the_draft() {
469 assert_eq!(demo_rewrite(" hallo zusammen!! "), "Hallo zusammen.");
470 }
471}