Skip to main content

lumen_dioxus/content/
terminal.rs

1//! `Terminal` and `InstallCommand`: terminal windows and one-line commands with a copy action.
2// cspell:words figcaption
3
4use dioxus::prelude::*;
5
6use super::copy::CopyAction;
7use super::util::optional_text;
8use crate::class::compose;
9
10/// The prompt shown before command lines. It is decorative and never copied.
11pub const TERMINAL_DEFAULT_PROMPT: &str = "$";
12
13/// What a [`TerminalLine`] holds.
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15#[non_exhaustive]
16pub enum TerminalLineKind {
17    /// A command: shows the prompt and is part of the copied text.
18    #[default]
19    Command,
20    /// Program output.
21    Output,
22    /// A comment.
23    Comment,
24}
25
26impl TerminalLineKind {
27    /// The class suffix and `data-kind` value.
28    pub fn as_str(self) -> &'static str {
29        match self {
30            Self::Command => "command",
31            Self::Output => "output",
32            Self::Comment => "comment",
33        }
34    }
35}
36
37/// Color of a [`TerminalLine`].
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
39#[non_exhaustive]
40pub enum TerminalLineTone {
41    /// The kind's default color.
42    #[default]
43    Default,
44    /// Dimmed.
45    Muted,
46    /// Positive result.
47    Success,
48    /// Warning.
49    Warning,
50    /// Error.
51    Danger,
52    /// Brand color.
53    Brand,
54}
55
56impl TerminalLineTone {
57    /// The class suffix.
58    pub fn as_str(self) -> &'static str {
59        match self {
60            Self::Default => "default",
61            Self::Muted => "muted",
62            Self::Success => "success",
63            Self::Warning => "warning",
64            Self::Danger => "danger",
65            Self::Brand => "brand",
66        }
67    }
68}
69
70/// One line of a [`Terminal`].
71#[derive(Clone, Debug, Default, PartialEq, Eq)]
72pub struct TerminalLine {
73    /// Command, output, or comment.
74    pub kind: TerminalLineKind,
75    /// The line text.
76    pub text: String,
77    /// Color.
78    pub tone: TerminalLineTone,
79}
80
81impl TerminalLine {
82    /// A command line.
83    pub fn command(text: impl Into<String>) -> Self {
84        Self {
85            kind: TerminalLineKind::Command,
86            text: text.into(),
87            tone: TerminalLineTone::Default,
88        }
89    }
90
91    /// An output line.
92    pub fn output(text: impl Into<String>) -> Self {
93        Self {
94            kind: TerminalLineKind::Output,
95            ..Self::command(text)
96        }
97    }
98
99    /// A comment line.
100    pub fn comment(text: impl Into<String>) -> Self {
101        Self {
102            kind: TerminalLineKind::Comment,
103            ..Self::command(text)
104        }
105    }
106
107    /// Sets the color.
108    #[must_use]
109    pub fn tone(mut self, tone: TerminalLineTone) -> Self {
110        self.tone = tone;
111        self
112    }
113
114    /// The line's classes, like `getLumenTerminalLineClassName` in `lumen-core`.
115    pub fn class_name(&self) -> String {
116        let kind = format!("ui-terminal__line--{}", self.kind.as_str());
117        let tone = (self.tone != TerminalLineTone::Default)
118            .then(|| format!("ui-terminal__line--{}", self.tone.as_str()));
119
120        compose([
121            Some("ui-terminal__line"),
122            Some(kind.as_str()),
123            tone.as_deref(),
124        ])
125    }
126}
127
128/// Joins the command lines without prompts, like `getLumenTerminalCopyValue`, so pasting runs
129/// exactly what is shown.
130pub fn terminal_copy_value(lines: &[TerminalLine]) -> String {
131    lines
132        .iter()
133        .filter(|line| line.kind == TerminalLineKind::Command)
134        .map(|line| line.text.as_str())
135        .collect::<Vec<_>>()
136        .join("\n")
137}
138
139/// Props for [`Terminal`].
140#[derive(Props, Clone, PartialEq)]
141pub struct TerminalProps {
142    /// Lines to render. Leave empty to render `children` instead.
143    #[props(default)]
144    pub lines: Vec<TerminalLine>,
145    /// Window title, rendered as the figure caption.
146    #[props(into)]
147    pub title: Option<String>,
148    /// Accessible name of the scrollable body. Defaults to the title, then "Terminal".
149    #[props(into)]
150    pub label: Option<String>,
151    /// Decorative prompt before command lines. Pass an empty string to hide it.
152    #[props(default = TERMINAL_DEFAULT_PROMPT.to_string(), into)]
153    pub prompt: String,
154    /// Adds a copy action for the command lines.
155    #[props(default)]
156    pub copy: bool,
157    /// Text to copy instead of the joined command lines; required to copy in children mode.
158    #[props(into)]
159    pub copy_value: Option<String>,
160    /// Accessible name of the copy action. Defaults to "Copy commands".
161    #[props(into)]
162    pub copy_label: Option<String>,
163    /// Name and feedback after a copy.
164    #[props(into)]
165    pub copied_label: Option<String>,
166    /// Name and feedback after a failed copy.
167    #[props(into)]
168    pub error_label: Option<String>,
169    /// Copies through the app instead of the browser clipboard. Use it on Dioxus Native.
170    pub on_copy: Option<Callback<String, bool>>,
171    /// Extra classes appended after the Lumen class.
172    #[props(into)]
173    pub class: Option<String>,
174    /// Any other `<figure>` or global attribute.
175    #[props(extends = GlobalAttributes, extends = figure)]
176    pub attributes: Vec<Attribute>,
177    /// Custom body content when `lines` is empty.
178    pub children: Element,
179}
180
181/// A terminal window with command, output, and comment lines and an optional copy action.
182#[component]
183pub fn Terminal(props: TerminalProps) -> Element {
184    let value = props
185        .copy_value
186        .clone()
187        .unwrap_or_else(|| terminal_copy_value(&props.lines));
188    let title = optional_text(props.title.as_deref());
189    let body_label = optional_text(props.label.as_deref())
190        .or_else(|| title.clone())
191        .unwrap_or_else(|| "Terminal".to_string());
192    let class = compose([Some("ui-terminal"), props.class.as_deref()]);
193    let prompt = props.prompt.clone();
194
195    rsx! {
196        figure { class, "data-slot": "terminal", ..props.attributes,
197            if let Some(title) = title {
198                figcaption { class: "ui-terminal__title", "data-slot": "terminal-title", {title} }
199            }
200            div { class: "ui-terminal__chrome", "data-slot": "terminal-chrome",
201                span { aria_hidden: "true", class: "ui-terminal__dots",
202                    span { class: "ui-terminal__dot" }
203                    span { class: "ui-terminal__dot" }
204                    span { class: "ui-terminal__dot" }
205                }
206                span { class: "ui-terminal__actions", "data-slot": "terminal-actions",
207                    if props.copy && !value.is_empty() {
208                        CopyAction {
209                            value: value.clone(),
210                            label: optional_text(props.copy_label.as_deref())
211                                .unwrap_or_else(|| "Copy commands".into()),
212                            copied_label: optional_text(props.copied_label.as_deref())
213                                .unwrap_or_else(|| "Commands copied to clipboard".into()),
214                            error_label: optional_text(props.error_label.as_deref()).unwrap_or_else(|| {
215                                "Could not copy commands. Select and copy them manually.".into()
216                            }),
217                            class: "ui-terminal__copy",
218                            variant_class: "ui-button--ghost",
219                            on_copy: props.on_copy,
220                            "Copy"
221                        }
222                    }
223                }
224            }
225            pre {
226                aria_label: body_label,
227                class: "ui-terminal__body",
228                "data-slot": "terminal-body",
229                role: "region",
230                tabindex: "0",
231                if props.lines.is_empty() {
232                    {props.children}
233                } else {
234                    for line in props.lines.iter() {
235                        span { class: line.class_name(), "data-kind": line.kind.as_str(),
236                            if line.kind == TerminalLineKind::Command && !prompt.is_empty() {
237                                span { aria_hidden: "true", class: "ui-terminal__prompt", {prompt.clone()} }
238                            }
239                            {line.text.clone()}
240                        }
241                    }
242                }
243            }
244        }
245    }
246}
247
248/// Props for [`InstallCommand`].
249#[derive(Props, Clone, PartialEq)]
250pub struct InstallCommandProps {
251    /// The exact text that is shown and copied.
252    #[props(into)]
253    pub command: String,
254    /// Accessible name of the group and its scrollable command. Defaults to "Install command".
255    #[props(into)]
256    pub label: Option<String>,
257    /// Decorative prompt. Pass an empty string to hide it.
258    #[props(default = TERMINAL_DEFAULT_PROMPT.to_string(), into)]
259    pub prompt: String,
260    /// Accessible name of the copy button. Defaults to "Copy install command", or "Copy {label}".
261    #[props(into)]
262    pub copy_label: Option<String>,
263    /// Name and feedback after a copy.
264    #[props(into)]
265    pub copied_label: Option<String>,
266    /// Name and feedback after a failed copy.
267    #[props(into)]
268    pub error_label: Option<String>,
269    /// Copies through the app instead of the browser clipboard. Use it on Dioxus Native.
270    pub on_copy: Option<Callback<String, bool>>,
271    /// Extra classes appended after the Lumen class.
272    #[props(into)]
273    pub class: Option<String>,
274    /// Any other `<div>` or global attribute.
275    #[props(extends = GlobalAttributes, extends = div)]
276    pub attributes: Vec<Attribute>,
277}
278
279/// A one-line command with a copy button.
280#[component]
281pub fn InstallCommand(props: InstallCommandProps) -> Element {
282    let authored = optional_text(props.label.as_deref());
283    let group_label = authored
284        .clone()
285        .unwrap_or_else(|| "Install command".to_string());
286    let copy_label = optional_text(props.copy_label.as_deref()).unwrap_or_else(|| {
287        authored.as_ref().map_or_else(
288            || "Copy install command".to_string(),
289            |label| format!("Copy {label}"),
290        )
291    });
292    let class = compose([Some("ui-install-command"), props.class.as_deref()]);
293
294    rsx! {
295        div {
296            aria_label: group_label.clone(),
297            class,
298            "data-slot": "install-command",
299            role: "group",
300            ..props.attributes,
301            span {
302                aria_label: group_label,
303                class: "ui-install-command__scroll",
304                "data-slot": "install-command-scroll",
305                role: "region",
306                tabindex: "0",
307                if !props.prompt.is_empty() {
308                    span { aria_hidden: "true", class: "ui-install-command__prompt", {props.prompt.clone()} }
309                }
310                code { class: "ui-install-command__code", {props.command.clone()} }
311            }
312            if optional_text(Some(&props.command)).is_some() {
313                span { class: "ui-install-command__actions", "data-slot": "install-command-actions",
314                    CopyAction {
315                        value: props.command.clone(),
316                        label: copy_label,
317                        copied_label: optional_text(props.copied_label.as_deref())
318                            .unwrap_or_else(|| "Command copied to clipboard".into()),
319                        error_label: optional_text(props.error_label.as_deref()).unwrap_or_else(|| {
320                            "Could not copy the command. Select and copy it manually.".into()
321                        }),
322                        class: "ui-install-command__copy",
323                        variant_class: "ui-button--ghost",
324                        on_copy: props.on_copy,
325                        "Copy"
326                    }
327                }
328            }
329        }
330    }
331}
332
333#[cfg(test)]
334mod tests {
335    use super::{TerminalLine, TerminalLineTone, terminal_copy_value};
336
337    #[test]
338    fn copies_only_command_lines() {
339        let lines = vec![
340            TerminalLine::command("pnpm install"),
341            TerminalLine::output("done").tone(TerminalLineTone::Success),
342            TerminalLine::comment("# next"),
343            TerminalLine::command("pnpm dev"),
344        ];
345
346        assert_eq!(terminal_copy_value(&lines), "pnpm install\npnpm dev");
347        assert_eq!(terminal_copy_value(&[]), "");
348    }
349
350    #[test]
351    fn line_classes_follow_lumen_core() {
352        assert_eq!(
353            TerminalLine::command("x").class_name(),
354            "ui-terminal__line ui-terminal__line--command"
355        );
356        assert_eq!(
357            TerminalLine::output("x")
358                .tone(TerminalLineTone::Danger)
359                .class_name(),
360            "ui-terminal__line ui-terminal__line--output ui-terminal__line--danger"
361        );
362    }
363}