1use dioxus::prelude::*;
6
7use super::image::{Image, ImageFit, ImageLoading, ImageRadius};
8use crate::class::{Glass, compose};
9
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
12#[non_exhaustive]
13pub enum MessageFrom {
14 #[default]
16 Assistant,
17 User,
19}
20
21impl MessageFrom {
22 pub fn as_str(self) -> &'static str {
24 match self {
25 Self::Assistant => "assistant",
26 Self::User => "user",
27 }
28 }
29}
30
31#[derive(Props, Clone, PartialEq)]
33pub struct BubbleProps {
34 #[props(default)]
36 pub from: MessageFrom,
37 #[props(default, into)]
39 pub glass: Glass,
40 #[props(into)]
42 pub class: Option<String>,
43 #[props(extends = GlobalAttributes, extends = article)]
45 pub attributes: Vec<Attribute>,
46 pub children: Element,
48}
49
50#[component]
52pub fn Bubble(props: BubbleProps) -> Element {
53 let glass = props.glass.class("ui-bubble");
54 let class = compose([
55 Some("ui-bubble"),
56 (props.from == MessageFrom::User).then_some("ui-bubble--user"),
57 glass.as_deref(),
58 props.class.as_deref(),
59 ]);
60
61 rsx! {
62 article {
63 class,
64 "data-from": props.from.as_str(),
65 ..props.attributes,
66 {props.children}
67 }
68 }
69}
70
71#[derive(Props, Clone, PartialEq)]
73pub struct MessageProps {
74 #[props(default)]
76 pub from: MessageFrom,
77 #[props(into)]
79 pub class: Option<String>,
80 #[props(extends = GlobalAttributes, extends = article)]
82 pub attributes: Vec<Attribute>,
83 pub children: Element,
85}
86
87#[component]
89pub fn Message(props: MessageProps) -> Element {
90 let from = format!("ui-message--{}", props.from.as_str());
91 let class = compose([
92 Some("ui-message"),
93 Some(from.as_str()),
94 props.class.as_deref(),
95 ]);
96
97 rsx! {
98 article {
99 class,
100 "data-from": props.from.as_str(),
101 ..props.attributes,
102 {props.children}
103 }
104 }
105}
106
107#[derive(Props, Clone, PartialEq)]
109pub struct AttachmentProps {
110 #[props(into)]
112 pub href: Option<String>,
113 #[props(default, into)]
115 pub glass: Glass,
116 #[props(into)]
118 pub class: Option<String>,
119 #[props(extends = GlobalAttributes)]
121 pub attributes: Vec<Attribute>,
122 pub children: Element,
124}
125
126#[component]
128pub fn Attachment(props: AttachmentProps) -> Element {
129 let glass = props.glass.class("ui-attachment");
130 let class = compose([
131 Some("ui-attachment"),
132 glass.as_deref(),
133 props.class.as_deref(),
134 ]);
135
136 if let Some(href) = props.href {
137 rsx! {
138 a { class, href, ..props.attributes, {props.children} }
139 }
140 } else {
141 rsx! {
142 article { class, ..props.attributes, {props.children} }
143 }
144 }
145}
146
147#[derive(Props, Clone, PartialEq)]
149pub struct AttachmentListProps {
150 #[props(into)]
152 pub class: Option<String>,
153 #[props(extends = GlobalAttributes, extends = ul)]
155 pub attributes: Vec<Attribute>,
156 pub children: Element,
158}
159
160#[component]
162pub fn AttachmentList(props: AttachmentListProps) -> Element {
163 let class = compose([Some("ui-attachment-list"), props.class.as_deref()]);
164
165 rsx! {
166 ul { class, "data-slot": "attachment-list", ..props.attributes, {props.children} }
167 }
168}
169
170#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
172#[non_exhaustive]
173pub enum AttachmentPreviewState {
174 #[default]
176 Ready,
177 Loading,
179 Error,
181 Unavailable,
183}
184
185impl AttachmentPreviewState {
186 pub fn as_str(self) -> &'static str {
188 match self {
189 Self::Ready => "ready",
190 Self::Loading => "loading",
191 Self::Error => "error",
192 Self::Unavailable => "unavailable",
193 }
194 }
195}
196
197#[derive(Clone, Debug, Default, PartialEq, Eq)]
199pub struct AttachmentPreviewLabels {
200 pub error: Option<String>,
202 pub loading: Option<String>,
204 pub unavailable: Option<String>,
206}
207
208impl AttachmentPreviewLabels {
209 fn message(&self, state: AttachmentPreviewState) -> String {
210 let (custom, fallback) = match state {
211 AttachmentPreviewState::Ready => return String::new(),
212 AttachmentPreviewState::Loading => (&self.loading, "Loading preview\u{2026}"),
213 AttachmentPreviewState::Error => (&self.error, "Could not load the preview."),
214 AttachmentPreviewState::Unavailable => (
215 &self.unavailable,
216 "A preview is not available for this file.",
217 ),
218 };
219
220 custom.clone().unwrap_or_else(|| fallback.to_string())
221 }
222}
223
224fn is_image_content_type(content_type: Option<&str>) -> bool {
225 content_type.is_none_or(|value| {
226 value.is_empty() || value.trim().to_ascii_lowercase().starts_with("image/")
227 })
228}
229
230pub(crate) fn resolve_attachment_preview_state(
232 src: Option<&str>,
233 content_type: Option<&str>,
234 requested: Option<AttachmentPreviewState>,
235 failed: bool,
236) -> AttachmentPreviewState {
237 if let Some(
238 state @ (AttachmentPreviewState::Loading
239 | AttachmentPreviewState::Error
240 | AttachmentPreviewState::Unavailable),
241 ) = requested
242 {
243 return state;
244 }
245
246 if src.is_none_or(|value| value.trim().is_empty()) || !is_image_content_type(content_type) {
247 return AttachmentPreviewState::Unavailable;
248 }
249
250 if failed {
251 AttachmentPreviewState::Error
252 } else {
253 AttachmentPreviewState::Ready
254 }
255}
256
257#[derive(Props, Clone, PartialEq)]
259pub struct AttachmentPreviewProps {
260 #[props(into)]
262 pub alt: String,
263 #[props(into)]
265 pub src: Option<String>,
266 #[props(into)]
268 pub content_type: Option<String>,
269 pub state: Option<AttachmentPreviewState>,
271 #[props(default)]
273 pub labels: AttachmentPreviewLabels,
274 #[props(into)]
276 pub retry_key: Option<String>,
277 pub on_state_change: Option<EventHandler<AttachmentPreviewState>>,
279 pub caption: Option<Element>,
281 pub actions: Option<Element>,
283 #[props(into)]
285 pub class: Option<String>,
286 #[props(extends = GlobalAttributes, extends = figure)]
288 pub attributes: Vec<Attribute>,
289 pub children: Element,
291}
292
293#[component]
297pub fn AttachmentPreview(props: AttachmentPreviewProps) -> Element {
298 let mut failure = use_signal(|| None::<(Option<String>, Option<String>)>);
299 let key = (props.src.clone(), props.retry_key.clone());
300 let failed = failure.read().as_ref() == Some(&key);
301 let state = resolve_attachment_preview_state(
302 props.src.as_deref(),
303 props.content_type.as_deref(),
304 props.state,
305 failed,
306 );
307 let mut reported = use_signal(|| state);
308 let on_state_change = props.on_state_change;
309
310 use_effect(use_reactive((&state,), move |(state,)| {
311 if *reported.peek() != state {
312 reported.set(state);
313
314 if let Some(handler) = on_state_change {
315 handler.call(state);
316 }
317 }
318 }));
319
320 let can_preview = resolve_attachment_preview_state(
321 props.src.as_deref(),
322 props.content_type.as_deref(),
323 None,
324 false,
325 ) == AttachmentPreviewState::Ready;
326 let ready = state == AttachmentPreviewState::Ready;
327 let class = compose([Some("ui-attachment-preview"), props.class.as_deref()]);
328 let message = props.labels.message(state);
329 let src = props.src.clone().unwrap_or_default();
330
331 rsx! {
332 figure {
333 class,
334 aria_busy: if state == AttachmentPreviewState::Loading { "true" } else { "false" },
335 "data-state": state.as_str(),
336 ..props.attributes,
337 div { "data-slot": "attachment-preview-media", hidden: !ready,
338 if can_preview {
339 Image {
340 key: "{src}:{props.retry_key.clone().unwrap_or_default()}",
341 src: src.clone(),
342 alt: props.alt.clone(),
343 fit: ImageFit::Contain,
344 radius: ImageRadius::None,
345 loading: ImageLoading::Eager,
346 onerror: move |_| failure.set(Some(key.clone())),
347 }
348 }
349 }
350 p {
351 role: "status",
352 "data-slot": "attachment-preview-fallback",
353 hidden: ready,
354 {message}
355 }
356 if let Some(caption) = props.caption {
357 figcaption { {caption} }
358 }
359 {props.children}
360 if let Some(actions) = props.actions {
361 div { "data-slot": "attachment-preview-actions", {actions} }
362 }
363 }
364 }
365}
366
367#[cfg(test)]
368mod tests {
369 use super::{
370 AttachmentPreviewLabels, AttachmentPreviewState, resolve_attachment_preview_state,
371 };
372
373 #[test]
374 fn preview_state_follows_lumen_core() {
375 use AttachmentPreviewState::{Error, Loading, Ready, Unavailable};
376
377 assert_eq!(
378 resolve_attachment_preview_state(Some("/a.png"), None, None, false),
379 Ready
380 );
381 assert_eq!(
382 resolve_attachment_preview_state(Some("/a.png"), None, None, true),
383 Error
384 );
385 assert_eq!(
386 resolve_attachment_preview_state(Some(" "), None, None, false),
387 Unavailable
388 );
389 assert_eq!(
390 resolve_attachment_preview_state(None, None, None, false),
391 Unavailable
392 );
393 assert_eq!(
394 resolve_attachment_preview_state(Some("/a.pdf"), Some("application/pdf"), None, false),
395 Unavailable
396 );
397 assert_eq!(
398 resolve_attachment_preview_state(Some("/a"), Some(" IMAGE/PNG "), None, false),
399 Ready
400 );
401 assert_eq!(
402 resolve_attachment_preview_state(Some("/a"), Some(""), None, false),
403 Ready
404 );
405 assert_eq!(
406 resolve_attachment_preview_state(None, None, Some(Loading), false),
407 Loading
408 );
409 assert_eq!(
410 resolve_attachment_preview_state(Some("/a.png"), None, Some(Ready), true),
411 Error
412 );
413 }
414
415 #[test]
416 fn labels_fall_back_to_english() {
417 let labels = AttachmentPreviewLabels {
418 loading: Some("Fetching".into()),
419 ..AttachmentPreviewLabels::default()
420 };
421
422 assert_eq!(labels.message(AttachmentPreviewState::Loading), "Fetching");
423 assert_eq!(
424 labels.message(AttachmentPreviewState::Error),
425 "Could not load the preview."
426 );
427 assert_eq!(labels.message(AttachmentPreviewState::Ready), "");
428 }
429}