use super::attachments::{AttachmentBudget, clipboard_batch};
use super::{ChatInput, resize, sizing};
use crate::rich::{self, Format};
use gpui_kit::component::FocusableExt as _;
use gpui_kit::component::input::{InputGroup, InputGroupAddon, InputGroupAddonAlignment, Textarea};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
ClipboardEntry, ClipboardItem, Context, InteractiveElement as _, ParentElement as _,
StatefulInteractiveElement as _, Styled as _, Window, div, px, rems,
};
pub(super) fn group(input: &ChatInput, window: &Window, cx: &mut Context<ChatInput>) -> InputGroup {
let mut group = InputGroup::new("chat-input")
.rounded_none()
.border_0()
.focus_ring(false)
.aria_label("Chat message");
let editor_height = resize::height(input, window).map(|height| {
(height - sizing::minimum_height(f32::from(window.rem_size()))
+ f32::from(window.rem_size()) * sizing::EDITOR_REM)
.max(0.0)
});
if input
.message
.as_ref()
.is_some_and(|message| message.preview)
{
group = group.addon(
InputGroupAddon::new("message-markdown-preview")
.align(InputGroupAddonAlignment::BlockStart)
.p_0()
.child(preview(input, editor_height.unwrap_or_default(), cx)),
);
} else {
let input_entity = cx.entity().downgrade();
group = group.input(
Textarea::new(&input.state)
.disabled(input.disabled)
.on_paste(move |item, _, cx| {
let has_attachment = has_attachment(item);
if has_attachment {
let batch = clipboard_batch(item, AttachmentBudget::empty_draft());
let _ = input_entity.update(cx, |_, cx| {
cx.emit(super::ChatInputEvent::PasteAttachments(
super::AttachmentPaste(batch),
));
});
}
has_attachment
&& !item
.entries()
.iter()
.any(|entry| matches!(entry, ClipboardEntry::String(_)))
})
.when_some(editor_height, |editor, height| {
editor.min_h_0().h(px(height))
}),
);
}
group.when_some(input.render_addon(cx), |group, addon| {
group.addon(
InputGroupAddon::new("chat-input-toolbar")
.align(InputGroupAddonAlignment::BlockEnd)
.py(px(sizing::TOOLBAR_PADDING_PX))
.child(div().w_full().min_h(rems(sizing::TOOLBAR_REM)).child(addon)),
)
})
}
fn has_attachment(item: &ClipboardItem) -> bool {
item.entries().iter().any(|entry| {
matches!(
entry,
ClipboardEntry::Image(_) | ClipboardEntry::ExternalPaths(_)
)
})
}
fn preview(
input: &ChatInput,
height: f32,
cx: &Context<ChatInput>,
) -> gpui_kit::Stateful<gpui_kit::Div> {
let text = input.text(cx);
div()
.id("message-preview-body")
.w_full()
.h(px(height))
.overflow_y_scroll()
.p_2()
.text_color(crate::Tokens::current(cx).fg)
.when(text.trim().is_empty(), |preview| {
preview.child("Nothing to preview.")
})
.when(!text.trim().is_empty(), |preview| {
preview.child(rich::rich_text(
"message-preview-text",
Format::Markdown,
&text,
))
})
}