use dioxus::prelude::*;
use super::image::{Image, ImageFit, ImageLoading, ImageRadius};
use crate::class::{Glass, compose};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum MessageFrom {
#[default]
Assistant,
User,
}
impl MessageFrom {
pub fn as_str(self) -> &'static str {
match self {
Self::Assistant => "assistant",
Self::User => "user",
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct BubbleProps {
#[props(default)]
pub from: MessageFrom,
#[props(default, into)]
pub glass: Glass,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = article)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[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}
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct MessageProps {
#[props(default)]
pub from: MessageFrom,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = article)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[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}
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct AttachmentProps {
#[props(into)]
pub href: Option<String>,
#[props(default, into)]
pub glass: Glass,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[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} }
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct AttachmentListProps {
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = ul)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[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} }
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum AttachmentPreviewState {
#[default]
Ready,
Loading,
Error,
Unavailable,
}
impl AttachmentPreviewState {
pub fn as_str(self) -> &'static str {
match self {
Self::Ready => "ready",
Self::Loading => "loading",
Self::Error => "error",
Self::Unavailable => "unavailable",
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AttachmentPreviewLabels {
pub error: Option<String>,
pub loading: Option<String>,
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/")
})
}
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
}
}
#[derive(Props, Clone, PartialEq)]
pub struct AttachmentPreviewProps {
#[props(into)]
pub alt: String,
#[props(into)]
pub src: Option<String>,
#[props(into)]
pub content_type: Option<String>,
pub state: Option<AttachmentPreviewState>,
#[props(default)]
pub labels: AttachmentPreviewLabels,
#[props(into)]
pub retry_key: Option<String>,
pub on_state_change: Option<EventHandler<AttachmentPreviewState>>,
pub caption: Option<Element>,
pub actions: Option<Element>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = figure)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[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), "");
}
}