use dioxus::document::{self, Eval};
use dioxus::prelude::*;
pub(crate) async fn write_clipboard(text: String) -> bool {
let eval = document::eval(
"const text = await dioxus.recv();\n\
await navigator.clipboard.writeText(text);\n\
return true;",
);
if eval.send(text).is_err() {
return false;
}
eval.join::<bool>().await.unwrap_or(false)
}
pub(crate) async fn read_selector_text(selector: String) -> Option<String> {
let eval = document::eval(
"const selector = await dioxus.recv();\n\
let target = null;\n\
try { target = document.querySelector(selector); } catch { return null; }\n\
if (!target) return null;\n\
if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) return target.value;\n\
return target.innerText ?? target.textContent ?? null;",
);
eval.send(selector).ok()?;
eval.join::<Option<String>>().await.ok().flatten()
}
pub(crate) async fn location_href() -> Option<String> {
document::eval("return window.location.href;")
.join::<String>()
.await
.ok()
}
pub(crate) fn scroll_window_to_top() {
let _ = document::eval(
"const reduce = typeof window.matchMedia === 'function' &&\n\
window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n\
window.scrollTo({ top: 0, behavior: reduce ? 'auto' : 'smooth' });",
);
}
pub(crate) async fn focus_selector(selector: String) -> bool {
let eval = document::eval(
"const selector = await dioxus.recv();\n\
let target = null;\n\
try { target = document.querySelector(selector); } catch { return false; }\n\
if (!(target instanceof HTMLElement)) return false;\n\
const focusable = 'a[href], area[href], button, input, select, textarea, iframe, summary, [contenteditable=\"\"], [contenteditable=\"true\"], [tabindex]';\n\
if (!target.matches(focusable)) {\n\
target.setAttribute('tabindex', '-1');\n\
target.addEventListener('blur', () => {\n\
if (target.getAttribute('tabindex') === '-1') target.removeAttribute('tabindex');\n\
}, { once: true });\n\
}\n\
target.focus({ preventScroll: true });\n\
return document.activeElement === target;",
);
if eval.send(selector).is_err() {
return false;
}
eval.join::<bool>().await.unwrap_or(false)
}
pub(crate) async fn focus_element_by_id(id: String, child: Option<usize>) -> bool {
let eval = document::eval(
"const [id, child] = await dioxus.recv();\n\
const owner = document.getElementById(id);\n\
const target = child === null ? owner : owner?.children.item(child);\n\
if (!(target instanceof HTMLElement)) return false;\n\
const temporary = !target.hasAttribute('tabindex') && target.tabIndex < 0 && !target.isContentEditable;\n\
const cleanup = () => { if (target.getAttribute('tabindex') === '-1') target.removeAttribute('tabindex'); };\n\
if (temporary) {\n\
target.setAttribute('tabindex', '-1');\n\
target.addEventListener('blur', cleanup, { once: true });\n\
}\n\
target.focus({ preventScroll: child === null });\n\
const focused = document.activeElement === target;\n\
if (temporary && !focused) { target.removeEventListener('blur', cleanup); cleanup(); }\n\
return focused;",
);
if eval.send((id, child)).is_err() {
return false;
}
eval.join::<bool>().await.unwrap_or(false)
}
pub(crate) fn set_busy_by_id(id: String, busy: bool) {
let eval = document::eval(
"const [id, busy] = await dioxus.recv();\n\
const target = document.getElementById(id);\n\
if (!target) return;\n\
if (busy) target.setAttribute('aria-busy', 'true'); else target.removeAttribute('aria-busy');",
);
let _ = eval.send((id, busy));
}
pub(crate) fn apply_root_theme(theme: String, dark: bool) {
let eval = document::eval(
"const [theme, dark] = await dioxus.recv();\n\
const root = document.documentElement;\n\
root.dataset.theme = theme;\n\
root.classList.toggle('dark', dark);",
);
let _ = eval.send((theme, dark));
}
pub(crate) fn apply_root_lang(lang: String) {
let eval = document::eval("document.documentElement.lang = await dioxus.recv();");
let _ = eval.send(lang);
}
pub(crate) async fn native_share_supported() -> bool {
document::eval("return typeof navigator.share === 'function';")
.join::<bool>()
.await
.unwrap_or(false)
}
pub(crate) async fn native_share(
url: String,
title: Option<String>,
text: Option<String>,
) -> String {
let eval = document::eval(
"const [url, title, text] = await dioxus.recv();\n\
if (typeof navigator.share !== 'function') return 'unsupported';\n\
const data = { url };\n\
if (title) data.title = title;\n\
if (text) data.text = text;\n\
try {\n\
if (typeof navigator.canShare === 'function' && !navigator.canShare(data)) return 'unsupported';\n\
await navigator.share(data);\n\
return 'shared';\n\
} catch (error) {\n\
return error && error.name === 'AbortError' ? 'aborted' : 'failed';\n\
}",
);
if eval.send((url, title, text)).is_err() {
return "unsupported".to_string();
}
eval.join::<String>()
.await
.unwrap_or_else(|_| "unsupported".to_string())
}
#[derive(Clone, Copy)]
pub(crate) struct Watcher {
eval: Eval,
}
impl Watcher {
pub(crate) fn send(self, command: &str) {
let _ = self.eval.send(command.to_string());
}
pub(crate) fn stop(self) {
self.send("stop");
}
}
pub(crate) fn watch_scroll_past(
threshold: f64,
mut on_change: impl FnMut(Option<bool>) + 'static,
) -> Watcher {
let mut eval = document::eval(
"const threshold = await dioxus.recv();\n\
let last = null;\n\
const update = () => {\n\
const next = Number.isFinite(window.scrollY) && window.scrollY > threshold;\n\
if (next !== last) { last = next; dioxus.send(next); }\n\
};\n\
window.addEventListener('scroll', update, { passive: true });\n\
window.addEventListener('resize', update, { passive: true });\n\
update();\n\
while ((await dioxus.recv()) !== 'stop') update();\n\
window.removeEventListener('scroll', update);\n\
window.removeEventListener('resize', update);",
);
let _ = eval.send(threshold);
spawn(async move {
let mut received = false;
while let Ok(value) = eval.recv::<bool>().await {
received = true;
on_change(Some(value));
}
if !received {
on_change(None);
}
});
Watcher { eval }
}
pub(crate) fn watch_active_section(
ids: Vec<String>,
offset: f64,
mut on_change: impl FnMut(usize) + 'static,
) -> Watcher {
let mut eval = document::eval(
"const [ids, offset] = await dioxus.recv();\n\
let frame = 0;\n\
let last = -1;\n\
const length = value => Number.parseFloat(value) || 0;\n\
const update = () => {\n\
frame = 0;\n\
const scroller = document.scrollingElement ?? document.documentElement;\n\
const maximum = scroller.scrollHeight - scroller.clientHeight;\n\
let active = 0;\n\
if (maximum > 0 && scroller.scrollTop > 0 && scroller.scrollTop >= maximum - 1) {\n\
active = ids.length - 1;\n\
} else {\n\
const padding = length(getComputedStyle(scroller).scrollPaddingTop);\n\
for (let index = 0; index < ids.length; index++) {\n\
const target = document.getElementById(ids[index]);\n\
if (!target) continue;\n\
const line = Math.max(offset, padding + length(getComputedStyle(target).scrollMarginTop));\n\
if (target.getBoundingClientRect().top > line + 1) break;\n\
active = index;\n\
}\n\
}\n\
if (active !== last) { last = active; dioxus.send(active); }\n\
};\n\
const schedule = () => { frame ||= requestAnimationFrame(update); };\n\
window.addEventListener('scroll', schedule, { passive: true });\n\
window.addEventListener('resize', schedule, { passive: true });\n\
update();\n\
while ((await dioxus.recv()) !== 'stop') schedule();\n\
if (frame) cancelAnimationFrame(frame);\n\
window.removeEventListener('scroll', schedule);\n\
window.removeEventListener('resize', schedule);",
);
let _ = eval.send((ids, offset));
spawn(async move {
while let Ok(value) = eval.recv::<usize>().await {
on_change(value);
}
});
Watcher { eval }
}
pub(crate) fn watch_visible(
id: String,
root_margin: String,
mut on_visible: impl FnMut() + 'static,
) -> Watcher {
let mut eval = document::eval(
"const [id, rootMargin] = await dioxus.recv();\n\
const target = document.getElementById(id);\n\
if (!target || typeof IntersectionObserver !== 'function') return;\n\
const observer = new IntersectionObserver(entries => {\n\
if (entries.some(entry => entry.isIntersecting)) dioxus.send(true);\n\
}, { rootMargin });\n\
observer.observe(target);\n\
while ((await dioxus.recv()) !== 'stop') { observer.unobserve(target); observer.observe(target); }\n\
observer.disconnect();",
);
let _ = eval.send((id, root_margin));
spawn(async move {
while eval.recv::<bool>().await.is_ok() {
on_visible();
}
});
Watcher { eval }
}
pub(crate) fn use_scroll_past(threshold: Option<f64>) -> Signal<Option<bool>> {
let mut past = use_signal(|| Some(false));
let mut watcher = use_hook(|| CopyValue::new(None::<Watcher>));
use_effect(use_reactive((&threshold,), move |(threshold,)| {
if let Some(previous) = watcher.write().take() {
previous.stop();
}
match threshold {
Some(threshold) => {
let next = watch_scroll_past(threshold, move |value| {
if *past.peek() != value {
past.set(value);
}
});
watcher.set(Some(next));
}
None => {
if *past.peek() != Some(false) {
past.set(Some(false));
}
}
}
}));
use_drop(move || {
if let Some(previous) = watcher.write().take() {
previous.stop();
}
});
past
}
const SITE_HEADER_SHEET_SCRIPT: &str = r#"
const panelId = await dioxus.recv();
const doc = document;
const view = window;
const panel = doc.getElementById(panelId);
const root = panel instanceof HTMLElement ? panel.closest('[data-ui-site-header]') : null;
if (!root || !panel.hasAttribute('popover') || !('showPopover' in panel)) return;
const owned = selector =>
Array.from(root.querySelectorAll(selector)).find(element => element.closest('[data-ui-site-header]') === root);
const toggle = owned('[data-ui-site-header-toggle]');
const closeButton = owned('[data-slot="site-header-close"]');
if (!(toggle instanceof HTMLElement)) return;
const isOpen = () => {
try { return panel.matches(':popover-open'); } catch { return false; }
};
// CSS hides the toggle once the header is wide enough to show the navigation inline.
const collapsed = () => view.getComputedStyle(toggle).display !== 'none';
const focusAway = active => active === null || active === doc.body;
// A close this script starts (a followed link, focus leaving, a wider header) leaves focus alone.
let keepFocus = false;
const hide = restoreFocus => {
if (!isOpen()) return;
keepFocus = !restoreFocus;
try { panel.hidePopover(); } catch { keepFocus = false; }
};
const onToggle = event => {
if (event.target !== panel) return;
const restoreFocus = !keepFocus;
const active = doc.activeElement;
const focusInside = active instanceof Node && panel.contains(active);
keepFocus = false;
const open = isOpen();
dioxus.send(open);
// The open sheet covers the toggle, so focus moves to its close button instead.
if (open) {
if (!focusInside) closeButton?.focus({ preventScroll: true });
return;
}
if (restoreFocus && (focusInside || focusAway(active))) toggle.focus({ preventScroll: true });
};
// Client routers cancel the click to navigate in place, so a cancelled click still closes the
// sheet; a modified click opens another tab and keeps it open.
const onClick = event => {
if (!isOpen() || event.button !== 0 || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
if (event.target instanceof Element && event.target.closest('a[href]')) hide(false);
};
// The sheet is not modal, so focus moving behind it closes it.
const onFocusOut = event => {
const next = event.relatedTarget;
if (next instanceof Node && !panel.contains(next)) hide(false);
};
const onResize = () => {
if (!isOpen() || collapsed()) return;
const active = doc.activeElement;
// The browser may already have dropped focus from the close button the wider layout hides.
const focusLost = active === closeButton || focusAway(active);
hide(false);
// The same links now sit inline in the header.
if (focusLost) panel.querySelector('a[href]')?.focus({ preventScroll: true });
};
panel.addEventListener('toggle', onToggle);
panel.addEventListener('click', onClick);
panel.addEventListener('focusout', onFocusOut);
view.addEventListener('resize', onResize, { passive: true });
const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(onResize) : null;
observer?.observe(root);
dioxus.send(isOpen());
while ((await dioxus.recv()) !== 'stop') dioxus.send(isOpen());
observer?.disconnect();
view.removeEventListener('resize', onResize);
panel.removeEventListener('focusout', onFocusOut);
panel.removeEventListener('click', onClick);
panel.removeEventListener('toggle', onToggle);
"#;
pub(crate) fn watch_site_header_sheet(
panel_id: String,
mut on_change: impl FnMut(bool) + 'static,
) -> Watcher {
let mut eval = document::eval(SITE_HEADER_SHEET_SCRIPT);
let _ = eval.send(panel_id);
spawn(async move {
while let Ok(open) = eval.recv::<bool>().await {
on_change(open);
}
});
Watcher { eval }
}
pub(crate) fn use_site_header_sheet(panel_id: Option<&str>) -> Signal<Option<bool>> {
let mut open = use_signal(|| None::<bool>);
let mut watcher = use_hook(|| CopyValue::new(None::<Watcher>));
let panel_id = panel_id.map(str::to_string);
use_effect(use_reactive((&panel_id,), move |(panel_id,)| {
if let Some(previous) = watcher.write().take() {
previous.stop();
}
if open.peek().is_some() {
open.set(None);
}
if let Some(panel_id) = panel_id {
let next = watch_site_header_sheet(panel_id, move |value| {
if *open.peek() != Some(value) {
open.set(Some(value));
}
});
watcher.set(Some(next));
}
}));
use_drop(move || {
if let Some(previous) = watcher.write().take() {
previous.stop();
}
});
open
}