lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! Optional web and desktop (webview) enhancements through `dioxus::document::eval`.
//!
//! Dioxus Native has no JavaScript, so every helper here fails quietly there: calls return `false`
//! or `None`, and watchers never report. Values always travel through the eval channel
//! (`dioxus.recv()`), never by formatting them into the script, so author input cannot inject code.
// cspell:words focusout unobserve

use dioxus::document::{self, Eval};
use dioxus::prelude::*;

/// Writes text to the system clipboard. Returns whether the write succeeded.
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)
}

/// Reads the value (form controls) or text of the first element matching a CSS selector.
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()
}

/// The current page URL, or `None` when there is no browser location.
pub(crate) async fn location_href() -> Option<String> {
    document::eval("return window.location.href;")
        .join::<String>()
        .await
        .ok()
}

/// Scrolls the window to the top, smoothly unless the user prefers reduced motion.
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' });",
    );
}

/// Focuses the first element matching `selector` without scrolling, making it temporarily
/// focusable when needed (like the `focusTarget` of `BackToTop` in lumen-react).
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)
}

/// Focuses the element with `id`, or its child at `child` when set, making it temporarily
/// focusable. Used for anchor destinations and newly loaded feed items.
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)
}

/// Sets or removes `aria-busy="true"` on the element with `id`.
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));
}

/// Sets `data-theme` on the document root and toggles its `dark` class, like the Lumen web
/// runtime's theme toggle.
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));
}

/// Sets the document language, like lumen-react's language toggle.
pub(crate) fn apply_root_lang(lang: String) {
    let eval = document::eval("document.documentElement.lang = await dioxus.recv();");
    let _ = eval.send(lang);
}

/// Whether the browser exposes the Web Share API.
pub(crate) async fn native_share_supported() -> bool {
    document::eval("return typeof navigator.share === 'function';")
        .join::<bool>()
        .await
        .unwrap_or(false)
}

/// Opens the platform share sheet. Resolves to `shared`, `aborted`, `failed`, or `unsupported`,
/// like `requestLumenNativeShare`.
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())
}

/// A long-running script that reports values until it is told to stop.
#[derive(Clone, Copy)]
pub(crate) struct Watcher {
    eval: Eval,
}

impl Watcher {
    /// Sends a command, such as `"refresh"`, to the running script.
    pub(crate) fn send(self, command: &str) {
        let _ = self.eval.send(command.to_string());
    }

    /// Ends the script and removes its listeners.
    pub(crate) fn stop(self) {
        self.send("stop");
    }
}

/// Reports whether the window has scrolled past `threshold` pixels, on every change. Reports
/// `None` once when the renderer cannot run the script, as on Dioxus Native.
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 }
}

/// Reports the index of the active section among `ids` while the page scrolls, like
/// `getLumenActiveAnchorIndex`: the last heading whose top passed the landing line, or the last
/// one at the end of the document.
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 }
}

/// Reports when the element with `id` scrolls into view (`IntersectionObserver`). Send `"refresh"`
/// to observe it again, so a sentinel that stays visible after a load fires once more.
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 }
}

/// Whether the window has scrolled past `threshold` pixels, tracked on web and desktop.
///
/// `Some(false)` during server rendering and while `threshold` is `None`; `None` once the
/// renderer turns out to have no scroll position to read, as on Dioxus Native.
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
}

/// Mirrors a `SiteHeader` sheet, like the `sheet` mode of lumen-core's
/// `createLumenSiteHeaderController`. It reports whether the popover panel is open after every
/// toggle, moves focus to the close button when the sheet opens and back to the toggle when
/// Escape, the close button, or an outside press hides it, and hides the sheet itself after a
/// plain link click, when focus leaves it, and when the header grows wide enough to hide the
/// toggle. It returns without reporting when the panel is missing or the browser has no Popover
/// API.
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);
"#;

/// Runs `SITE_HEADER_SHEET_SCRIPT` for the sheet panel with `panel_id` and reports whether the
/// sheet is open, once at the start and after every toggle. Reports nothing where the renderer
/// cannot run the script, as on Dioxus Native, or the browser has no Popover API.
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 }
}

/// Whether a `SiteHeader` sheet is open, mirrored from its native popover on web and desktop.
///
/// `None` during server rendering, while `panel_id` is `None` (the header is not a sheet), and
/// where the script cannot run or the browser has no Popover API, as on Dioxus Native, so the
/// toggle keeps the server markup's lack of `aria-expanded` there.
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
}