lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! Copy feedback shared by `Code`, `CodeTabs`, `Terminal`, `InstallCommand`, and `SecretValue`.
//!
//! On the web and desktop the text goes to `navigator.clipboard` through `document::eval`.
//! Dioxus Native has no JavaScript, so the copy reports an error there unless the app passes an
//! `on_copy` callback that writes the clipboard itself (for example with a platform clipboard
//! crate) and returns whether it succeeded.

use std::time::Duration;

use dioxus::prelude::*;

use crate::class::compose;

/// How long the copied or error feedback stays before returning to idle, like lumen-react.
const RESET_AFTER: Duration = Duration::from_millis(2000);

const CLIPBOARD_SCRIPT: &str = "const text = await dioxus.recv();\
try { await navigator.clipboard.writeText(text); return true; } catch (error) { return false; }";

/// The state of a copy action.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum CopyState {
    /// Nothing copied recently.
    #[default]
    Idle,
    /// The last copy succeeded.
    Copied,
    /// The last copy failed.
    Error,
}

impl CopyState {
    /// The `data-state` value.
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Idle => "idle",
            Self::Copied => "copied",
            Self::Error => "error",
        }
    }
}

/// Writes `text` to the browser clipboard. Returns false where JavaScript is unavailable.
pub(crate) async fn write_clipboard(text: String) -> bool {
    let eval = document::eval(CLIPBOARD_SCRIPT);

    if eval.send(text).is_err() {
        return false;
    }

    eval.join::<bool>().await.unwrap_or(false)
}

/// Copy state, the text kept for manual recovery after a failed copy, and the running operation.
#[derive(Clone, Copy)]
pub(crate) struct CopyFeedback {
    state: Signal<CopyState>,
    recovery: Signal<Option<String>>,
    operation: Signal<u64>,
}

/// Keeps the feedback of one copy action. Changing `key` (the copied value) resets it, like the
/// recovery key in lumen-react.
pub(crate) fn use_copy_feedback(key: &str) -> CopyFeedback {
    let feedback = CopyFeedback {
        state: use_signal(CopyState::default),
        recovery: use_signal(|| None),
        operation: use_signal(|| 0),
    };
    let key = key.to_string();

    use_effect(use_reactive((&key,), move |_| feedback.reset()));

    feedback
}

impl CopyFeedback {
    /// The current state.
    pub(crate) fn state(&self) -> CopyState {
        *self.state.read()
    }

    /// The text to show for manual copying after a failure, when recovery is enabled.
    pub(crate) fn recovery(&self) -> Option<String> {
        self.recovery.read().clone()
    }

    /// Drops any pending result and returns to idle.
    pub(crate) fn reset(self) {
        let (mut state, mut recovery, mut operation) = (self.state, self.recovery, self.operation);
        let next = *operation.peek() + 1;

        operation.set(next);

        if *state.peek() != CopyState::Idle {
            state.set(CopyState::Idle);
        }

        if recovery.peek().is_some() {
            recovery.set(None);
        }
    }

    /// Copies `value` with the app's `on_copy` callback, or the browser clipboard without one,
    /// then shows the result for two seconds. `keep_recovery` keeps the value for manual copying
    /// when the copy fails.
    pub(crate) fn copy(
        self,
        value: Option<String>,
        on_copy: Option<Callback<String, bool>>,
        keep_recovery: bool,
    ) {
        let (mut state, mut recovery, mut operation) = (self.state, self.recovery, self.operation);
        let current = *operation.peek() + 1;

        operation.set(current);

        spawn(async move {
            let copied = match (&value, on_copy) {
                (Some(text), Some(callback)) => callback.call(text.clone()),
                (Some(text), None) => write_clipboard(text.clone()).await,
                (None, _) => false,
            };

            if *operation.peek() != current {
                return;
            }

            state.set(if copied {
                CopyState::Copied
            } else {
                CopyState::Error
            });
            recovery.set(if copied || !keep_recovery {
                None
            } else {
                value
            });

            crate::time::sleep(RESET_AFTER).await;

            if *operation.peek() == current {
                state.set(CopyState::Idle);
            }
        });
    }
}

/// Props for [`CopyAction`].
#[derive(Props, Clone, PartialEq)]
pub(crate) struct CopyActionProps {
    /// The copied text.
    pub(crate) value: String,
    /// Accessible name while idle.
    pub(crate) label: String,
    /// Accessible name and feedback after a copy.
    pub(crate) copied_label: String,
    /// Accessible name and feedback after a failure.
    pub(crate) error_label: String,
    /// Extra class after `ui-copy-button`.
    pub(crate) class: &'static str,
    /// `ui-button--ghost` or `ui-button--outline`.
    pub(crate) variant_class: &'static str,
    /// Copies through the app instead of the browser clipboard.
    pub(crate) on_copy: Option<Callback<String, bool>>,
    /// Idle content.
    pub(crate) children: Element,
}

/// A small `CopyButton`-style action, with the markup lumen-react's `CopyButton` renders for
/// `Terminal`, `InstallCommand`, and `SecretValue`.
#[component]
pub(crate) fn CopyAction(props: CopyActionProps) -> Element {
    let feedback = use_copy_feedback(&props.value);
    let state = feedback.state();
    let accessible_label = match state {
        CopyState::Idle => props.label.clone(),
        CopyState::Copied => props.copied_label.clone(),
        CopyState::Error => props.error_label.clone(),
    };
    let class = compose([
        Some("ui-button"),
        Some(props.variant_class),
        Some("ui-button--sm ui-copy-button"),
        Some(props.class),
    ]);
    let (value, on_copy) = (props.value.clone(), props.on_copy);

    rsx! {
        button {
            aria_label: accessible_label,
            class,
            "data-slot": "copy-button",
            "data-state": state.as_str(),
            "data-ui-copy-button": "true",
            "data-ui-owner": "dioxus",
            r#type: "button",
            onclick: move |_| feedback.copy(Some(value.clone()), on_copy, false),
            span { class: "ui-button__content",
                span {
                    aria_hidden: "true",
                    "data-slot": "copy-idle",
                    hidden: state != CopyState::Idle,
                    {props.children}
                }
                span {
                    aria_hidden: "true",
                    "data-slot": "copy-copied",
                    hidden: state != CopyState::Copied,
                    {props.copied_label}
                }
                span {
                    aria_hidden: "true",
                    "data-slot": "copy-error",
                    hidden: state != CopyState::Error,
                    {props.error_label}
                }
            }
        }
    }
}