Skip to main content

lumen_dioxus/content/
conversation.rs

1//! Conversation and file surfaces: `Bubble`, `Message`, `Attachment`, `AttachmentList`, and
2//! `AttachmentPreview`.
3// cspell:words figcaption
4
5use dioxus::prelude::*;
6
7use super::image::{Image, ImageFit, ImageLoading, ImageRadius};
8use crate::class::{Glass, compose};
9
10/// Who wrote a [`Message`] or [`Bubble`].
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
12#[non_exhaustive]
13pub enum MessageFrom {
14    /// The assistant or the other party.
15    #[default]
16    Assistant,
17    /// The current user.
18    User,
19}
20
21impl MessageFrom {
22    /// The `data-from` value.
23    pub fn as_str(self) -> &'static str {
24        match self {
25            Self::Assistant => "assistant",
26            Self::User => "user",
27        }
28    }
29}
30
31/// Props for [`Bubble`].
32#[derive(Props, Clone, PartialEq)]
33pub struct BubbleProps {
34    /// Author. User bubbles align to the inline end.
35    #[props(default)]
36    pub from: MessageFrom,
37    /// Glass intensity.
38    #[props(default, into)]
39    pub glass: Glass,
40    /// Extra classes appended after the Lumen classes.
41    #[props(into)]
42    pub class: Option<String>,
43    /// Any other `<article>` or global attribute.
44    #[props(extends = GlobalAttributes, extends = article)]
45    pub attributes: Vec<Attribute>,
46    /// Bubble content.
47    pub children: Element,
48}
49
50/// A chat bubble.
51#[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/// Props for [`Message`].
72#[derive(Props, Clone, PartialEq)]
73pub struct MessageProps {
74    /// Author.
75    #[props(default)]
76    pub from: MessageFrom,
77    /// Extra classes appended after the Lumen classes.
78    #[props(into)]
79    pub class: Option<String>,
80    /// Any other `<article>` or global attribute.
81    #[props(extends = GlobalAttributes, extends = article)]
82    pub attributes: Vec<Attribute>,
83    /// Message content, such as an avatar and a [`Bubble`].
84    pub children: Element,
85}
86
87/// One message in a conversation.
88#[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/// Props for [`Attachment`].
108#[derive(Props, Clone, PartialEq)]
109pub struct AttachmentProps {
110    /// Renders the attachment as a link to this URL instead of an `<article>`.
111    #[props(into)]
112    pub href: Option<String>,
113    /// Glass intensity.
114    #[props(default, into)]
115    pub glass: Glass,
116    /// Extra classes appended after the Lumen classes.
117    #[props(into)]
118    pub class: Option<String>,
119    /// Any other global attribute.
120    #[props(extends = GlobalAttributes)]
121    pub attributes: Vec<Attribute>,
122    /// File icon, name, and metadata.
123    pub children: Element,
124}
125
126/// A file chip: an `<article>`, or a link when `href` is set.
127#[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/// Props for [`AttachmentList`].
148#[derive(Props, Clone, PartialEq)]
149pub struct AttachmentListProps {
150    /// Extra classes appended after the Lumen class.
151    #[props(into)]
152    pub class: Option<String>,
153    /// Any other `<ul>` or global attribute.
154    #[props(extends = GlobalAttributes, extends = ul)]
155    pub attributes: Vec<Attribute>,
156    /// `li` elements that hold [`Attachment`]s or [`AttachmentPreview`]s.
157    pub children: Element,
158}
159
160/// A list of attachments.
161#[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/// What an [`AttachmentPreview`] shows.
171#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
172#[non_exhaustive]
173pub enum AttachmentPreviewState {
174    /// The image preview.
175    #[default]
176    Ready,
177    /// The preview is loading.
178    Loading,
179    /// The image failed to load.
180    Error,
181    /// The file has no image preview.
182    Unavailable,
183}
184
185impl AttachmentPreviewState {
186    /// The `data-state` value.
187    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/// Status messages of an [`AttachmentPreview`]. Unset fields keep the English default.
198#[derive(Clone, Debug, Default, PartialEq, Eq)]
199pub struct AttachmentPreviewLabels {
200    /// Shown when the image fails to load. Default: "Could not load the preview."
201    pub error: Option<String>,
202    /// Shown while loading. Default: "Loading preview…"
203    pub loading: Option<String>,
204    /// Shown for files without an image preview. Default: "A preview is not available for this file."
205    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
230/// Resolves the preview state like `resolveLumenAttachmentPreviewState` in `lumen-core`.
231pub(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/// Props for [`AttachmentPreview`].
258#[derive(Props, Clone, PartialEq)]
259pub struct AttachmentPreviewProps {
260    /// Alternative text for the image.
261    #[props(into)]
262    pub alt: String,
263    /// Image URL.
264    #[props(into)]
265    pub src: Option<String>,
266    /// MIME type of the file. Non-image types show the unavailable message.
267    #[props(into)]
268    pub content_type: Option<String>,
269    /// Forces a state, such as `Loading` while the app fetches the file.
270    pub state: Option<AttachmentPreviewState>,
271    /// Status messages.
272    #[props(default)]
273    pub labels: AttachmentPreviewLabels,
274    /// Change it to retry an image that failed to load.
275    #[props(into)]
276    pub retry_key: Option<String>,
277    /// Called when the resolved state changes.
278    pub on_state_change: Option<EventHandler<AttachmentPreviewState>>,
279    /// Caption under the preview.
280    pub caption: Option<Element>,
281    /// Actions such as download or remove.
282    pub actions: Option<Element>,
283    /// Extra classes appended after the Lumen class.
284    #[props(into)]
285    pub class: Option<String>,
286    /// Any other `<figure>` or global attribute.
287    #[props(extends = GlobalAttributes, extends = figure)]
288    pub attributes: Vec<Attribute>,
289    /// Extra content after the caption.
290    pub children: Element,
291}
292
293/// An image preview of an attachment with loading, error, and unavailable states.
294///
295/// A failed image load switches to the error state until `src` or `retry_key` changes.
296#[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}