lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! Conversation and file surfaces: `Bubble`, `Message`, `Attachment`, `AttachmentList`, and
//! `AttachmentPreview`.
// cspell:words figcaption

use dioxus::prelude::*;

use super::image::{Image, ImageFit, ImageLoading, ImageRadius};
use crate::class::{Glass, compose};

/// Who wrote a [`Message`] or [`Bubble`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum MessageFrom {
    /// The assistant or the other party.
    #[default]
    Assistant,
    /// The current user.
    User,
}

impl MessageFrom {
    /// The `data-from` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Assistant => "assistant",
            Self::User => "user",
        }
    }
}

/// Props for [`Bubble`].
#[derive(Props, Clone, PartialEq)]
pub struct BubbleProps {
    /// Author. User bubbles align to the inline end.
    #[props(default)]
    pub from: MessageFrom,
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<article>` or global attribute.
    #[props(extends = GlobalAttributes, extends = article)]
    pub attributes: Vec<Attribute>,
    /// Bubble content.
    pub children: Element,
}

/// A chat bubble.
#[component]
pub fn Bubble(props: BubbleProps) -> Element {
    let glass = props.glass.class("ui-bubble");
    let class = compose([
        Some("ui-bubble"),
        (props.from == MessageFrom::User).then_some("ui-bubble--user"),
        glass.as_deref(),
        props.class.as_deref(),
    ]);

    rsx! {
        article {
            class,
            "data-from": props.from.as_str(),
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`Message`].
#[derive(Props, Clone, PartialEq)]
pub struct MessageProps {
    /// Author.
    #[props(default)]
    pub from: MessageFrom,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<article>` or global attribute.
    #[props(extends = GlobalAttributes, extends = article)]
    pub attributes: Vec<Attribute>,
    /// Message content, such as an avatar and a [`Bubble`].
    pub children: Element,
}

/// One message in a conversation.
#[component]
pub fn Message(props: MessageProps) -> Element {
    let from = format!("ui-message--{}", props.from.as_str());
    let class = compose([
        Some("ui-message"),
        Some(from.as_str()),
        props.class.as_deref(),
    ]);

    rsx! {
        article {
            class,
            "data-from": props.from.as_str(),
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`Attachment`].
#[derive(Props, Clone, PartialEq)]
pub struct AttachmentProps {
    /// Renders the attachment as a link to this URL instead of an `<article>`.
    #[props(into)]
    pub href: Option<String>,
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other global attribute.
    #[props(extends = GlobalAttributes)]
    pub attributes: Vec<Attribute>,
    /// File icon, name, and metadata.
    pub children: Element,
}

/// A file chip: an `<article>`, or a link when `href` is set.
#[component]
pub fn Attachment(props: AttachmentProps) -> Element {
    let glass = props.glass.class("ui-attachment");
    let class = compose([
        Some("ui-attachment"),
        glass.as_deref(),
        props.class.as_deref(),
    ]);

    if let Some(href) = props.href {
        rsx! {
            a { class, href, ..props.attributes, {props.children} }
        }
    } else {
        rsx! {
            article { class, ..props.attributes, {props.children} }
        }
    }
}

/// Props for [`AttachmentList`].
#[derive(Props, Clone, PartialEq)]
pub struct AttachmentListProps {
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<ul>` or global attribute.
    #[props(extends = GlobalAttributes, extends = ul)]
    pub attributes: Vec<Attribute>,
    /// `li` elements that hold [`Attachment`]s or [`AttachmentPreview`]s.
    pub children: Element,
}

/// A list of attachments.
#[component]
pub fn AttachmentList(props: AttachmentListProps) -> Element {
    let class = compose([Some("ui-attachment-list"), props.class.as_deref()]);

    rsx! {
        ul { class, "data-slot": "attachment-list", ..props.attributes, {props.children} }
    }
}

/// What an [`AttachmentPreview`] shows.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum AttachmentPreviewState {
    /// The image preview.
    #[default]
    Ready,
    /// The preview is loading.
    Loading,
    /// The image failed to load.
    Error,
    /// The file has no image preview.
    Unavailable,
}

impl AttachmentPreviewState {
    /// The `data-state` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Ready => "ready",
            Self::Loading => "loading",
            Self::Error => "error",
            Self::Unavailable => "unavailable",
        }
    }
}

/// Status messages of an [`AttachmentPreview`]. Unset fields keep the English default.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AttachmentPreviewLabels {
    /// Shown when the image fails to load. Default: "Could not load the preview."
    pub error: Option<String>,
    /// Shown while loading. Default: "Loading preview…"
    pub loading: Option<String>,
    /// Shown for files without an image preview. Default: "A preview is not available for this file."
    pub unavailable: Option<String>,
}

impl AttachmentPreviewLabels {
    fn message(&self, state: AttachmentPreviewState) -> String {
        let (custom, fallback) = match state {
            AttachmentPreviewState::Ready => return String::new(),
            AttachmentPreviewState::Loading => (&self.loading, "Loading preview\u{2026}"),
            AttachmentPreviewState::Error => (&self.error, "Could not load the preview."),
            AttachmentPreviewState::Unavailable => (
                &self.unavailable,
                "A preview is not available for this file.",
            ),
        };

        custom.clone().unwrap_or_else(|| fallback.to_string())
    }
}

fn is_image_content_type(content_type: Option<&str>) -> bool {
    content_type.is_none_or(|value| {
        value.is_empty() || value.trim().to_ascii_lowercase().starts_with("image/")
    })
}

/// Resolves the preview state like `resolveLumenAttachmentPreviewState` in `lumen-core`.
pub(crate) fn resolve_attachment_preview_state(
    src: Option<&str>,
    content_type: Option<&str>,
    requested: Option<AttachmentPreviewState>,
    failed: bool,
) -> AttachmentPreviewState {
    if let Some(
        state @ (AttachmentPreviewState::Loading
        | AttachmentPreviewState::Error
        | AttachmentPreviewState::Unavailable),
    ) = requested
    {
        return state;
    }

    if src.is_none_or(|value| value.trim().is_empty()) || !is_image_content_type(content_type) {
        return AttachmentPreviewState::Unavailable;
    }

    if failed {
        AttachmentPreviewState::Error
    } else {
        AttachmentPreviewState::Ready
    }
}

/// Props for [`AttachmentPreview`].
#[derive(Props, Clone, PartialEq)]
pub struct AttachmentPreviewProps {
    /// Alternative text for the image.
    #[props(into)]
    pub alt: String,
    /// Image URL.
    #[props(into)]
    pub src: Option<String>,
    /// MIME type of the file. Non-image types show the unavailable message.
    #[props(into)]
    pub content_type: Option<String>,
    /// Forces a state, such as `Loading` while the app fetches the file.
    pub state: Option<AttachmentPreviewState>,
    /// Status messages.
    #[props(default)]
    pub labels: AttachmentPreviewLabels,
    /// Change it to retry an image that failed to load.
    #[props(into)]
    pub retry_key: Option<String>,
    /// Called when the resolved state changes.
    pub on_state_change: Option<EventHandler<AttachmentPreviewState>>,
    /// Caption under the preview.
    pub caption: Option<Element>,
    /// Actions such as download or remove.
    pub actions: Option<Element>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<figure>` or global attribute.
    #[props(extends = GlobalAttributes, extends = figure)]
    pub attributes: Vec<Attribute>,
    /// Extra content after the caption.
    pub children: Element,
}

/// An image preview of an attachment with loading, error, and unavailable states.
///
/// A failed image load switches to the error state until `src` or `retry_key` changes.
#[component]
pub fn AttachmentPreview(props: AttachmentPreviewProps) -> Element {
    let mut failure = use_signal(|| None::<(Option<String>, Option<String>)>);
    let key = (props.src.clone(), props.retry_key.clone());
    let failed = failure.read().as_ref() == Some(&key);
    let state = resolve_attachment_preview_state(
        props.src.as_deref(),
        props.content_type.as_deref(),
        props.state,
        failed,
    );
    let mut reported = use_signal(|| state);
    let on_state_change = props.on_state_change;

    use_effect(use_reactive((&state,), move |(state,)| {
        if *reported.peek() != state {
            reported.set(state);

            if let Some(handler) = on_state_change {
                handler.call(state);
            }
        }
    }));

    let can_preview = resolve_attachment_preview_state(
        props.src.as_deref(),
        props.content_type.as_deref(),
        None,
        false,
    ) == AttachmentPreviewState::Ready;
    let ready = state == AttachmentPreviewState::Ready;
    let class = compose([Some("ui-attachment-preview"), props.class.as_deref()]);
    let message = props.labels.message(state);
    let src = props.src.clone().unwrap_or_default();

    rsx! {
        figure {
            class,
            aria_busy: if state == AttachmentPreviewState::Loading { "true" } else { "false" },
            "data-state": state.as_str(),
            ..props.attributes,
            div { "data-slot": "attachment-preview-media", hidden: !ready,
                if can_preview {
                    Image {
                        key: "{src}:{props.retry_key.clone().unwrap_or_default()}",
                        src: src.clone(),
                        alt: props.alt.clone(),
                        fit: ImageFit::Contain,
                        radius: ImageRadius::None,
                        loading: ImageLoading::Eager,
                        onerror: move |_| failure.set(Some(key.clone())),
                    }
                }
            }
            p {
                role: "status",
                "data-slot": "attachment-preview-fallback",
                hidden: ready,
                {message}
            }
            if let Some(caption) = props.caption {
                figcaption { {caption} }
            }
            {props.children}
            if let Some(actions) = props.actions {
                div { "data-slot": "attachment-preview-actions", {actions} }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        AttachmentPreviewLabels, AttachmentPreviewState, resolve_attachment_preview_state,
    };

    #[test]
    fn preview_state_follows_lumen_core() {
        use AttachmentPreviewState::{Error, Loading, Ready, Unavailable};

        assert_eq!(
            resolve_attachment_preview_state(Some("/a.png"), None, None, false),
            Ready
        );
        assert_eq!(
            resolve_attachment_preview_state(Some("/a.png"), None, None, true),
            Error
        );
        assert_eq!(
            resolve_attachment_preview_state(Some("  "), None, None, false),
            Unavailable
        );
        assert_eq!(
            resolve_attachment_preview_state(None, None, None, false),
            Unavailable
        );
        assert_eq!(
            resolve_attachment_preview_state(Some("/a.pdf"), Some("application/pdf"), None, false),
            Unavailable
        );
        assert_eq!(
            resolve_attachment_preview_state(Some("/a"), Some(" IMAGE/PNG "), None, false),
            Ready
        );
        assert_eq!(
            resolve_attachment_preview_state(Some("/a"), Some(""), None, false),
            Ready
        );
        assert_eq!(
            resolve_attachment_preview_state(None, None, Some(Loading), false),
            Loading
        );
        assert_eq!(
            resolve_attachment_preview_state(Some("/a.png"), None, Some(Ready), true),
            Error
        );
    }

    #[test]
    fn labels_fall_back_to_english() {
        let labels = AttachmentPreviewLabels {
            loading: Some("Fetching".into()),
            ..AttachmentPreviewLabels::default()
        };

        assert_eq!(labels.message(AttachmentPreviewState::Loading), "Fetching");
        assert_eq!(
            labels.message(AttachmentPreviewState::Error),
            "Could not load the preview."
        );
        assert_eq!(labels.message(AttachmentPreviewState::Ready), "");
    }
}