Skip to main content

lumen_dioxus/overlays/
search_dialog.rs

1//! `SearchDialog` and `SearchDialogTrigger`: a modal site search fed by an async provider, and the
2//! link that opens it.
3//!
4//! The markup matches lumen-react's `SearchDialog`. The dialog shell is the same one [`Dialog`]
5//! renders (`<dialog open>` with a modal dismiss layer), so focus moves to the search field when it
6//! opens and back to the trigger when it closes. The Ctrl+K and Command+K shortcut and following
7//! the first result with Enter run through `document::eval`, so they work on web and desktop but
8//! not on Dioxus Native, which has no JavaScript or document listeners.
9//!
10//! [`Dialog`]: super::Dialog
11
12// cspell:words feff oncompositionend oncompositionstart
13
14use std::collections::{HashMap, HashSet};
15use std::future::Future;
16use std::pin::Pin;
17use std::rc::Rc;
18
19use dioxus::core::Task;
20use dioxus::document::{self, Eval};
21use dioxus::html::input_data::MouseButton;
22use dioxus::prelude::*;
23
24use super::dialog::{
25    DialogBody, DialogClose, DialogController, DialogHeader, DialogKind, DialogShell, DialogTitle,
26    render_dialog, use_dialog, use_dialog_handle,
27};
28use super::shared::{button_class, has_content, surface};
29use crate::class::{Glass, compose};
30use crate::hooks::use_id_or;
31use crate::navigation::util::resolve_safe_href;
32use crate::overlay::focus_element;
33use crate::{ButtonSize, ButtonVariant, Kbd, Label};
34
35/// Classes of the trigger link, which looks like an outline button.
36const TRIGGER_CLASS: &str =
37    "ui-button ui-button--outline ui-button--default-size ui-search-dialog-trigger";
38/// Visible trigger text without a custom label or children.
39const TRIGGER_LABEL: &str = "Search";
40/// Shortcut announced on a trigger once the shortcut listener runs. Both modifiers open the dialog.
41const KEY_SHORTCUTS: &str = "Control+K Meta+K";
42/// Hint the trigger shows before the platform is known.
43const DEFAULT_HINT: &str = "Ctrl K";
44
45/// Listens for Ctrl+K and Command+K on the document, like the core controller in lumen-react.
46/// Receives the dialog id, reports `["ready", platform]` once installed and `["open", ""]` when the
47/// shortcut should open the dialog, and takes `"restore"` (focus what had focus before the
48/// shortcut) and `"stop"`. Values travel through the eval channel, never through the script text.
49const SHORTCUT_SCRIPT: &str = "const id = await dioxus.recv();\n\
50     const editable = target => {\n\
51       if (!(target instanceof Element)) return false;\n\
52       if (target.closest('input, textarea, select, [role=\"textbox\"], [role=\"combobox\"]')) return true;\n\
53       const owner = target.closest('[contenteditable]');\n\
54       return owner !== null && owner.getAttribute('contenteditable') !== 'false';\n\
55     };\n\
56     let returnTarget = null;\n\
57     const onKeyDown = event => {\n\
58       if (event.defaultPrevented || event.repeat || event.isComposing || event.altKey || event.shiftKey) return;\n\
59       if (event.ctrlKey === event.metaKey || typeof event.key !== 'string' || event.key.toLowerCase() !== 'k') return;\n\
60       const dialog = document.getElementById(id);\n\
61       if (!(dialog instanceof HTMLDialogElement)) return;\n\
62       if (dialog.open) {\n\
63         event.preventDefault();\n\
64         document.getElementById(id + '-query')?.focus();\n\
65         return;\n\
66       }\n\
67       if (editable(event.target)) return;\n\
68       if (Array.from(document.querySelectorAll('dialog[open]')).some(other => other !== dialog)) return;\n\
69       event.preventDefault();\n\
70       const active = document.activeElement;\n\
71       returnTarget = active instanceof HTMLElement && active !== document.body ? active : null;\n\
72       dioxus.send(['open', '']);\n\
73     };\n\
74     const restore = () => {\n\
75       const target = returnTarget;\n\
76       returnTarget = null;\n\
77       const dialog = document.getElementById(id);\n\
78       if (!target?.isConnected || dialog?.open) return;\n\
79       const active = document.activeElement;\n\
80       if (active && active !== document.body && !dialog?.contains(active)) return;\n\
81       target.focus({ preventScroll: true });\n\
82     };\n\
83     document.addEventListener('keydown', onKeyDown);\n\
84     dioxus.send(['ready', String(navigator.platform || navigator.userAgent || '')]);\n\
85     for (;;) {\n\
86       const command = await dioxus.recv();\n\
87       if (command === 'stop') break;\n\
88       if (command === 'restore') setTimeout(restore, 0);\n\
89     }\n\
90     document.removeEventListener('keydown', onKeyDown);";
91
92/// Clicks the first result link of the dialog with the received id, so client routers and the
93/// result's own click handler see an ordinary activation.
94const FOLLOW_FIRST_RESULT_SCRIPT: &str = "const id = await dioxus.recv();\n\
95     const link = document.getElementById(id)?.querySelector('[data-slot=\"search-dialog-result\"]');\n\
96     if (link instanceof HTMLElement) link.click();";
97
98/// Attributes the dialog root sets itself; the same names in `attributes` are ignored.
99const RESERVED_ATTRIBUTES: [&str; 14] = [
100    "aria-labelledby",
101    "data-empty-label",
102    "data-failure-label",
103    "data-loading-label",
104    "data-ready",
105    "data-results-label",
106    "data-shortcut",
107    "data-slot",
108    "data-status",
109    "data-ui-owner",
110    "data-ui-search-dialog",
111    "id",
112    "open",
113    "role",
114];
115
116/// One search result. [`SearchDialog`] shows a result only when it has a title and an `http:`,
117/// `https:`, or relative link, and drops later results that repeat a link.
118#[derive(Clone, Debug, PartialEq, Eq)]
119pub struct SearchResult {
120    /// Visible title.
121    pub title: String,
122    /// Link the result opens.
123    pub href: String,
124    /// Optional second line.
125    pub description: Option<String>,
126}
127
128impl SearchResult {
129    /// A result without a description.
130    pub fn new(title: impl Into<String>, href: impl Into<String>) -> Self {
131        Self {
132            title: title.into(),
133            href: href.into(),
134            description: None,
135        }
136    }
137
138    /// Adds a description below the title.
139    #[must_use]
140    pub fn with_description(mut self, description: impl Into<String>) -> Self {
141        self.description = Some(description.into());
142        self
143    }
144}
145
146/// The future a [`SearchDialog`] `search` provider returns: the results for a query, or an error
147/// message, which shows the failure status with a retry button.
148pub type SearchDialogFuture = Pin<Box<dyn Future<Output = Result<Vec<SearchResult>, String>>>>;
149
150/// What a [`SearchDialog`] shows below its field.
151#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
152#[non_exhaustive]
153pub enum SearchDialogStatus {
154    /// No query, or the dialog is closed. The status region is empty.
155    #[default]
156    Idle,
157    /// Waiting for the provider.
158    Loading,
159    /// At least one result.
160    Results,
161    /// The provider returned no usable result.
162    Empty,
163    /// The provider failed; a retry button is shown.
164    Error,
165}
166
167impl SearchDialogStatus {
168    /// The `data-status` value.
169    pub fn as_str(self) -> &'static str {
170        match self {
171            Self::Idle => "idle",
172            Self::Loading => "loading",
173            Self::Results => "results",
174            Self::Empty => "empty",
175            Self::Error => "error",
176        }
177    }
178}
179
180/// Text of a [`SearchDialog`]. Unset or blank fields keep the English default.
181#[derive(Clone, Debug, Default, PartialEq, Eq)]
182pub struct SearchDialogLabels {
183    /// Close button. Default: "Close".
184    pub close: Option<String>,
185    /// Status with no results. Default: "No results found.".
186    pub empty: Option<String>,
187    /// Status after the provider fails. Default: "Search could not be loaded.".
188    pub failure: Option<String>,
189    /// Accessible name of the search field. Default: "Search query".
190    pub field: Option<String>,
191    /// Status while waiting. Default: "Searching…".
192    pub loading: Option<String>,
193    /// Status with results; `{count}` becomes the number of results. Default:
194    /// "Results found: {count}".
195    pub results: Option<String>,
196    /// Retry button. Default: "Retry search".
197    pub retry: Option<String>,
198    /// Dialog title. Default: "Search this site".
199    pub title: Option<String>,
200}
201
202/// Labels with defaults applied.
203#[derive(Clone, Debug, PartialEq, Eq)]
204struct ResolvedLabels {
205    close: String,
206    empty: String,
207    failure: String,
208    field: String,
209    loading: String,
210    results: String,
211    retry: String,
212    title: String,
213}
214
215impl ResolvedLabels {
216    fn new(labels: &SearchDialogLabels) -> Self {
217        Self {
218            close: label_or(labels.close.as_deref(), "Close"),
219            empty: label_or(labels.empty.as_deref(), "No results found."),
220            failure: label_or(labels.failure.as_deref(), "Search could not be loaded."),
221            field: label_or(labels.field.as_deref(), "Search query"),
222            loading: label_or(labels.loading.as_deref(), "Searching…"),
223            results: label_or(labels.results.as_deref(), "Results found: {count}"),
224            retry: label_or(labels.retry.as_deref(), "Retry search"),
225            title: label_or(labels.title.as_deref(), "Search this site"),
226        }
227    }
228}
229
230/// Whitespace that JavaScript's `String.prototype.trim` removes.
231fn is_js_whitespace(character: char) -> bool {
232    const SPACES: [char; 14] = [
233        '\t', '\n', '\u{b}', '\u{c}', '\r', ' ', '\u{a0}', '\u{1680}', '\u{2028}', '\u{2029}',
234        '\u{202f}', '\u{205f}', '\u{3000}', '\u{feff}',
235    ];
236
237    SPACES.contains(&character) || ('\u{2000}'..='\u{200a}').contains(&character)
238}
239
240fn js_trim(value: &str) -> &str {
241    value.trim_matches(is_js_whitespace)
242}
243
244/// A trimmed label, or `fallback` when it is missing or blank.
245fn label_or(value: Option<&str>, fallback: &str) -> String {
246    value
247        .map(js_trim)
248        .filter(|text| !text.is_empty())
249        .unwrap_or(fallback)
250        .to_string()
251}
252
253/// Text of the live status region; `Idle` is empty so nothing is announced.
254fn status_text(status: SearchDialogStatus, count: usize, labels: &ResolvedLabels) -> String {
255    match status {
256        SearchDialogStatus::Idle => String::new(),
257        SearchDialogStatus::Loading => labels.loading.clone(),
258        SearchDialogStatus::Results => labels.results.replace("{count}", &count.to_string()),
259        SearchDialogStatus::Empty => labels.empty.clone(),
260        SearchDialogStatus::Error => labels.failure.clone(),
261    }
262}
263
264/// A trimmed result link when it is an `http:`, `https:`, or relative URL without credentials,
265/// control characters, or backslashes. `javascript:` and every other scheme return `None`.
266fn resolve_search_result_href(value: &str) -> Option<String> {
267    resolve_safe_href(js_trim(value))
268}
269
270/// Keeps results with a title and a safe link, trims their text, and drops later results whose
271/// link is already listed.
272fn normalize_search_results(results: Vec<SearchResult>) -> Vec<SearchResult> {
273    let mut seen = HashSet::new();
274
275    results
276        .into_iter()
277        .filter_map(|result| {
278            let title = js_trim(&result.title);
279
280            if title.is_empty() {
281                return None;
282            }
283
284            let href = resolve_search_result_href(&result.href)?;
285
286            if !seen.insert(href.clone()) {
287                return None;
288            }
289
290            let description = result
291                .description
292                .as_deref()
293                .map(js_trim)
294                .filter(|text| !text.is_empty())
295                .map(str::to_string);
296
297            Some(SearchResult {
298                title: title.to_string(),
299                href,
300                description,
301            })
302        })
303        .collect()
304}
305
306/// What a key does inside the dialog.
307#[derive(Clone, Copy, Debug, PartialEq, Eq)]
308enum KeyAction {
309    /// Focus the result at this index.
310    Focus(usize),
311    /// Follow the result at this index.
312    Follow(usize),
313}
314
315fn has_command_modifier(modifiers: Modifiers) -> bool {
316    modifiers.intersects(Modifiers::ALT | Modifiers::CONTROL | Modifiers::META | Modifiers::SHIFT)
317}
318
319/// The keyboard model of `resolveLumenSearchDialogKey`. `index` is `None` for the search field, or
320/// the focused result. `ArrowDown` and `ArrowUp` move between the field and the results and wrap
321/// among results; Enter in the field follows the first result.
322fn resolve_key(
323    key: &Key,
324    modifiers: Modifiers,
325    composing: bool,
326    count: usize,
327    index: Option<usize>,
328) -> Option<KeyAction> {
329    if composing || count == 0 || index.is_some_and(|current| current >= count) {
330        return None;
331    }
332
333    if has_command_modifier(modifiers) {
334        return None;
335    }
336
337    match key {
338        Key::Enter => index.is_none().then_some(KeyAction::Follow(0)),
339        Key::ArrowDown => Some(KeyAction::Focus(
340            index.map_or(0, |current| (current + 1) % count),
341        )),
342        Key::ArrowUp => Some(KeyAction::Focus(
343            index.map_or(count - 1, |current| (current + count - 1) % count),
344        )),
345        _ => None,
346    }
347}
348
349/// True for Ctrl+K or Command+K without other modifiers, like `isLumenSearchDialogShortcut`.
350fn is_shortcut(key: &Key, modifiers: Modifiers, repeat: bool, composing: bool) -> bool {
351    !repeat
352        && !composing
353        && !modifiers.intersects(Modifiers::ALT | Modifiers::SHIFT)
354        && modifiers.contains(Modifiers::CONTROL) != modifiers.contains(Modifiers::META)
355        && matches!(key, Key::Character(text) if text.to_lowercase() == "k")
356}
357
358/// Shortcut hint for a platform string, such as `navigator.platform` or a user agent.
359fn shortcut_hint(platform: &str) -> &'static str {
360    if ["Mac", "iPhone", "iPad", "iPod"]
361        .iter()
362        .any(|name| platform.contains(name))
363    {
364        "⌘K"
365    } else {
366        DEFAULT_HINT
367    }
368}
369
370/// A primary-button click without modifiers. Modified clicks open the link elsewhere and keep the
371/// dialog open.
372fn is_plain_activation(event: &MouseEvent) -> bool {
373    matches!(event.trigger_button(), None | Some(MouseButton::Primary))
374        && !has_command_modifier(event.modifiers())
375}
376
377fn is_space(key: &Key) -> bool {
378    matches!(key, Key::Character(text) if text == " ")
379}
380
381/// Open state, readiness, and status of a [`SearchDialog`], shared with its
382/// [`SearchDialogTrigger`]s.
383///
384/// Create it with [`use_search_dialog`]. It is `Copy`, so event handlers can capture it.
385#[derive(Clone, Copy, PartialEq)]
386pub struct SearchDialogController {
387    dialog: DialogController,
388    ready: Signal<bool>,
389    hint: Signal<Option<&'static str>>,
390    status: Signal<SearchDialogStatus>,
391    refresh: Signal<u64>,
392}
393
394impl SearchDialogController {
395    /// Whether the dialog is open. Reading it subscribes the component.
396    pub fn is_open(&self) -> bool {
397        self.dialog.is_open()
398    }
399
400    /// Opens the dialog. Focus moves to the search field.
401    pub fn open(&self) {
402        self.dialog.open();
403    }
404
405    /// Closes the dialog.
406    pub fn close(&self) {
407        self.dialog.close();
408    }
409
410    /// What the dialog shows below its field. Reading it subscribes the component.
411    pub fn status(&self) -> SearchDialogStatus {
412        *self.status.read()
413    }
414
415    /// Runs the current query again while the dialog is open, for example after the data behind
416    /// the provider changes.
417    pub fn refresh(&self) {
418        let mut refresh = self.refresh;
419        let next = refresh.peek().wrapping_add(1);
420        refresh.set(next);
421    }
422}
423
424/// A closed search dialog controller. Pass it to [`SearchDialogTrigger`]s and to the `dialog`
425/// prop of the [`SearchDialog`] they open.
426pub fn use_search_dialog() -> SearchDialogController {
427    let dialog = use_dialog();
428
429    use_hook(|| SearchDialogController {
430        dialog,
431        ready: Signal::new(false),
432        hint: Signal::new(None),
433        status: Signal::new(SearchDialogStatus::Idle),
434        refresh: Signal::new(0),
435    })
436}
437
438/// The running shortcut script and the task that reads its messages.
439#[derive(Clone, Copy)]
440struct ShortcutListener {
441    eval: Eval,
442    task: Task,
443}
444
445/// Plain state of one mounted [`SearchDialog`]. Borrows of it stay short: no user code, spawn,
446/// or focus call runs while it is borrowed.
447struct SessionState {
448    controller: SearchDialogController,
449    search: Callback<String, SearchDialogFuture>,
450    id: String,
451    query: String,
452    /// Bumped by every run, close, and unmount; a response from an older generation is ignored.
453    generation: u64,
454    request: Option<Task>,
455    composing: bool,
456    shortcut_opened: bool,
457    /// Mounted result links by href, for arrow-key focus.
458    links: HashMap<String, Rc<MountedData>>,
459    listener: Option<ShortcutListener>,
460}
461
462/// Request sequencing, results, and focus targets of one mounted [`SearchDialog`]. `Copy`, so
463/// event handlers and tasks can capture it.
464#[derive(Clone, Copy)]
465struct SearchSession {
466    state: CopyValue<SessionState>,
467    results: Signal<Vec<SearchResult>>,
468    field: Signal<Option<Rc<MountedData>>>,
469}
470
471impl SearchSession {
472    fn read<R>(self, read: impl FnOnce(&SessionState) -> R) -> R {
473        read(&self.state.peek())
474    }
475
476    fn update<R>(self, update: impl FnOnce(&mut SessionState) -> R) -> R {
477        let mut state = self.state;
478        let mut guard = state.write();
479        update(&mut guard)
480    }
481
482    /// Like [`Self::update`], for unmounting, when the state may already be gone.
483    fn try_update<R>(self, update: impl FnOnce(&mut SessionState) -> R) -> Option<R> {
484        let mut state = self.state;
485        let mut guard = state.try_write().ok()?;
486        Some(update(&mut guard))
487    }
488
489    fn controller(self) -> SearchDialogController {
490        self.read(|state| state.controller)
491    }
492
493    fn dialog(self) -> DialogController {
494        self.controller().dialog
495    }
496
497    fn set_status(self, next: SearchDialogStatus) {
498        let mut status = self.controller().status;
499
500        if *status.peek() != next {
501            status.set(next);
502        }
503    }
504
505    fn set_hint(self, next: Option<&'static str>) {
506        let Some(mut hint) = self
507            .state
508            .try_peek()
509            .ok()
510            .map(|state| state.controller.hint)
511        else {
512            return;
513        };
514
515        if hint.try_peek().is_ok_and(|current| *current != next)
516            && let Ok(mut value) = hint.try_write()
517        {
518            *value = next;
519        }
520    }
521
522    fn clear_results(self) {
523        let mut results = self.results;
524
525        if !results.peek().is_empty() {
526            results.set(Vec::new());
527        }
528    }
529
530    /// Ignores the response of the request in flight and cancels its task.
531    fn cancel(self) {
532        let pending = self.update(|state| {
533            state.generation = state.generation.wrapping_add(1);
534            state.request.take()
535        });
536
537        if let Some(task) = pending {
538            task.cancel();
539        }
540    }
541
542    /// Runs the current query: idle without a query or while closed, otherwise loading until the
543    /// provider answers. A newer run makes the older response stale.
544    fn run(self) {
545        self.cancel();
546        self.clear_results();
547
548        let (query, current, search) = self.read(|state| {
549            (
550                js_trim(&state.query).to_string(),
551                state.generation,
552                state.search,
553            )
554        });
555
556        if query.is_empty() || !self.dialog().is_open_untracked() {
557            self.set_status(SearchDialogStatus::Idle);
558            return;
559        }
560
561        self.set_status(SearchDialogStatus::Loading);
562        let response = search.call(query);
563
564        let task = spawn(async move {
565            let outcome = response.await;
566
567            if self.read(|state| state.generation) != current || !self.dialog().is_open_untracked()
568            {
569                return;
570            }
571
572            self.update(|state| state.request = None);
573            self.finish(outcome);
574        });
575
576        self.update(|state| state.request = Some(task));
577    }
578
579    fn finish(self, outcome: Result<Vec<SearchResult>, String>) {
580        let Ok(items) = outcome else {
581            self.set_status(SearchDialogStatus::Error);
582            return;
583        };
584
585        let items = normalize_search_results(items);
586        let count = items.len();
587
588        if count > 0 {
589            // Links that stay mounted keep their entry; new ones register when they mount.
590            self.update(|state| {
591                state
592                    .links
593                    .retain(|href, _| items.iter().any(|item| item.href == *href));
594            });
595        }
596
597        let mut results = self.results;
598        results.set(items);
599        self.set_status(if count > 0 {
600            SearchDialogStatus::Results
601        } else {
602            SearchDialogStatus::Empty
603        });
604    }
605
606    /// Called when the dialog closes: the request is dropped and the status cleared. Focus goes
607    /// back to what had it before a shortcut opened the dialog.
608    fn end(self) {
609        self.cancel();
610        self.clear_results();
611        self.set_status(SearchDialogStatus::Idle);
612
613        let restore = self.update(|state| {
614            let listener = state.shortcut_opened.then_some(state.listener).flatten();
615            state.shortcut_opened = false;
616            listener
617        });
618
619        if let Some(listener) = restore {
620            let _ = listener.eval.send("restore");
621        }
622    }
623
624    fn input(self, value: String) {
625        let composing = self.update(|state| {
626            state.query = value;
627            state.composing
628        });
629
630        if !composing {
631            self.run();
632        }
633    }
634
635    fn set_composing(self, composing: bool) {
636        self.update(|state| state.composing = composing);
637    }
638
639    fn composition_end(self) {
640        self.set_composing(false);
641        self.run();
642    }
643
644    fn retry(self) {
645        self.focus_field();
646        self.run();
647    }
648
649    fn focus_field(self) {
650        focus_element(self.field.peek().clone());
651    }
652
653    fn focus_result(self, index: usize) {
654        let href = self.results.peek().get(index).map(|item| item.href.clone());
655        let node = href.and_then(|href| self.read(|state| state.links.get(&href).cloned()));
656        focus_element(node);
657    }
658
659    /// Clicks the first result through the page, so its click handler and client routers run.
660    /// Dioxus Native has no script support, so Enter does nothing there.
661    fn follow_first(self) {
662        let id = self.read(|state| state.id.clone());
663        let eval = document::eval(FOLLOW_FIRST_RESULT_SCRIPT);
664        let _ = eval.send(id);
665    }
666
667    fn mount_field(self, node: Rc<MountedData>) {
668        let mut field = self.field;
669        field.set(Some(node));
670    }
671
672    fn mount_link(self, href: String, node: Rc<MountedData>) {
673        self.update(|state| {
674            state.links.insert(href, node);
675        });
676    }
677
678    fn field_key(self, event: &KeyboardEvent) {
679        if !event.default_action_enabled() {
680            return;
681        }
682
683        let key = event.key();
684        let modifiers = event.modifiers();
685        let composing = event.is_composing() || self.read(|state| state.composing);
686
687        if is_shortcut(&key, modifiers, event.is_auto_repeating(), composing) {
688            event.prevent_default();
689            return;
690        }
691
692        if key == Key::Escape && composing {
693            // Escape cancels the composition, not the dialog.
694            event.stop_propagation();
695            return;
696        }
697
698        let count = self.results.peek().len();
699
700        match resolve_key(&key, modifiers, composing, count, None) {
701            Some(KeyAction::Focus(index)) => {
702                event.prevent_default();
703                self.focus_result(index);
704            }
705            Some(KeyAction::Follow(_)) => {
706                event.prevent_default();
707                self.follow_first();
708            }
709            None => {}
710        }
711    }
712
713    fn result_key(self, event: &KeyboardEvent, index: usize) {
714        if !event.default_action_enabled() {
715            return;
716        }
717
718        let key = event.key();
719        let modifiers = event.modifiers();
720        let composing = event.is_composing();
721
722        if is_shortcut(&key, modifiers, event.is_auto_repeating(), composing) {
723            event.prevent_default();
724            self.focus_field();
725            return;
726        }
727
728        let count = self.results.peek().len();
729
730        if let Some(KeyAction::Focus(next)) =
731            resolve_key(&key, modifiers, composing, count, Some(index))
732        {
733            event.prevent_default();
734            self.focus_result(next);
735        }
736    }
737
738    /// Following a result closes the dialog, even when a client router cancels the click; a
739    /// modified click opens another tab and keeps it open.
740    fn result_click(self, event: &MouseEvent) {
741        if is_plain_activation(event) {
742            self.dialog().close();
743        }
744    }
745
746    fn open_from_shortcut(self) {
747        let dialog = self.dialog();
748
749        if dialog.is_open_untracked() {
750            return;
751        }
752
753        self.update(|state| state.shortcut_opened = true);
754        dialog.set_trigger(None);
755        dialog.open();
756    }
757
758    /// Installs the document shortcut listener. Without script support the send fails and no
759    /// listener, hint, or `aria-keyshortcuts` appears.
760    fn start_listener(self, id: String) {
761        let mut eval = document::eval(SHORTCUT_SCRIPT);
762
763        if eval.send(id).is_err() {
764            return;
765        }
766
767        let task = spawn(async move {
768            while let Ok((kind, value)) = eval.recv::<(String, String)>().await {
769                match kind.as_str() {
770                    "ready" => self.set_hint(Some(shortcut_hint(&value))),
771                    "open" => self.open_from_shortcut(),
772                    _ => {}
773                }
774            }
775        });
776
777        self.update(|state| state.listener = Some(ShortcutListener { eval, task }));
778    }
779
780    fn stop_listener(self) {
781        if let Some(active) = self.try_update(|state| state.listener.take()).flatten() {
782            let _ = active.eval.send("stop");
783            active.task.cancel();
784        }
785
786        self.set_hint(None);
787    }
788
789    /// Runs when the dialog unmounts. Any handle may already be gone, so nothing here panics.
790    fn release(self) {
791        if let Some(task) = self.try_update(|state| state.request.take()).flatten() {
792            task.cancel();
793        }
794
795        self.stop_listener();
796
797        if let Some(mut ready) = self
798            .state
799            .try_peek()
800            .ok()
801            .map(|state| state.controller.ready)
802            && let Ok(mut value) = ready.try_write()
803        {
804            *value = false;
805        }
806    }
807}
808
809fn use_search_session(
810    controller: SearchDialogController,
811    search: Callback<String, SearchDialogFuture>,
812    id: &str,
813) -> SearchSession {
814    let session = use_hook(|| SearchSession {
815        state: CopyValue::new(SessionState {
816            controller,
817            search,
818            id: id.to_string(),
819            query: String::new(),
820            generation: 0,
821            request: None,
822            composing: false,
823            shortcut_opened: false,
824            links: HashMap::new(),
825            listener: None,
826        }),
827        results: Signal::new(Vec::new()),
828        field: Signal::new(None),
829    });
830
831    session.update(|state| {
832        state.controller = controller;
833        state.search = search;
834
835        if state.id != id {
836            state.id = id.to_string();
837        }
838    });
839
840    session
841}
842
843/// Runs the query when the dialog opens or the controller asks for a refresh, ends the session
844/// when it closes, marks the controller ready once mounted, and releases everything on unmount.
845fn use_search_lifecycle(session: SearchSession, controller: SearchDialogController) {
846    let open = controller.dialog.is_open();
847    let refresh = *controller.refresh.read();
848    let mut seen = use_hook(|| CopyValue::new((false, refresh)));
849
850    use_effect(use_reactive((&open, &refresh), move |(open, refresh)| {
851        let (was_open, last_refresh) = *seen.peek();
852        seen.set((open, refresh));
853
854        if open && (!was_open || refresh != last_refresh) {
855            session.run();
856        } else if !open && was_open {
857            session.end();
858        }
859    }));
860
861    use_effect(move || {
862        let mut ready = session.controller().ready;
863
864        if !*ready.peek() {
865            ready.set(true);
866        }
867    });
868
869    use_drop(move || session.release());
870}
871
872/// Starts the document shortcut listener while `enabled`, and restarts it when the id changes.
873fn use_shortcut_listener(session: SearchSession, id: &str, enabled: bool) {
874    let id = id.to_string();
875
876    use_effect(use_reactive((&id, &enabled), move |(id, enabled)| {
877        session.stop_listener();
878
879        if enabled {
880            session.start_listener(id);
881        }
882    }));
883}
884
885/// Attributes of the `<dialog>`, like `resolveLumenSearchDialogAttributes` plus the enhanced
886/// `data-ready` and `data-status`.
887fn dialog_attributes(
888    id: &str,
889    labels: &ResolvedLabels,
890    shortcut: bool,
891    status: Option<SearchDialogStatus>,
892    extra: Vec<Attribute>,
893) -> Vec<Attribute> {
894    let text = |name: &'static str, value: String| Attribute::new(name, value, None, false);
895    let mut attributes: Vec<Attribute> = extra
896        .into_iter()
897        .filter(|attribute| !RESERVED_ATTRIBUTES.contains(&attribute.name))
898        .collect();
899
900    attributes.extend([
901        text("aria-labelledby", format!("{id}-title")),
902        text("data-empty-label", labels.empty.clone()),
903        text("data-failure-label", labels.failure.clone()),
904        text("data-loading-label", labels.loading.clone()),
905        text("data-results-label", labels.results.clone()),
906        text("data-slot", "search-dialog".to_string()),
907        text("data-ui-owner", "dioxus".to_string()),
908        text("data-ui-search-dialog", String::new()),
909        text("id", id.to_string()),
910    ]);
911
912    if shortcut {
913        attributes.push(text("data-shortcut", String::new()));
914    }
915
916    if let Some(status) = status {
917        attributes.push(text("data-ready", String::new()));
918        attributes.push(text("data-status", status.as_str().to_string()));
919    }
920
921    attributes
922}
923
924/// One result row.
925fn result_item(session: SearchSession, index: usize, result: SearchResult) -> Element {
926    let SearchResult {
927        title,
928        href,
929        description,
930    } = result;
931    let mounted_href = href.clone();
932
933    rsx! {
934        li { key: "{href}", class: "ui-search-dialog__item",
935            a {
936                class: "ui-search-dialog__result",
937                "data-slot": "search-dialog-result",
938                href: href.clone(),
939                onclick: move |event: MouseEvent| session.result_click(&event),
940                onkeydown: move |event: KeyboardEvent| session.result_key(&event, index),
941                onmounted: move |event: MountedEvent| session.mount_link(mounted_href.clone(), event.data()),
942                span { class: "ui-search-dialog__result-title", "{title}" }
943                if let Some(description) = description {
944                    span { class: "ui-search-dialog__result-description", "{description}" }
945                }
946            }
947        }
948    }
949}
950
951/// Header and body of the dialog, in lumen-react's order.
952fn search_dialog_content(
953    session: SearchSession,
954    id: &str,
955    labels: &ResolvedLabels,
956    status: SearchDialogStatus,
957) -> Element {
958    let results = session.results.read().clone();
959    let status_message = status_text(status, results.len(), labels);
960    let retry_class = button_class(
961        ButtonVariant::Outline,
962        ButtonSize::Default,
963        Some("ui-search-dialog__retry"),
964    );
965    let (title_id, field_id) = (format!("{id}-title"), format!("{id}-query"));
966
967    rsx! {
968        DialogHeader {
969            DialogTitle { id: title_id, "{labels.title}" }
970            DialogClose { variant: ButtonVariant::Outline, "{labels.close}" }
971        }
972        DialogBody { class: "ui-search-dialog__body",
973            Label { r#for: field_id.clone(), "{labels.field}" }
974            input {
975                autocomplete: "off",
976                class: "ui-input ui-search-field",
977                "data-slot": "search-dialog-field",
978                id: field_id,
979                r#type: "search",
980                oncompositionstart: move |_| session.set_composing(true),
981                oncompositionend: move |_| session.composition_end(),
982                oninput: move |event: FormEvent| session.input(event.value()),
983                onkeydown: move |event: KeyboardEvent| session.field_key(&event),
984                onmounted: move |event: MountedEvent| session.mount_field(event.data()),
985            }
986            p {
987                class: "ui-search-dialog__status",
988                "data-slot": "search-dialog-status",
989                role: "status",
990                "{status_message}"
991            }
992            button {
993                class: retry_class,
994                "data-slot": "search-dialog-retry",
995                hidden: status != SearchDialogStatus::Error,
996                r#type: "button",
997                onclick: move |_| session.retry(),
998                span { class: "ui-button__content", "{labels.retry}" }
999            }
1000            ol { class: "ui-search-dialog__results", "data-slot": "search-dialog-results",
1001                for (index, result) in results.into_iter().enumerate() {
1002                    {result_item(session, index, result)}
1003                }
1004            }
1005        }
1006    }
1007}
1008
1009/// Props for [`SearchDialog`].
1010#[derive(Props, Clone, PartialEq)]
1011pub struct SearchDialogProps {
1012    /// Dialog id. A [`SearchDialogTrigger`] `target` names it; the title and field ids derive
1013    /// from it.
1014    #[props(into)]
1015    pub id: String,
1016    /// Returns the results for a query. A newer query, closing the dialog, or unmounting it drops
1017    /// the pending future, so a stale response never shows.
1018    pub search: Callback<String, SearchDialogFuture>,
1019    /// A controller from [`use_search_dialog`], shared with its [`SearchDialogTrigger`]s.
1020    pub dialog: Option<SearchDialogController>,
1021    /// Overrides any of the default title, field, status, close, and retry labels.
1022    #[props(default)]
1023    pub labels: SearchDialogLabels,
1024    /// Opens the dialog with Ctrl+K or Command+K outside text fields (web and desktop). Defaults
1025    /// to true.
1026    #[props(default = true)]
1027    pub shortcut: bool,
1028    /// Extra classes appended after the Lumen classes.
1029    #[props(into)]
1030    pub class: Option<String>,
1031    /// Any other `<dialog>` or global attribute. The search attributes and `id` win over the same
1032    /// names here.
1033    #[props(extends = GlobalAttributes, extends = dialog)]
1034    pub attributes: Vec<Attribute>,
1035}
1036
1037/// A modal site search: a field, a live status, a retry button, and result links from an async
1038/// provider. Arrow keys move between the field and the results, Enter follows the first result,
1039/// and following a result closes the dialog.
1040#[component]
1041pub fn SearchDialog(props: SearchDialogProps) -> Element {
1042    let own = use_search_dialog();
1043    let controller = props.dialog.unwrap_or(own);
1044    let id = use_id_or(Some(props.id.as_str()));
1045    let labels = ResolvedLabels::new(&props.labels);
1046    let session = use_search_session(controller, props.search, &id);
1047    use_search_lifecycle(session, controller);
1048    use_shortcut_listener(session, &id, props.shortcut);
1049
1050    let status = *controller.status.read();
1051    let ready = *controller.ready.read();
1052    let handle = use_dialog_handle(Some(controller.dialog), None, false, None);
1053    let class = compose([Some("ui-dialog ui-search-dialog"), props.class.as_deref()]);
1054    let children = search_dialog_content(session, &id, &labels, status);
1055    let attributes = dialog_attributes(
1056        &id,
1057        &labels,
1058        props.shortcut,
1059        ready.then_some(status),
1060        props.attributes,
1061    );
1062
1063    render_dialog(DialogShell {
1064        handle,
1065        kind: DialogKind::Dialog,
1066        alert: false,
1067        class,
1068        layout: Some("centered"),
1069        surface: surface(Glass::Off),
1070        dismiss_on_escape: true,
1071        dismiss_on_outside_press: true,
1072        initial_focus: Some(session.field),
1073        attributes,
1074        children,
1075    })
1076}
1077
1078/// Props for [`SearchDialogTrigger`].
1079#[derive(Props, Clone, PartialEq)]
1080pub struct SearchDialogTriggerProps {
1081    /// The controller of the dialog this link opens.
1082    pub dialog: SearchDialogController,
1083    /// The `id` of the [`SearchDialog`] to open.
1084    #[props(into)]
1085    pub target: String,
1086    /// Search page the link opens before the dialog is ready, without script support, or on a
1087    /// modified click.
1088    #[props(into)]
1089    pub fallback_href: String,
1090    /// Visible text when the trigger has no children. Default: "Search".
1091    #[props(into)]
1092    pub label: Option<String>,
1093    /// Extra classes appended after the Lumen classes.
1094    #[props(into)]
1095    pub class: Option<String>,
1096    /// Any other `<a>` or global attribute.
1097    #[props(extends = GlobalAttributes, extends = a)]
1098    pub attributes: Vec<Attribute>,
1099    /// Custom content in place of the label.
1100    pub children: Element,
1101}
1102
1103/// A link to the search page that opens its [`SearchDialog`] once the dialog is mounted. While
1104/// the shortcut listener runs it shows the platform's shortcut hint and announces
1105/// `aria-keyshortcuts`.
1106#[component]
1107pub fn SearchDialogTrigger(props: SearchDialogTriggerProps) -> Element {
1108    let controller = props.dialog;
1109    let ready = *controller.ready.read();
1110    let hint = if ready { *controller.hint.read() } else { None };
1111    let mut node = use_signal(|| None::<Rc<MountedData>>);
1112    let class = compose([Some(TRIGGER_CLASS), props.class.as_deref()]);
1113    let custom = has_content(&props.children);
1114    let label = label_or(props.label.as_deref(), TRIGGER_LABEL);
1115    let hint_text = hint.unwrap_or(DEFAULT_HINT);
1116    let open = move || {
1117        controller.dialog.set_trigger(node.peek().clone());
1118        controller.dialog.open();
1119    };
1120
1121    rsx! {
1122        a {
1123            aria_controls: ready.then(|| props.target.clone()),
1124            aria_haspopup: ready.then_some("dialog"),
1125            aria_keyshortcuts: hint.map(|_| KEY_SHORTCUTS),
1126            class,
1127            "data-ready": ready.then_some(""),
1128            "data-shortcut": hint.map(|_| ""),
1129            "data-slot": "search-dialog-trigger",
1130            "data-ui-search-dialog-trigger": props.target.clone(),
1131            href: props.fallback_href.clone(),
1132            role: ready.then_some("button"),
1133            onclick: move |event: MouseEvent| {
1134                if *controller.ready.peek() && event.default_action_enabled() && is_plain_activation(&event) {
1135                    event.prevent_default();
1136                    open();
1137                }
1138            },
1139            onkeydown: move |event: KeyboardEvent| {
1140                if *controller.ready.peek() && event.default_action_enabled() && is_space(&event.key()) {
1141                    event.prevent_default();
1142                    open();
1143                }
1144            },
1145            onmounted: move |event: MountedEvent| node.set(Some(event.data())),
1146            ..props.attributes,
1147            span { class: "ui-button__content",
1148                if custom {
1149                    {props.children}
1150                } else {
1151                    span { "{label}" }
1152                }
1153                Kbd {
1154                    aria_hidden: "true",
1155                    class: "ui-search-dialog-trigger__shortcut",
1156                    "data-slot": "search-dialog-shortcut",
1157                    "{hint_text}"
1158                }
1159            }
1160        }
1161    }
1162}
1163
1164#[cfg(test)]
1165mod tests {
1166    use super::*;
1167
1168    fn labels() -> ResolvedLabels {
1169        ResolvedLabels::new(&SearchDialogLabels::default())
1170    }
1171
1172    #[test]
1173    fn labels_trim_and_keep_defaults_for_blank_values() {
1174        let resolved = ResolvedLabels::new(&SearchDialogLabels {
1175            title: Some("  Find docs \u{feff}".to_string()),
1176            empty: Some(" \t ".to_string()),
1177            ..SearchDialogLabels::default()
1178        });
1179
1180        assert_eq!(resolved.title, "Find docs");
1181        assert_eq!(resolved.empty, "No results found.");
1182        assert_eq!(resolved.close, "Close");
1183        assert_eq!(resolved.loading, "Searching…");
1184    }
1185
1186    #[test]
1187    fn status_text_covers_every_status() {
1188        let labels = labels();
1189
1190        assert_eq!(status_text(SearchDialogStatus::Idle, 3, &labels), "");
1191        assert_eq!(
1192            status_text(SearchDialogStatus::Loading, 0, &labels),
1193            "Searching…"
1194        );
1195        assert_eq!(
1196            status_text(SearchDialogStatus::Results, 2, &labels),
1197            "Results found: 2"
1198        );
1199        assert_eq!(
1200            status_text(SearchDialogStatus::Empty, 0, &labels),
1201            "No results found."
1202        );
1203        assert_eq!(
1204            status_text(SearchDialogStatus::Error, 0, &labels),
1205            "Search could not be loaded."
1206        );
1207
1208        let custom = ResolvedLabels::new(&SearchDialogLabels {
1209            results: Some("{count} of {count}".to_string()),
1210            ..SearchDialogLabels::default()
1211        });
1212
1213        assert_eq!(
1214            status_text(SearchDialogStatus::Results, 4, &custom),
1215            "4 of 4"
1216        );
1217    }
1218
1219    #[test]
1220    fn result_links_keep_web_and_relative_links_only() {
1221        assert_eq!(
1222            resolve_search_result_href("  https://Example.com/docs?q=1#top "),
1223            Some("https://example.com/docs?q=1#top".to_string())
1224        );
1225        assert_eq!(
1226            resolve_search_result_href("/docs/start"),
1227            Some("/docs/start".to_string())
1228        );
1229        assert_eq!(
1230            resolve_search_result_href("#intro"),
1231            Some("#intro".to_string())
1232        );
1233
1234        for unsafe_href in [
1235            "",
1236            "   ",
1237            "javascript:alert(1)",
1238            "JavaScript:alert(1)",
1239            "java\tscript:alert(1)",
1240            "data:text/html,hi",
1241            "mailto:team@example.com",
1242            "https://user:secret@example.com/",
1243            "//evil.example/path",
1244            "/docs\\start",
1245            "/docs/\u{0}start",
1246        ] {
1247            assert_eq!(
1248                resolve_search_result_href(unsafe_href),
1249                None,
1250                "{unsafe_href:?}"
1251            );
1252        }
1253    }
1254
1255    #[test]
1256    fn long_links_are_rejected_in_linear_time() {
1257        let long = format!("https://example.com/{}", "a".repeat(100_000));
1258        assert_eq!(resolve_search_result_href(&long), None);
1259
1260        let colons = ":".repeat(100_000);
1261        assert_eq!(resolve_search_result_href(&colons), None);
1262    }
1263
1264    #[test]
1265    fn normalizing_drops_untitled_unsafe_and_duplicate_results() {
1266        let results = normalize_search_results(vec![
1267            SearchResult::new(" Start ", "/docs/start").with_description("  First steps "),
1268            SearchResult::new("   ", "/docs/blank"),
1269            SearchResult::new("Script", "javascript:alert(1)"),
1270            SearchResult::new("Again", " /docs/start "),
1271            SearchResult::new("Theming", "https://example.com/theming").with_description(" "),
1272        ]);
1273
1274        assert_eq!(
1275            results,
1276            vec![
1277                SearchResult::new("Start", "/docs/start").with_description("First steps"),
1278                SearchResult::new("Theming", "https://example.com/theming"),
1279            ]
1280        );
1281    }
1282
1283    #[test]
1284    fn normalizing_many_results_keeps_order() {
1285        let many: Vec<SearchResult> = (0..10_000)
1286            .map(|index| {
1287                SearchResult::new(format!("Page {index}"), format!("/p/{}", index % 5_000))
1288            })
1289            .collect();
1290        let results = normalize_search_results(many);
1291
1292        assert_eq!(results.len(), 5_000);
1293        assert_eq!(results[4_999].title, "Page 4999");
1294    }
1295
1296    #[test]
1297    fn keys_move_between_the_field_and_results() {
1298        let none = Modifiers::empty();
1299
1300        assert_eq!(
1301            resolve_key(&Key::Enter, none, false, 3, None),
1302            Some(KeyAction::Follow(0))
1303        );
1304        assert_eq!(resolve_key(&Key::Enter, none, false, 3, Some(1)), None);
1305        assert_eq!(
1306            resolve_key(&Key::ArrowDown, none, false, 3, None),
1307            Some(KeyAction::Focus(0))
1308        );
1309        assert_eq!(
1310            resolve_key(&Key::ArrowUp, none, false, 3, None),
1311            Some(KeyAction::Focus(2))
1312        );
1313        assert_eq!(
1314            resolve_key(&Key::ArrowDown, none, false, 3, Some(2)),
1315            Some(KeyAction::Focus(0))
1316        );
1317        assert_eq!(
1318            resolve_key(&Key::ArrowUp, none, false, 3, Some(0)),
1319            Some(KeyAction::Focus(2))
1320        );
1321        assert_eq!(
1322            resolve_key(&Key::ArrowDown, none, false, 3, Some(1)),
1323            Some(KeyAction::Focus(2))
1324        );
1325    }
1326
1327    #[test]
1328    fn keys_do_nothing_without_results_or_with_modifiers() {
1329        let none = Modifiers::empty();
1330
1331        assert_eq!(resolve_key(&Key::Enter, none, false, 0, None), None);
1332        assert_eq!(resolve_key(&Key::ArrowDown, none, true, 3, None), None);
1333        assert_eq!(resolve_key(&Key::ArrowDown, none, false, 3, Some(3)), None);
1334        assert_eq!(
1335            resolve_key(&Key::ArrowDown, Modifiers::SHIFT, false, 3, None),
1336            None
1337        );
1338        assert_eq!(
1339            resolve_key(&Key::Enter, Modifiers::CONTROL, false, 3, None),
1340            None
1341        );
1342        assert_eq!(resolve_key(&Key::Tab, none, false, 3, None), None);
1343        assert_eq!(
1344            resolve_key(&Key::ArrowDown, Modifiers::CAPS_LOCK, false, 3, None),
1345            Some(KeyAction::Focus(0))
1346        );
1347    }
1348
1349    #[test]
1350    fn the_shortcut_needs_exactly_one_of_control_or_command() {
1351        let k = Key::Character("k".to_string());
1352
1353        assert!(is_shortcut(&k, Modifiers::CONTROL, false, false));
1354        assert!(is_shortcut(&k, Modifiers::META, false, false));
1355        assert!(is_shortcut(
1356            &Key::Character("K".to_string()),
1357            Modifiers::META,
1358            false,
1359            false
1360        ));
1361        assert!(!is_shortcut(
1362            &k,
1363            Modifiers::CONTROL | Modifiers::META,
1364            false,
1365            false
1366        ));
1367        assert!(!is_shortcut(&k, Modifiers::empty(), false, false));
1368        assert!(!is_shortcut(
1369            &k,
1370            Modifiers::CONTROL | Modifiers::SHIFT,
1371            false,
1372            false
1373        ));
1374        assert!(!is_shortcut(
1375            &k,
1376            Modifiers::CONTROL | Modifiers::ALT,
1377            false,
1378            false
1379        ));
1380        assert!(!is_shortcut(&k, Modifiers::CONTROL, true, false));
1381        assert!(!is_shortcut(&k, Modifiers::CONTROL, false, true));
1382        assert!(!is_shortcut(
1383            &Key::Character("j".to_string()),
1384            Modifiers::CONTROL,
1385            false,
1386            false
1387        ));
1388    }
1389
1390    #[test]
1391    fn the_hint_follows_the_platform() {
1392        assert_eq!(shortcut_hint("MacIntel"), "⌘K");
1393        assert_eq!(shortcut_hint("iPhone"), "⌘K");
1394        assert_eq!(shortcut_hint("Win32"), "Ctrl K");
1395        assert_eq!(shortcut_hint(""), "Ctrl K");
1396        assert_eq!(shortcut_hint(&"x".repeat(100_000)), "Ctrl K");
1397    }
1398
1399    #[test]
1400    fn dialog_attributes_ignore_reserved_names() {
1401        let attributes = dialog_attributes(
1402            "site-search",
1403            &labels(),
1404            true,
1405            Some(SearchDialogStatus::Loading),
1406            vec![
1407                Attribute::new("id", "other", None, false),
1408                Attribute::new("aria-describedby", "hint", None, false),
1409            ],
1410        );
1411        let text = |name: &str| {
1412            attributes
1413                .iter()
1414                .filter(|attribute| attribute.name == name)
1415                .map(|attribute| match &attribute.value {
1416                    dioxus::dioxus_core::AttributeValue::Text(value) => value.clone(),
1417                    _ => String::new(),
1418                })
1419                .collect::<Vec<_>>()
1420        };
1421
1422        assert_eq!(text("id"), ["site-search"]);
1423        assert_eq!(text("aria-describedby"), ["hint"]);
1424        assert_eq!(text("aria-labelledby"), ["site-search-title"]);
1425        assert_eq!(text("data-shortcut"), [""]);
1426        assert_eq!(text("data-ready"), [""]);
1427        assert_eq!(text("data-status"), ["loading"]);
1428    }
1429}