use std::cell::Cell;
use std::fmt::Write as _;
use dioxus::core::AttributeValue;
use dioxus::document::{self, EvalError};
use dioxus::prelude::*;
thread_local! {
static SCRIPTING: Cell<Option<bool>> = const { Cell::new(None) };
}
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()
}
fn scripting_capability(result: &Result<bool, EvalError>) -> Option<bool> {
match result {
Ok(true) => Some(true),
Err(EvalError::Unsupported | EvalError::Finished) => Some(false),
_ => None,
}
}
#[cfg(test)]
pub(crate) fn set_scripting_for_tests(value: Option<bool>) {
SCRIPTING.with(|cell| cell.set(value));
}
#[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 {
pub(crate) fn attribute(&self, corrected: &str) -> String {
self.pending
.read()
.clone()
.unwrap_or_else(|| corrected.to_string())
}
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() });
});
}
}
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}); }}"
)
}
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}); }}"
)
}
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;
}
});
}
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
}
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)), "\"\\\\\\\\\\\\\"");
}
}