lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! Renderer helpers shared by the numeric inputs: a JavaScript capability probe and a value
//! mirror that rewrites a text control after Rust normalizes what the user typed.

use std::cell::Cell;
use std::fmt::Write as _;

use dioxus::core::AttributeValue;
use dioxus::document::{self, EvalError};
use dioxus::prelude::*;

thread_local! {
    /// The probe result, shared by every component rendered on this thread.
    static SCRIPTING: Cell<Option<bool>> = const { Cell::new(None) };
}

/// Whether the renderer runs JavaScript: `Some(true)` on web and desktop webviews,
/// `Some(false)` on Dioxus Native (Blitz), and `None` until the first probe finishes and during
/// server rendering, where components render their lumen-react markup.
///
/// The probe evaluates `return true;` once per mounted caller until a result is cached. Dioxus
/// Native delegates to `NoOpDocument`: its fresh evaluator reports `Unsupported`, or `Finished`
/// in Dioxus 0.7.10 because that document drops the evaluator's owner before it can be polled.
/// Other failures leave the capability unknown instead of selecting Native behavior on web.
pub(crate) fn use_scripting() -> Option<bool> {
    let mut state = use_signal(|| SCRIPTING.with(Cell::get));

    use_hook(move || {
        if state.peek().is_none() {
            spawn(async move {
                let result = document::eval("return true;").join::<bool>().await;
                if let Some(available) = scripting_capability(&result) {
                    SCRIPTING.with(|cell| cell.set(Some(available)));
                    state.set(Some(available));
                }
            });
        }
    });

    state()
}

/// Classifies only a fresh, one-shot evaluation. `Finished` cannot mean a consumed result here:
/// the probe never clones or reuses the eval, and a mounted web renderer retains its owner.
fn scripting_capability(result: &Result<bool, EvalError>) -> Option<bool> {
    match result {
        Ok(true) => Some(true),
        Err(EvalError::Unsupported | EvalError::Finished) => Some(false),
        _ => None,
    }
}

/// Sets the probe result for the current thread, so tests can render the Dioxus Native markup.
#[cfg(test)]
pub(crate) fn set_scripting_for_tests(value: Option<bool>) {
    SCRIPTING.with(|cell| cell.set(value));
}

/// Mirrors the `value` attribute of a text control whose content Rust rewrites.
///
/// Dioxus only writes an attribute when it differs from the previous render, so a correction back
/// to the previously rendered value (a rejected character) would never reach the control. After
/// each user edit the mirror first renders the raw text the control already shows, then renders
/// the corrected value on the next pass, which always produces a write.
#[derive(Clone, Copy)]
pub(crate) struct ValueMirror {
    pending: Signal<Option<String>>,
}

pub(crate) fn use_value_mirror() -> ValueMirror {
    ValueMirror {
        pending: use_signal(|| None),
    }
}

impl ValueMirror {
    /// The `value` attribute to render this pass, given the corrected value.
    pub(crate) fn attribute(&self, corrected: &str) -> String {
        self.pending
            .read()
            .clone()
            .unwrap_or_else(|| corrected.to_string())
    }

    /// Records the text the control shows after a user edit and schedules the correction.
    /// `after` runs once the corrected value has been rendered (for caret placement).
    pub(crate) fn record(&self, raw: String, after: impl FnOnce() + 'static) {
        let mut pending = self.pending;

        pending.set(Some(raw));
        spawn(async move {
            pending.set(None);
            spawn(async move { after() });
        });
    }
}

/// A script that places the caret of the focused control, when it matches `selector`, after
/// `chars` characters of `value`. A web and desktop enhancement: Dioxus Native runs no JavaScript.
pub(crate) fn caret_script(selector: &'static str, value: &str, chars: usize) -> String {
    let position: usize = value.chars().take(chars).map(char::len_utf16).sum();

    format!(
        "const el = document.activeElement; if (el && el.matches('{selector}') && el.setSelectionRange) {{ el.setSelectionRange({position}, {position}); }}"
    )
}

/// A script that sets the custom validity message of the focused control when it matches
/// `selector`.
pub(crate) fn validity_script(selector: &'static str, message: &str) -> String {
    let message = json_string(message);

    format!(
        "const el = document.activeElement; if (el && el.matches('{selector}') && el.setCustomValidity) {{ el.setCustomValidity({message}); }}"
    )
}

/// Runs scripts in order without waiting in the caller; errors (Dioxus Native) are ignored.
pub(crate) fn run_scripts(scripts: Vec<String>) {
    if scripts.is_empty() {
        return;
    }

    spawn(async move {
        for script in scripts {
            let _ = document::eval(&script).await;
        }
    });
}

/// A JavaScript string literal for arbitrary text, escaped with a single linear scan.
pub(crate) fn json_string(value: &str) -> String {
    let mut out = String::with_capacity(value.len() + 2);

    out.push('"');

    for character in value.chars() {
        match character {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '<' => out.push_str("\\u003c"),
            '>' => out.push_str("\\u003e"),
            '\u{2028}' => out.push_str("\\u2028"),
            '\u{2029}' => out.push_str("\\u2029"),
            control if u32::from(control) < 0x20 => {
                let _ = write!(out, "\\u{:04x}", u32::from(control));
            }
            other => out.push(other),
        }
    }

    out.push('"');
    out
}

/// Whether an attribute list sets a boolean attribute such as `readonly` or `disabled`.
pub(crate) fn has_flag(attributes: &[Attribute], name: &str) -> bool {
    attributes.iter().any(|attribute| {
        attribute.name == name
            && match &attribute.value {
                AttributeValue::Bool(value) => *value,
                AttributeValue::Text(value) => value != "false",
                AttributeValue::None => false,
                _ => true,
            }
    })
}

#[cfg(test)]
mod tests {
    use std::rc::Rc;
    use std::time::Duration;

    use dioxus::document::{Document, EvalError, NoOpDocument};
    use dioxus::prelude::*;

    use super::{json_string, scripting_capability, set_scripting_for_tests, use_scripting};

    fn probe() -> Element {
        let capability = use_scripting();
        rsx! { span { "{capability:?}" } }
    }

    fn native_document() -> VirtualDom {
        let dom = VirtualDom::new(probe);
        dom.provide_root_context(Rc::new(NoOpDocument) as Rc<dyn Document>);
        dom
    }

    #[test]
    fn scripting_requires_a_positive_result_or_a_known_unavailable_evaluator() {
        assert_eq!(scripting_capability(&Ok(true)), Some(true));
        assert_eq!(
            scripting_capability(&Err(EvalError::Unsupported)),
            Some(false)
        );
        assert_eq!(scripting_capability(&Err(EvalError::Finished)), Some(false));
        assert_eq!(scripting_capability(&Ok(false)), None);
        assert_eq!(
            scripting_capability(&Err(EvalError::InvalidJs("Invalid script".into()))),
            None
        );
        assert_eq!(
            scripting_capability(&Err(EvalError::Communication("Disconnected".into()))),
            None
        );
        let error = serde_json::from_value::<bool>(serde_json::Value::Null).unwrap_err();
        assert_eq!(
            scripting_capability(&Err(EvalError::Serialization(error))),
            None
        );
    }

    #[test]
    fn server_rendering_leaves_the_capability_pending() {
        set_scripting_for_tests(None);
        let mut dom = native_document();
        dom.rebuild_in_place();
        let html = dioxus_ssr::render(&dom);
        set_scripting_for_tests(None);
        assert!(html.contains(">None</span>"), "{html}");
    }

    #[tokio::test]
    async fn actual_native_noop_document_selects_the_fallback_after_polling() {
        set_scripting_for_tests(None);
        let mut dom = native_document();
        dom.rebuild_in_place();
        let pending = dioxus_ssr::render(&dom);
        let completed = tokio::time::timeout(Duration::from_secs(1), dom.wait_for_work()).await;
        dom.render_immediate_to_vec();
        let settled = dioxus_ssr::render(&dom);
        set_scripting_for_tests(None);
        assert!(pending.contains(">None</span>"), "{pending}");
        assert!(completed.is_ok(), "the native probe must settle");
        assert!(settled.contains(">Some(false)</span>"), "{settled}");
    }

    #[test]
    fn javascript_strings_escape_quotes_controls_and_markup() {
        assert_eq!(
            json_string("Máximo \"5\"\n</script>"),
            "\"Máximo \\\"5\\\"\\u000a\\u003c/script\\u003e\""
        );
        assert_eq!(json_string(&"\\".repeat(3)), "\"\\\\\\\\\\\\\"");
    }
}