lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `Terminal` and `InstallCommand`: terminal windows and one-line commands with a copy action.
// cspell:words figcaption

use dioxus::prelude::*;

use super::copy::CopyAction;
use super::util::optional_text;
use crate::class::compose;

/// The prompt shown before command lines. It is decorative and never copied.
pub const TERMINAL_DEFAULT_PROMPT: &str = "$";

/// What a [`TerminalLine`] holds.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum TerminalLineKind {
    /// A command: shows the prompt and is part of the copied text.
    #[default]
    Command,
    /// Program output.
    Output,
    /// A comment.
    Comment,
}

impl TerminalLineKind {
    /// The class suffix and `data-kind` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Command => "command",
            Self::Output => "output",
            Self::Comment => "comment",
        }
    }
}

/// Color of a [`TerminalLine`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum TerminalLineTone {
    /// The kind's default color.
    #[default]
    Default,
    /// Dimmed.
    Muted,
    /// Positive result.
    Success,
    /// Warning.
    Warning,
    /// Error.
    Danger,
    /// Brand color.
    Brand,
}

impl TerminalLineTone {
    /// The class suffix.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Default => "default",
            Self::Muted => "muted",
            Self::Success => "success",
            Self::Warning => "warning",
            Self::Danger => "danger",
            Self::Brand => "brand",
        }
    }
}

/// One line of a [`Terminal`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TerminalLine {
    /// Command, output, or comment.
    pub kind: TerminalLineKind,
    /// The line text.
    pub text: String,
    /// Color.
    pub tone: TerminalLineTone,
}

impl TerminalLine {
    /// A command line.
    pub fn command(text: impl Into<String>) -> Self {
        Self {
            kind: TerminalLineKind::Command,
            text: text.into(),
            tone: TerminalLineTone::Default,
        }
    }

    /// An output line.
    pub fn output(text: impl Into<String>) -> Self {
        Self {
            kind: TerminalLineKind::Output,
            ..Self::command(text)
        }
    }

    /// A comment line.
    pub fn comment(text: impl Into<String>) -> Self {
        Self {
            kind: TerminalLineKind::Comment,
            ..Self::command(text)
        }
    }

    /// Sets the color.
    #[must_use]
    pub fn tone(mut self, tone: TerminalLineTone) -> Self {
        self.tone = tone;
        self
    }

    /// The line's classes, like `getLumenTerminalLineClassName` in `lumen-core`.
    pub fn class_name(&self) -> String {
        let kind = format!("ui-terminal__line--{}", self.kind.as_str());
        let tone = (self.tone != TerminalLineTone::Default)
            .then(|| format!("ui-terminal__line--{}", self.tone.as_str()));

        compose([
            Some("ui-terminal__line"),
            Some(kind.as_str()),
            tone.as_deref(),
        ])
    }
}

/// Joins the command lines without prompts, like `getLumenTerminalCopyValue`, so pasting runs
/// exactly what is shown.
pub fn terminal_copy_value(lines: &[TerminalLine]) -> String {
    lines
        .iter()
        .filter(|line| line.kind == TerminalLineKind::Command)
        .map(|line| line.text.as_str())
        .collect::<Vec<_>>()
        .join("\n")
}

/// Props for [`Terminal`].
#[derive(Props, Clone, PartialEq)]
pub struct TerminalProps {
    /// Lines to render. Leave empty to render `children` instead.
    #[props(default)]
    pub lines: Vec<TerminalLine>,
    /// Window title, rendered as the figure caption.
    #[props(into)]
    pub title: Option<String>,
    /// Accessible name of the scrollable body. Defaults to the title, then "Terminal".
    #[props(into)]
    pub label: Option<String>,
    /// Decorative prompt before command lines. Pass an empty string to hide it.
    #[props(default = TERMINAL_DEFAULT_PROMPT.to_string(), into)]
    pub prompt: String,
    /// Adds a copy action for the command lines.
    #[props(default)]
    pub copy: bool,
    /// Text to copy instead of the joined command lines; required to copy in children mode.
    #[props(into)]
    pub copy_value: Option<String>,
    /// Accessible name of the copy action. Defaults to "Copy commands".
    #[props(into)]
    pub copy_label: Option<String>,
    /// Name and feedback after a copy.
    #[props(into)]
    pub copied_label: Option<String>,
    /// Name and feedback after a failed copy.
    #[props(into)]
    pub error_label: Option<String>,
    /// Copies through the app instead of the browser clipboard. Use it on Dioxus Native.
    pub on_copy: Option<Callback<String, bool>>,
    /// 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>,
    /// Custom body content when `lines` is empty.
    pub children: Element,
}

/// A terminal window with command, output, and comment lines and an optional copy action.
#[component]
pub fn Terminal(props: TerminalProps) -> Element {
    let value = props
        .copy_value
        .clone()
        .unwrap_or_else(|| terminal_copy_value(&props.lines));
    let title = optional_text(props.title.as_deref());
    let body_label = optional_text(props.label.as_deref())
        .or_else(|| title.clone())
        .unwrap_or_else(|| "Terminal".to_string());
    let class = compose([Some("ui-terminal"), props.class.as_deref()]);
    let prompt = props.prompt.clone();

    rsx! {
        figure { class, "data-slot": "terminal", ..props.attributes,
            if let Some(title) = title {
                figcaption { class: "ui-terminal__title", "data-slot": "terminal-title", {title} }
            }
            div { class: "ui-terminal__chrome", "data-slot": "terminal-chrome",
                span { aria_hidden: "true", class: "ui-terminal__dots",
                    span { class: "ui-terminal__dot" }
                    span { class: "ui-terminal__dot" }
                    span { class: "ui-terminal__dot" }
                }
                span { class: "ui-terminal__actions", "data-slot": "terminal-actions",
                    if props.copy && !value.is_empty() {
                        CopyAction {
                            value: value.clone(),
                            label: optional_text(props.copy_label.as_deref())
                                .unwrap_or_else(|| "Copy commands".into()),
                            copied_label: optional_text(props.copied_label.as_deref())
                                .unwrap_or_else(|| "Commands copied to clipboard".into()),
                            error_label: optional_text(props.error_label.as_deref()).unwrap_or_else(|| {
                                "Could not copy commands. Select and copy them manually.".into()
                            }),
                            class: "ui-terminal__copy",
                            variant_class: "ui-button--ghost",
                            on_copy: props.on_copy,
                            "Copy"
                        }
                    }
                }
            }
            pre {
                aria_label: body_label,
                class: "ui-terminal__body",
                "data-slot": "terminal-body",
                role: "region",
                tabindex: "0",
                if props.lines.is_empty() {
                    {props.children}
                } else {
                    for line in props.lines.iter() {
                        span { class: line.class_name(), "data-kind": line.kind.as_str(),
                            if line.kind == TerminalLineKind::Command && !prompt.is_empty() {
                                span { aria_hidden: "true", class: "ui-terminal__prompt", {prompt.clone()} }
                            }
                            {line.text.clone()}
                        }
                    }
                }
            }
        }
    }
}

/// Props for [`InstallCommand`].
#[derive(Props, Clone, PartialEq)]
pub struct InstallCommandProps {
    /// The exact text that is shown and copied.
    #[props(into)]
    pub command: String,
    /// Accessible name of the group and its scrollable command. Defaults to "Install command".
    #[props(into)]
    pub label: Option<String>,
    /// Decorative prompt. Pass an empty string to hide it.
    #[props(default = TERMINAL_DEFAULT_PROMPT.to_string(), into)]
    pub prompt: String,
    /// Accessible name of the copy button. Defaults to "Copy install command", or "Copy {label}".
    #[props(into)]
    pub copy_label: Option<String>,
    /// Name and feedback after a copy.
    #[props(into)]
    pub copied_label: Option<String>,
    /// Name and feedback after a failed copy.
    #[props(into)]
    pub error_label: Option<String>,
    /// Copies through the app instead of the browser clipboard. Use it on Dioxus Native.
    pub on_copy: Option<Callback<String, bool>>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
}

/// A one-line command with a copy button.
#[component]
pub fn InstallCommand(props: InstallCommandProps) -> Element {
    let authored = optional_text(props.label.as_deref());
    let group_label = authored
        .clone()
        .unwrap_or_else(|| "Install command".to_string());
    let copy_label = optional_text(props.copy_label.as_deref()).unwrap_or_else(|| {
        authored.as_ref().map_or_else(
            || "Copy install command".to_string(),
            |label| format!("Copy {label}"),
        )
    });
    let class = compose([Some("ui-install-command"), props.class.as_deref()]);

    rsx! {
        div {
            aria_label: group_label.clone(),
            class,
            "data-slot": "install-command",
            role: "group",
            ..props.attributes,
            span {
                aria_label: group_label,
                class: "ui-install-command__scroll",
                "data-slot": "install-command-scroll",
                role: "region",
                tabindex: "0",
                if !props.prompt.is_empty() {
                    span { aria_hidden: "true", class: "ui-install-command__prompt", {props.prompt.clone()} }
                }
                code { class: "ui-install-command__code", {props.command.clone()} }
            }
            if optional_text(Some(&props.command)).is_some() {
                span { class: "ui-install-command__actions", "data-slot": "install-command-actions",
                    CopyAction {
                        value: props.command.clone(),
                        label: copy_label,
                        copied_label: optional_text(props.copied_label.as_deref())
                            .unwrap_or_else(|| "Command copied to clipboard".into()),
                        error_label: optional_text(props.error_label.as_deref()).unwrap_or_else(|| {
                            "Could not copy the command. Select and copy it manually.".into()
                        }),
                        class: "ui-install-command__copy",
                        variant_class: "ui-button--ghost",
                        on_copy: props.on_copy,
                        "Copy"
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{TerminalLine, TerminalLineTone, terminal_copy_value};

    #[test]
    fn copies_only_command_lines() {
        let lines = vec![
            TerminalLine::command("pnpm install"),
            TerminalLine::output("done").tone(TerminalLineTone::Success),
            TerminalLine::comment("# next"),
            TerminalLine::command("pnpm dev"),
        ];

        assert_eq!(terminal_copy_value(&lines), "pnpm install\npnpm dev");
        assert_eq!(terminal_copy_value(&[]), "");
    }

    #[test]
    fn line_classes_follow_lumen_core() {
        assert_eq!(
            TerminalLine::command("x").class_name(),
            "ui-terminal__line ui-terminal__line--command"
        );
        assert_eq!(
            TerminalLine::output("x")
                .tone(TerminalLineTone::Danger)
                .class_name(),
            "ui-terminal__line ui-terminal__line--output ui-terminal__line--danger"
        );
    }
}