A file or image attachment with media, name, metadata, upload state and actions.
use std::time::Duration;
use gpui::{div, prelude::*, px, svg, Context, Entity, Task, Window};
use crate::theme::ActiveTheme;
use crate::ui::attachment::{Attachment, AttachmentGroup, AttachmentState};
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::input::TextInput;
use crate::ui::spinner::Spinner;
use crate::icons::{ARROW_UP, FILE_CODE, FILE_TEXT, FILE_VIDEO, REFRESH_CCW, X};
/// Stands in for the time a real upload takes.
const UPLOAD_TIME: Duration = Duration::from_millis(2500);
struct File {
id: usize,
name: &'static str,
details: &'static str,
icon: &'static [u8],
state: AttachmentState,
}
#[derive(Default)]
pub struct AttachmentDemo {
files: Vec<File>,
composer: Option<Entity<TextInput>>,
uploads: Vec<Task<()>>,
}
impl AttachmentDemo {
fn upload(&mut self, id: usize, cx: &mut Context<Self>) {
if let Some(file) = self.files.iter_mut().find(|file| file.id == id) {
file.state = AttachmentState::Uploading;
}
self.uploads.push(cx.spawn(async move |this, cx| {
cx.background_executor().timer(UPLOAD_TIME).await;
this.update(cx, |this, cx| {
if let Some(file) = this.files.iter_mut().find(|file| file.id == id) {
file.state = AttachmentState::Done;
}
cx.notify();
})
.ok();
}));
cx.notify();
}
}
impl Render for AttachmentDemo {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
if self.composer.is_none() {
self.composer = Some(cx.new(|cx| {
TextInput::new(cx)
.placeholder("Ask about these files...")
.bare()
}));
self.files = vec![
File {
id: 0,
name: "q3-sales.pdf",
details: "PDF · 2.4 MB",
icon: FILE_TEXT,
state: AttachmentState::Done,
},
File {
id: 1,
name: "schema.ts",
details: "TypeScript · 18 KB",
icon: FILE_CODE,
state: AttachmentState::Done,
},
File {
id: 2,
name: "demo.mov",
details: "Upload failed",
icon: FILE_VIDEO,
state: AttachmentState::Error,
},
];
self.upload(1, cx);
}
let theme = cx.theme();
let (muted_fg, primary_fg) = (theme.muted_foreground, theme.primary_foreground);
let icon = |data: &'static [u8], color| svg().data(data).size(px(14.0)).text_color(color);
let attachments = self.files.iter().map(|file| {
let id = file.id;
let uploading = file.state == AttachmentState::Uploading;
let failed = file.state == AttachmentState::Error;
let attachment = Attachment::new(("file", id))
.title(file.name)
.description(if uploading {
"Uploading..."
} else {
file.details
})
.state(file.state)
.map(|this| {
if uploading {
this.media(Spinner::new().color(muted_fg))
} else {
this.icon(file.icon)
}
});
let attachment = if failed {
attachment.action(
Button::new(("retry", id), "")
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Xs)
.icon_only()
.leading(icon(REFRESH_CCW, muted_fg))
.on_click(cx.listener(move |this, _, _, cx| this.upload(id, cx))),
)
} else {
attachment
};
attachment.action(
Button::new(("remove", id), "")
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Xs)
.icon_only()
.leading(icon(X, muted_fg))
.on_click(cx.listener(move |this, _, _, cx| {
this.files.retain(|file| file.id != id);
cx.notify();
})),
)
});
let composer = self.composer.clone();
div()
.w(px(648.0))
.flex()
.flex_col()
.gap_3()
.p_3()
.rounded(theme.radius + px(4.0))
.border_1()
.border_color(theme.input)
.bg(theme.background)
.shadow_xs()
.child(AttachmentGroup::new("files").children(attachments))
.when(self.files.is_empty(), |this| {
this.child(
div()
.text_sm()
.text_color(muted_fg)
.child("No files attached."),
)
})
.child(
div()
.flex()
.items_center()
.gap_2()
.child(div().flex_1().min_w_0().children(composer))
.child(
Button::new("send", "")
.size(ButtonSize::Sm)
.icon_only()
.rounded_full()
.leading(icon(ARROW_UP, primary_fg)),
),
)
}
}Installation
Copies src/ui/attachment.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Copy the source
Paste the code below into
src/ui/attachment.rs.src/ui/attachment.rs use std::time::Duration; use gpui::{ div, prelude::*, pulsating_between, px, svg, Animation, AnimationExt, AnyElement, App, ClickEvent, ElementId, FontWeight, MouseButton, Pixels, SharedString, Window, }; use crate::theme::ActiveTheme; /// One shimmer sweep. GPUI can't mask text with a moving gradient, so the shimmer is a pulse. const SHIMMER: Duration = Duration::from_millis(1500); #[derive(Clone, Copy, Default, PartialEq)] pub enum AttachmentState { /// Picked but not sent yet: a dashed border. Idle, /// The title shimmers and an image preview is dimmed. Uploading, Processing, /// Destructive border, media and description. Error, #[default] Done, } #[derive(Clone, Copy, Default, PartialEq)] pub enum AttachmentSize { #[default] Default, Sm, Xs, } #[derive(Clone, Copy, Default, PartialEq)] pub enum AttachmentOrientation { /// Media beside the text, at least 160px wide. #[default] Horizontal, /// Media stacked above the text in a 96px (120px with text) tile; actions float on the /// media's top-right corner. Vertical, } enum Media { Icon(&'static [u8]), Element(AnyElement), Image(AnyElement), } type ClickHandler = Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>; /// A file or image attached to a message or a composer: media, a name, metadata such as /// "PDF · 2.4 MB", its upload state and optional actions. #[derive(IntoElement)] pub struct Attachment { id: ElementId, title: Option<SharedString>, description: Option<SharedString>, media: Option<Media>, state: AttachmentState, size: AttachmentSize, orientation: AttachmentOrientation, actions: Vec<AnyElement>, on_click: Option<ClickHandler>, } impl Attachment { pub fn new(id: impl Into<ElementId>) -> Self { Self { id: id.into(), title: None, description: None, media: None, state: AttachmentState::default(), size: AttachmentSize::default(), orientation: AttachmentOrientation::default(), actions: Vec::new(), on_click: None, } } /// The file name. It truncates to one line. pub fn title(mut self, title: impl Into<SharedString>) -> Self { self.title = Some(title.into()); self } /// Secondary metadata such as type and size, or why the upload failed. pub fn description(mut self, description: impl Into<SharedString>) -> Self { self.description = Some(description.into()); self } /// An SVG icon for the media tile, tinted and sized for the attachment's size and state. pub fn icon(mut self, svg: &'static [u8]) -> Self { self.media = Some(Media::Icon(svg)); self } /// Any element in the media tile, such as a `Spinner` while uploading. pub fn media(mut self, media: impl IntoElement) -> Self { self.media = Some(Media::Element(media.into_any_element())); self } /// An image preview, e.g. `img(src).size_full()`. It is dimmed until the upload is done. pub fn image(mut self, image: impl IntoElement) -> Self { self.media = Some(Media::Image(image.into_any_element())); self } pub fn state(mut self, state: AttachmentState) -> Self { self.state = state; self } pub fn size(mut self, size: AttachmentSize) -> Self { self.size = size; self } pub fn orientation(mut self, orientation: AttachmentOrientation) -> Self { self.orientation = orientation; self } /// An action at the end, usually a ghost `Button` of size `Xs` with an icon, such as /// remove. Clicking it doesn't trigger the attachment's own `on_click`. pub fn action(mut self, action: impl IntoElement) -> Self { self.actions.push(action.into_any_element()); self } /// Makes the whole card clickable, e.g. to open a preview. pub fn on_click( mut self, handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, ) -> Self { self.on_click = Some(Box::new(handler)); self } } impl RenderOnce for Attachment { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let state = self.state; let error = state == AttachmentState::Error; let busy = matches!( state, AttachmentState::Uploading | AttachmentState::Processing ); let vertical = self.orientation == AttachmentOrientation::Vertical; let has_content = self.title.is_some() || self.description.is_some(); let has_media = self.media.is_some(); // (gap, media size, icon size, padding with media, padding without media) let (gap, media_size, icon_size, pad_media, (pad_x, pad_y)): ( Pixels, Pixels, Pixels, Pixels, (Pixels, Pixels), ) = match self.size { AttachmentSize::Default => (px(8.0), px(40.0), px(16.0), px(8.0), (px(10.0), px(8.0))), AttachmentSize::Sm => (px(10.0), px(32.0), px(16.0), px(6.0), (px(8.0), px(6.0))), AttachmentSize::Xs => (px(6.0), px(28.0), px(14.0), px(4.0), (px(6.0), px(4.0))), }; let icon_size = if vertical { px(24.0) } else { icon_size }; let xs = self.size == AttachmentSize::Xs; // shadcn's `rounded-2xl` card (`rounded-xl` at xs) around a `rounded-lg` tile // (`rounded-md` at xs). On the default theme's 8px radius these are its 18/10 and // 14/8, and they scale with the theme's radius. let radius = theme.radius; let (card_radius, media_radius) = if xs { (radius * 1.75, radius) } else { (radius * 2.25, radius * 1.25) }; let (media_bg, media_fg) = if error { (theme.destructive.opacity(0.1), theme.destructive) } else { (theme.muted, theme.foreground) }; let media = self.media.map(|media| { let image = matches!(media, Media::Image(_)); div() .flex() .flex_none() .items_center() .justify_center() .overflow_hidden() .rounded(media_radius) .bg(media_bg) .map(|this| { if vertical { this.w_full().aspect_square() } else { this.size(media_size) } }) .when( image && !matches!(state, AttachmentState::Done | AttachmentState::Idle), |this| this.opacity(0.6), ) .child(match media { Media::Icon(data) => svg() .data(data) .flex_none() .size(icon_size) .text_color(media_fg) .into_any_element(), Media::Element(element) | Media::Image(element) => element, }) }); let title = self.title.map(|title| { let title = div() .id("title") .min_w_0() .truncate() .font_weight(FontWeight::MEDIUM) .child(title); if busy { title .with_animation( "shimmer", Animation::new(SHIMMER) .repeat() .with_easing(pulsating_between(0.4, 1.0)), |this, opacity| this.opacity(opacity), ) .into_any_element() } else { title.into_any_element() } }); let description = self.description.map(|description| { div() .mt(px(2.0)) .min_w_0() .truncate() .text_xs() .text_color(if error { theme.destructive.opacity(0.8) } else { theme.muted_foreground }) .child(description) }); let content = has_content.then(|| { div() .flex() .flex_col() .flex_1() .min_w_0() .when(vertical, |this| this.w_full().px_1()) .line_height(gpui::relative(1.25)) .children(title) .children(description) }); let actions = (!self.actions.is_empty()).then(|| { div() .flex() .flex_none() .items_center() .when(vertical, |this| { this.absolute().top(px(12.0)).right(px(12.0)).gap_1() }) // Keeps a click on an action from also counting as a click on the card. .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .children(self.actions) }); let hover_bg = theme.muted.opacity(0.5); div() .id(self.id) .relative() .flex() .min_w_0() .max_w_full() .gap(gap) .map(|this| { if vertical { this.flex_col() .w(if has_content { px(120.0) } else { px(96.0) }) } else { this.items_center().min_w(px(160.0)) } }) .map(|this| { if has_media { this.p(pad_media) } else { this.px(pad_x).py(pad_y) } }) .rounded(card_radius) .border_1() .border_color(if error { theme.destructive.opacity(0.3) } else { theme.border }) .when(state == AttachmentState::Idle, |this| this.border_dashed()) .bg(theme.card) .text_color(theme.card_foreground) .map(|this| { if self.size == AttachmentSize::Default { this.text_sm() } else { this.text_xs() } }) .when_some(self.on_click, |this, handler| { this.cursor_pointer() .hover(move |style| style.bg(hover_bg)) .on_click(move |event, window, cx| handler(event, window, cx)) }) .children(media) .children(content) .children(actions) } } /// A row of attachments that scrolls sideways when it overflows. #[derive(IntoElement)] pub struct AttachmentGroup { id: ElementId, children: Vec<AnyElement>, } impl AttachmentGroup { pub fn new(id: impl Into<ElementId>) -> Self { Self { id: id.into(), children: Vec::new(), } } } impl ParentElement for AttachmentGroup { fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) { self.children.extend(elements); } } impl RenderOnce for AttachmentGroup { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { // No visible scrollbar, like shadcn's `scrollbar-none`: the row is short and a bar // would sit on top of the cards. div() .id(self.id) .w_full() .min_w_0() .overflow_x_scroll() .child( div().flex().items_start().gap_3().py_1().children( self.children .into_iter() .map(|child| div().flex_none().child(child)), ), ) } }Register the module
// src/ui/mod.rs pub mod attachment;
Usage
use crate::ui::attachment::*;API Reference
AttachmentState
AttachmentState::IdlePicked but not sent yet: a dashed border.
AttachmentState::UploadingThe title shimmers and an image preview is dimmed.
AttachmentState::ProcessingAttachmentState::ErrorDestructive border, media and description.
AttachmentState::DoneAttachmentSize
AttachmentSize::DefaultAttachmentSize::SmAttachmentSize::XsAttachmentOrientation
AttachmentOrientation::HorizontalMedia beside the text, at least 160px wide.
AttachmentOrientation::VerticalMedia stacked above the text in a 96px (120px with text) tile; actions float on the media's top-right corner.
Attachment
A file or image attached to a message or a composer: media, a name, metadata such as "PDF · 2.4 MB", its upload state and optional actions.
Attachment::new(id: impl Into<ElementId>) -> Self.title(title: impl Into<SharedString>)The file name. It truncates to one line.
.description(description: impl Into<SharedString>)Secondary metadata such as type and size, or why the upload failed.
.icon(svg: &'static [u8])An SVG icon for the media tile, tinted and sized for the attachment's size and state.
.media(media: impl IntoElement)Any element in the media tile, such as a Spinner while uploading.
.image(image: impl IntoElement)An image preview, e.g. img(src).size_full(). It is dimmed until the upload is done.
.state(state: AttachmentState).size(size: AttachmentSize).orientation(orientation: AttachmentOrientation).action(action: impl IntoElement)An action at the end, usually a ghost Button of size Xs with an icon, such as remove. Clicking it doesn't trigger the attachment's own on_click.
.on_click(handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)Makes the whole card clickable, e.g. to open a preview.
AttachmentGroup
A row of attachments that scrolls sideways when it overflows.
AttachmentGroup::new(id: impl Into<ElementId>) -> Self