Skip to main content

subspace_dashboard/chat_input/
message.rs

1//! The same chat input with Markdown Write/Preview instead of agent settings.
2
3use super::{ChatInput, Context, IntoElement, Window};
4use crate::{
5    action::{Intent, action_button, icon_button},
6    panel::IconName,
7    tokens::Tokens,
8};
9use gpui_kit::component::button::ButtonVariants as _;
10use gpui_kit::component::{
11    ActiveTheme as _, Disableable as _, Selectable as _, Sizable as _, h_flex,
12};
13use gpui_kit::prelude::FluentBuilder as _;
14use gpui_kit::{
15    AnyElement, FocusHandle, InteractiveElement as _, ParentElement as _, SharedString,
16    Styled as _, TestSupportExt as _, div,
17};
18
19pub(super) struct CompactMessage {
20    pub label: SharedString,
21    pub input_name: SharedString,
22}
23
24pub(super) struct MessageState {
25    /// Write/Preview for Markdown; off for plain-text protocols.
26    pub markdown: bool,
27    pub compact: Option<CompactMessage>,
28    pub busy: bool,
29    pub submit_blocked: bool,
30    pub error: Option<String>,
31    pub preview: bool,
32    pub height: Option<f32>,
33    pub available: f32,
34    pub resize_focus: FocusHandle,
35}
36
37impl ChatInput {
38    /// A Markdown message input, sharing Copilot's minimum size and Enter bindings.
39    pub fn message(window: &mut Window, cx: &mut Context<Self>) -> Self {
40        Self::with_message(None, window, cx)
41    }
42
43    /// An inset plain-text composer with a labelled send action.
44    ///
45    /// An addon set on this composer appears before the shared send controls.
46    pub fn compact_message(
47        label: impl Into<SharedString>,
48        input_name: impl Into<SharedString>,
49        window: &mut Window,
50        cx: &mut Context<Self>,
51    ) -> Self {
52        let compact = CompactMessage {
53            label: label.into(),
54            input_name: input_name.into(),
55        };
56        Self::with_message(Some(compact), window, cx)
57    }
58
59    fn with_message(
60        compact: Option<CompactMessage>,
61        window: &mut Window,
62        cx: &mut Context<Self>,
63    ) -> Self {
64        Self {
65            message: Some(MessageState {
66                markdown: compact.is_none(),
67                compact,
68                busy: false,
69                submit_blocked: false,
70                error: None,
71                preview: false,
72                height: None,
73                available: 0.0,
74                resize_focus: cx.focus_handle(),
75            }),
76            ..Self::with_placeholder("Write a message…".into(), window, cx)
77        }
78    }
79
80    pub(super) fn compact(&self) -> Option<&CompactMessage> {
81        self.message.as_ref()?.compact.as_ref()
82    }
83
84    /// A plain-text message input for a protocol without Markdown, such as
85    /// IRC: no Write/Preview and no Markdown hint.
86    pub fn set_plain_text(&mut self, cx: &mut Context<Self>) {
87        if let Some(message) = &mut self.message {
88            message.markdown = false;
89            message.preview = false;
90        }
91        cx.notify();
92    }
93
94    // qual:api - controlled by a messaging board's asynchronous send.
95    pub fn set_busy(&mut self, busy: bool, cx: &mut Context<Self>) {
96        if let Some(message) = &mut self.message {
97            message.busy = busy;
98            message.error = None;
99        }
100        self.set_disabled(busy, cx);
101    }
102
103    // qual:api - read by a messaging board's tests of its send errors.
104    #[cfg(any(test, feature = "test-support"))]
105    pub fn error(&self) -> Option<&str> {
106        self.message.as_ref()?.error.as_deref()
107    }
108
109    // qual:api - controlled by a messaging board's asynchronous send.
110    pub fn set_error(&mut self, error: String, cx: &mut Context<Self>) {
111        self.set_busy(false, cx);
112        if let Some(message) = &mut self.message {
113            message.error = Some(error);
114        }
115        cx.notify();
116    }
117
118    /// Prevents submitting the message while leaving its draft editable.
119    // qual:api
120    pub fn set_submit_blocked(&mut self, blocked: bool, cx: &mut Context<Self>) {
121        if let Some(message) = &mut self.message
122            && message.submit_blocked != blocked
123        {
124            message.submit_blocked = blocked;
125            cx.notify();
126        }
127    }
128
129    /// The actual board height, excluding neighbouring panes and window chrome.
130    // qual:api
131    pub fn set_available_height(&mut self, available: f32, cx: &mut Context<Self>) {
132        if let Some(message) = &mut self.message
133            && crate::measure::changed(message.available, available)
134        {
135            message.available = available;
136            cx.notify();
137        }
138    }
139
140    fn set_preview(&mut self, preview: bool, window: &mut Window, cx: &mut Context<Self>) {
141        if let Some(message) = &mut self.message {
142            message.preview = preview;
143        }
144        if !preview {
145            self.focus(window, cx);
146        }
147        cx.notify();
148    }
149
150    pub(super) fn render_addon(
151        &self,
152        window: &mut Window,
153        cx: &mut Context<Self>,
154    ) -> Option<AnyElement> {
155        if let Some(compact) = self.compact() {
156            return self.compact_toolbar(&compact.label, window, cx);
157        }
158        if let Some(addon) = &self.addon {
159            return Some(addon.clone().into_any_element());
160        }
161        let message = self.message.as_ref()?;
162        Some(
163            h_flex()
164                .w_full()
165                .gap_1()
166                .when(message.markdown, |toolbar| {
167                    toolbar.children(Self::markdown_modes(message, cx))
168                })
169                .child(self.message_status(message, window, cx))
170                .child(self.message_send(message, cx))
171                .into_any_element(),
172        )
173    }
174
175    fn compact_toolbar(
176        &self,
177        label: &SharedString,
178        window: &mut Window,
179        cx: &mut Context<Self>,
180    ) -> Option<AnyElement> {
181        let message = self.message.as_ref()?;
182        let send = action_button(
183            "message-send",
184            Intent::Primary,
185            Some(IconName::CornerDownLeft),
186            label.clone(),
187        )
188        .loading(message.busy)
189        .disabled(!self.can_send(message, cx))
190        .on_click(cx.listener(|this, _, _, cx| this.enter(cx)));
191        Some(
192            h_flex()
193                .w_full()
194                .min_w_0()
195                .gap_2()
196                .children(self.addon.clone())
197                .child(self.message_status(message, window, cx))
198                .child(send)
199                .into_any_element(),
200        )
201    }
202
203    fn can_send(&self, message: &MessageState, cx: &gpui_kit::App) -> bool {
204        !self.disabled
205            && !message.submit_blocked
206            && (self.submit_empty || !self.text(cx).trim().is_empty())
207    }
208
209    fn message_status(
210        &self,
211        message: &MessageState,
212        window: &mut Window,
213        cx: &mut Context<Self>,
214    ) -> AnyElement {
215        let tokens = Tokens::current(cx);
216        if let Some(error) = &message.error {
217            return crate::truncated::text("message-status", error.clone())
218                .flex_1()
219                .min_w_0()
220                .text_xs()
221                .text_color(tokens.red)
222                .into_any_element();
223        }
224        if message.compact.is_some() {
225            let keys = if cx.platform_info().is_mac() {
226                "⇧↵ New line"
227            } else {
228                "Shift+Enter · New line"
229            };
230            return crate::truncated::text("message-status", keys)
231                .flex_1()
232                .min_w_0()
233                .text_right()
234                .text_size(tokens.caption_size())
235                .text_color(tokens.muted)
236                .into_any_element();
237        }
238        let target = hint_opacity(!self.text(cx).is_empty(), message.submit_blocked);
239        let opacity = gpui_kit::base::transition(
240            "message-hint-opacity",
241            target,
242            gpui_kit::base::Transition::new(cx.theme().motion_tokens().duration_fast),
243            window,
244            cx,
245        );
246        div()
247            .id("message-hint")
248            .test_support()
249            .flex_1()
250            .min_w_0()
251            .opacity(opacity)
252            .when(opacity == 0.0, |hint| hint.invisible())
253            .child(
254                crate::truncated::text(
255                    "message-status",
256                    send_hint(message.markdown, cx.platform_info().is_mac()),
257                )
258                .text_xs()
259                .text_color(tokens.muted),
260            )
261            .into_any_element()
262    }
263
264    /// The Write and Preview choices of a Markdown message.
265    fn markdown_modes(message: &MessageState, cx: &mut Context<Self>) -> [AnyElement; 2] {
266        [
267            action_button(
268                "message-write",
269                Intent::Quiet,
270                Some(IconName::Pencil),
271                "Write",
272            )
273            .selected(!message.preview)
274            .on_click(cx.listener(|this, _, window, cx| this.set_preview(false, window, cx)))
275            .into_any_element(),
276            action_button(
277                "message-preview",
278                Intent::Quiet,
279                Some(IconName::Eye),
280                "Preview",
281            )
282            .selected(message.preview)
283            .on_click(cx.listener(|this, _, window, cx| this.set_preview(true, window, cx)))
284            .into_any_element(),
285        ]
286    }
287
288    fn message_send(
289        &self,
290        message: &MessageState,
291        cx: &Context<Self>,
292    ) -> crate::icon_button::IconButton {
293        icon_button(
294            "message-send",
295            Intent::Primary,
296            IconName::ArrowUp,
297            "Send message",
298        )
299        .primary()
300        .small()
301        .rounded_full()
302        .loading(message.busy)
303        .disabled(self.disabled || message.submit_blocked || self.text(cx).trim().is_empty())
304        .on_click(cx.listener(|this, _, _, cx| this.enter(cx)))
305    }
306}
307
308fn hint_opacity(has_text: bool, blocked: bool) -> f32 {
309    if has_text || blocked { 0.0 } else { 1.0 }
310}
311
312/// The toolbar's key hint: Return (Enter off macOS) sends and Shift with it
313/// starts a new line, after `Markdown` when the draft takes Markdown.
314fn send_hint(markdown: bool, mac: bool) -> String {
315    let key = if mac { "Return" } else { "Enter" };
316    let keys = format!("{key} to send · Shift+{key} for a new line");
317    if markdown {
318        format!("Markdown · {keys}")
319    } else {
320        keys
321    }
322}
323
324#[cfg(test)]
325#[path = "message_hint_tests.rs"]
326mod hint_tests;
327#[cfg(test)]
328#[path = "message_tests.rs"]
329mod tests;
330
331impl super::ChatInput {
332    /// The owner service's intake budget. File reads remain the owner's responsibility.
333    pub fn set_attachment_budget(
334        &mut self,
335        budget: super::attachments::AttachmentBudget,
336        cx: &mut Context<Self>,
337    ) {
338        self.attachment_budget = budget;
339        cx.notify();
340    }
341}