use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use dioxus::core::Task;
use dioxus::document::{self, Eval};
use dioxus::html::input_data::MouseButton;
use dioxus::prelude::*;
use super::dialog::{
DialogBody, DialogClose, DialogController, DialogHeader, DialogKind, DialogShell, DialogTitle,
render_dialog, use_dialog, use_dialog_handle,
};
use super::shared::{button_class, has_content, surface};
use crate::class::{Glass, compose};
use crate::hooks::use_id_or;
use crate::navigation::util::resolve_safe_href;
use crate::overlay::focus_element;
use crate::{ButtonSize, ButtonVariant, Kbd, Label};
const TRIGGER_CLASS: &str =
"ui-button ui-button--outline ui-button--default-size ui-search-dialog-trigger";
const TRIGGER_LABEL: &str = "Search";
const KEY_SHORTCUTS: &str = "Control+K Meta+K";
const DEFAULT_HINT: &str = "Ctrl K";
const SHORTCUT_SCRIPT: &str = "const id = await dioxus.recv();\n\
const editable = target => {\n\
if (!(target instanceof Element)) return false;\n\
if (target.closest('input, textarea, select, [role=\"textbox\"], [role=\"combobox\"]')) return true;\n\
const owner = target.closest('[contenteditable]');\n\
return owner !== null && owner.getAttribute('contenteditable') !== 'false';\n\
};\n\
let returnTarget = null;\n\
const onKeyDown = event => {\n\
if (event.defaultPrevented || event.repeat || event.isComposing || event.altKey || event.shiftKey) return;\n\
if (event.ctrlKey === event.metaKey || typeof event.key !== 'string' || event.key.toLowerCase() !== 'k') return;\n\
const dialog = document.getElementById(id);\n\
if (!(dialog instanceof HTMLDialogElement)) return;\n\
if (dialog.open) {\n\
event.preventDefault();\n\
document.getElementById(id + '-query')?.focus();\n\
return;\n\
}\n\
if (editable(event.target)) return;\n\
if (Array.from(document.querySelectorAll('dialog[open]')).some(other => other !== dialog)) return;\n\
event.preventDefault();\n\
const active = document.activeElement;\n\
returnTarget = active instanceof HTMLElement && active !== document.body ? active : null;\n\
dioxus.send(['open', '']);\n\
};\n\
const restore = () => {\n\
const target = returnTarget;\n\
returnTarget = null;\n\
const dialog = document.getElementById(id);\n\
if (!target?.isConnected || dialog?.open) return;\n\
const active = document.activeElement;\n\
if (active && active !== document.body && !dialog?.contains(active)) return;\n\
target.focus({ preventScroll: true });\n\
};\n\
document.addEventListener('keydown', onKeyDown);\n\
dioxus.send(['ready', String(navigator.platform || navigator.userAgent || '')]);\n\
for (;;) {\n\
const command = await dioxus.recv();\n\
if (command === 'stop') break;\n\
if (command === 'restore') setTimeout(restore, 0);\n\
}\n\
document.removeEventListener('keydown', onKeyDown);";
const FOLLOW_FIRST_RESULT_SCRIPT: &str = "const id = await dioxus.recv();\n\
const link = document.getElementById(id)?.querySelector('[data-slot=\"search-dialog-result\"]');\n\
if (link instanceof HTMLElement) link.click();";
const RESERVED_ATTRIBUTES: [&str; 14] = [
"aria-labelledby",
"data-empty-label",
"data-failure-label",
"data-loading-label",
"data-ready",
"data-results-label",
"data-shortcut",
"data-slot",
"data-status",
"data-ui-owner",
"data-ui-search-dialog",
"id",
"open",
"role",
];
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SearchResult {
pub title: String,
pub href: String,
pub description: Option<String>,
}
impl SearchResult {
pub fn new(title: impl Into<String>, href: impl Into<String>) -> Self {
Self {
title: title.into(),
href: href.into(),
description: None,
}
}
#[must_use]
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
}
pub type SearchDialogFuture = Pin<Box<dyn Future<Output = Result<Vec<SearchResult>, String>>>>;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SearchDialogStatus {
#[default]
Idle,
Loading,
Results,
Empty,
Error,
}
impl SearchDialogStatus {
pub fn as_str(self) -> &'static str {
match self {
Self::Idle => "idle",
Self::Loading => "loading",
Self::Results => "results",
Self::Empty => "empty",
Self::Error => "error",
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SearchDialogLabels {
pub close: Option<String>,
pub empty: Option<String>,
pub failure: Option<String>,
pub field: Option<String>,
pub loading: Option<String>,
pub results: Option<String>,
pub retry: Option<String>,
pub title: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct ResolvedLabels {
close: String,
empty: String,
failure: String,
field: String,
loading: String,
results: String,
retry: String,
title: String,
}
impl ResolvedLabels {
fn new(labels: &SearchDialogLabels) -> Self {
Self {
close: label_or(labels.close.as_deref(), "Close"),
empty: label_or(labels.empty.as_deref(), "No results found."),
failure: label_or(labels.failure.as_deref(), "Search could not be loaded."),
field: label_or(labels.field.as_deref(), "Search query"),
loading: label_or(labels.loading.as_deref(), "Searching…"),
results: label_or(labels.results.as_deref(), "Results found: {count}"),
retry: label_or(labels.retry.as_deref(), "Retry search"),
title: label_or(labels.title.as_deref(), "Search this site"),
}
}
}
fn is_js_whitespace(character: char) -> bool {
const SPACES: [char; 14] = [
'\t', '\n', '\u{b}', '\u{c}', '\r', ' ', '\u{a0}', '\u{1680}', '\u{2028}', '\u{2029}',
'\u{202f}', '\u{205f}', '\u{3000}', '\u{feff}',
];
SPACES.contains(&character) || ('\u{2000}'..='\u{200a}').contains(&character)
}
fn js_trim(value: &str) -> &str {
value.trim_matches(is_js_whitespace)
}
fn label_or(value: Option<&str>, fallback: &str) -> String {
value
.map(js_trim)
.filter(|text| !text.is_empty())
.unwrap_or(fallback)
.to_string()
}
fn status_text(status: SearchDialogStatus, count: usize, labels: &ResolvedLabels) -> String {
match status {
SearchDialogStatus::Idle => String::new(),
SearchDialogStatus::Loading => labels.loading.clone(),
SearchDialogStatus::Results => labels.results.replace("{count}", &count.to_string()),
SearchDialogStatus::Empty => labels.empty.clone(),
SearchDialogStatus::Error => labels.failure.clone(),
}
}
fn resolve_search_result_href(value: &str) -> Option<String> {
resolve_safe_href(js_trim(value))
}
fn normalize_search_results(results: Vec<SearchResult>) -> Vec<SearchResult> {
let mut seen = HashSet::new();
results
.into_iter()
.filter_map(|result| {
let title = js_trim(&result.title);
if title.is_empty() {
return None;
}
let href = resolve_search_result_href(&result.href)?;
if !seen.insert(href.clone()) {
return None;
}
let description = result
.description
.as_deref()
.map(js_trim)
.filter(|text| !text.is_empty())
.map(str::to_string);
Some(SearchResult {
title: title.to_string(),
href,
description,
})
})
.collect()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum KeyAction {
Focus(usize),
Follow(usize),
}
fn has_command_modifier(modifiers: Modifiers) -> bool {
modifiers.intersects(Modifiers::ALT | Modifiers::CONTROL | Modifiers::META | Modifiers::SHIFT)
}
fn resolve_key(
key: &Key,
modifiers: Modifiers,
composing: bool,
count: usize,
index: Option<usize>,
) -> Option<KeyAction> {
if composing || count == 0 || index.is_some_and(|current| current >= count) {
return None;
}
if has_command_modifier(modifiers) {
return None;
}
match key {
Key::Enter => index.is_none().then_some(KeyAction::Follow(0)),
Key::ArrowDown => Some(KeyAction::Focus(
index.map_or(0, |current| (current + 1) % count),
)),
Key::ArrowUp => Some(KeyAction::Focus(
index.map_or(count - 1, |current| (current + count - 1) % count),
)),
_ => None,
}
}
fn is_shortcut(key: &Key, modifiers: Modifiers, repeat: bool, composing: bool) -> bool {
!repeat
&& !composing
&& !modifiers.intersects(Modifiers::ALT | Modifiers::SHIFT)
&& modifiers.contains(Modifiers::CONTROL) != modifiers.contains(Modifiers::META)
&& matches!(key, Key::Character(text) if text.to_lowercase() == "k")
}
fn shortcut_hint(platform: &str) -> &'static str {
if ["Mac", "iPhone", "iPad", "iPod"]
.iter()
.any(|name| platform.contains(name))
{
"⌘K"
} else {
DEFAULT_HINT
}
}
fn is_plain_activation(event: &MouseEvent) -> bool {
matches!(event.trigger_button(), None | Some(MouseButton::Primary))
&& !has_command_modifier(event.modifiers())
}
fn is_space(key: &Key) -> bool {
matches!(key, Key::Character(text) if text == " ")
}
#[derive(Clone, Copy, PartialEq)]
pub struct SearchDialogController {
dialog: DialogController,
ready: Signal<bool>,
hint: Signal<Option<&'static str>>,
status: Signal<SearchDialogStatus>,
refresh: Signal<u64>,
}
impl SearchDialogController {
pub fn is_open(&self) -> bool {
self.dialog.is_open()
}
pub fn open(&self) {
self.dialog.open();
}
pub fn close(&self) {
self.dialog.close();
}
pub fn status(&self) -> SearchDialogStatus {
*self.status.read()
}
pub fn refresh(&self) {
let mut refresh = self.refresh;
let next = refresh.peek().wrapping_add(1);
refresh.set(next);
}
}
pub fn use_search_dialog() -> SearchDialogController {
let dialog = use_dialog();
use_hook(|| SearchDialogController {
dialog,
ready: Signal::new(false),
hint: Signal::new(None),
status: Signal::new(SearchDialogStatus::Idle),
refresh: Signal::new(0),
})
}
#[derive(Clone, Copy)]
struct ShortcutListener {
eval: Eval,
task: Task,
}
struct SessionState {
controller: SearchDialogController,
search: Callback<String, SearchDialogFuture>,
id: String,
query: String,
generation: u64,
request: Option<Task>,
composing: bool,
shortcut_opened: bool,
links: HashMap<String, Rc<MountedData>>,
listener: Option<ShortcutListener>,
}
#[derive(Clone, Copy)]
struct SearchSession {
state: CopyValue<SessionState>,
results: Signal<Vec<SearchResult>>,
field: Signal<Option<Rc<MountedData>>>,
}
impl SearchSession {
fn read<R>(self, read: impl FnOnce(&SessionState) -> R) -> R {
read(&self.state.peek())
}
fn update<R>(self, update: impl FnOnce(&mut SessionState) -> R) -> R {
let mut state = self.state;
let mut guard = state.write();
update(&mut guard)
}
fn try_update<R>(self, update: impl FnOnce(&mut SessionState) -> R) -> Option<R> {
let mut state = self.state;
let mut guard = state.try_write().ok()?;
Some(update(&mut guard))
}
fn controller(self) -> SearchDialogController {
self.read(|state| state.controller)
}
fn dialog(self) -> DialogController {
self.controller().dialog
}
fn set_status(self, next: SearchDialogStatus) {
let mut status = self.controller().status;
if *status.peek() != next {
status.set(next);
}
}
fn set_hint(self, next: Option<&'static str>) {
let Some(mut hint) = self
.state
.try_peek()
.ok()
.map(|state| state.controller.hint)
else {
return;
};
if hint.try_peek().is_ok_and(|current| *current != next)
&& let Ok(mut value) = hint.try_write()
{
*value = next;
}
}
fn clear_results(self) {
let mut results = self.results;
if !results.peek().is_empty() {
results.set(Vec::new());
}
}
fn cancel(self) {
let pending = self.update(|state| {
state.generation = state.generation.wrapping_add(1);
state.request.take()
});
if let Some(task) = pending {
task.cancel();
}
}
fn run(self) {
self.cancel();
self.clear_results();
let (query, current, search) = self.read(|state| {
(
js_trim(&state.query).to_string(),
state.generation,
state.search,
)
});
if query.is_empty() || !self.dialog().is_open_untracked() {
self.set_status(SearchDialogStatus::Idle);
return;
}
self.set_status(SearchDialogStatus::Loading);
let response = search.call(query);
let task = spawn(async move {
let outcome = response.await;
if self.read(|state| state.generation) != current || !self.dialog().is_open_untracked()
{
return;
}
self.update(|state| state.request = None);
self.finish(outcome);
});
self.update(|state| state.request = Some(task));
}
fn finish(self, outcome: Result<Vec<SearchResult>, String>) {
let Ok(items) = outcome else {
self.set_status(SearchDialogStatus::Error);
return;
};
let items = normalize_search_results(items);
let count = items.len();
if count > 0 {
self.update(|state| {
state
.links
.retain(|href, _| items.iter().any(|item| item.href == *href));
});
}
let mut results = self.results;
results.set(items);
self.set_status(if count > 0 {
SearchDialogStatus::Results
} else {
SearchDialogStatus::Empty
});
}
fn end(self) {
self.cancel();
self.clear_results();
self.set_status(SearchDialogStatus::Idle);
let restore = self.update(|state| {
let listener = state.shortcut_opened.then_some(state.listener).flatten();
state.shortcut_opened = false;
listener
});
if let Some(listener) = restore {
let _ = listener.eval.send("restore");
}
}
fn input(self, value: String) {
let composing = self.update(|state| {
state.query = value;
state.composing
});
if !composing {
self.run();
}
}
fn set_composing(self, composing: bool) {
self.update(|state| state.composing = composing);
}
fn composition_end(self) {
self.set_composing(false);
self.run();
}
fn retry(self) {
self.focus_field();
self.run();
}
fn focus_field(self) {
focus_element(self.field.peek().clone());
}
fn focus_result(self, index: usize) {
let href = self.results.peek().get(index).map(|item| item.href.clone());
let node = href.and_then(|href| self.read(|state| state.links.get(&href).cloned()));
focus_element(node);
}
fn follow_first(self) {
let id = self.read(|state| state.id.clone());
let eval = document::eval(FOLLOW_FIRST_RESULT_SCRIPT);
let _ = eval.send(id);
}
fn mount_field(self, node: Rc<MountedData>) {
let mut field = self.field;
field.set(Some(node));
}
fn mount_link(self, href: String, node: Rc<MountedData>) {
self.update(|state| {
state.links.insert(href, node);
});
}
fn field_key(self, event: &KeyboardEvent) {
if !event.default_action_enabled() {
return;
}
let key = event.key();
let modifiers = event.modifiers();
let composing = event.is_composing() || self.read(|state| state.composing);
if is_shortcut(&key, modifiers, event.is_auto_repeating(), composing) {
event.prevent_default();
return;
}
if key == Key::Escape && composing {
event.stop_propagation();
return;
}
let count = self.results.peek().len();
match resolve_key(&key, modifiers, composing, count, None) {
Some(KeyAction::Focus(index)) => {
event.prevent_default();
self.focus_result(index);
}
Some(KeyAction::Follow(_)) => {
event.prevent_default();
self.follow_first();
}
None => {}
}
}
fn result_key(self, event: &KeyboardEvent, index: usize) {
if !event.default_action_enabled() {
return;
}
let key = event.key();
let modifiers = event.modifiers();
let composing = event.is_composing();
if is_shortcut(&key, modifiers, event.is_auto_repeating(), composing) {
event.prevent_default();
self.focus_field();
return;
}
let count = self.results.peek().len();
if let Some(KeyAction::Focus(next)) =
resolve_key(&key, modifiers, composing, count, Some(index))
{
event.prevent_default();
self.focus_result(next);
}
}
fn result_click(self, event: &MouseEvent) {
if is_plain_activation(event) {
self.dialog().close();
}
}
fn open_from_shortcut(self) {
let dialog = self.dialog();
if dialog.is_open_untracked() {
return;
}
self.update(|state| state.shortcut_opened = true);
dialog.set_trigger(None);
dialog.open();
}
fn start_listener(self, id: String) {
let mut eval = document::eval(SHORTCUT_SCRIPT);
if eval.send(id).is_err() {
return;
}
let task = spawn(async move {
while let Ok((kind, value)) = eval.recv::<(String, String)>().await {
match kind.as_str() {
"ready" => self.set_hint(Some(shortcut_hint(&value))),
"open" => self.open_from_shortcut(),
_ => {}
}
}
});
self.update(|state| state.listener = Some(ShortcutListener { eval, task }));
}
fn stop_listener(self) {
if let Some(active) = self.try_update(|state| state.listener.take()).flatten() {
let _ = active.eval.send("stop");
active.task.cancel();
}
self.set_hint(None);
}
fn release(self) {
if let Some(task) = self.try_update(|state| state.request.take()).flatten() {
task.cancel();
}
self.stop_listener();
if let Some(mut ready) = self
.state
.try_peek()
.ok()
.map(|state| state.controller.ready)
&& let Ok(mut value) = ready.try_write()
{
*value = false;
}
}
}
fn use_search_session(
controller: SearchDialogController,
search: Callback<String, SearchDialogFuture>,
id: &str,
) -> SearchSession {
let session = use_hook(|| SearchSession {
state: CopyValue::new(SessionState {
controller,
search,
id: id.to_string(),
query: String::new(),
generation: 0,
request: None,
composing: false,
shortcut_opened: false,
links: HashMap::new(),
listener: None,
}),
results: Signal::new(Vec::new()),
field: Signal::new(None),
});
session.update(|state| {
state.controller = controller;
state.search = search;
if state.id != id {
state.id = id.to_string();
}
});
session
}
fn use_search_lifecycle(session: SearchSession, controller: SearchDialogController) {
let open = controller.dialog.is_open();
let refresh = *controller.refresh.read();
let mut seen = use_hook(|| CopyValue::new((false, refresh)));
use_effect(use_reactive((&open, &refresh), move |(open, refresh)| {
let (was_open, last_refresh) = *seen.peek();
seen.set((open, refresh));
if open && (!was_open || refresh != last_refresh) {
session.run();
} else if !open && was_open {
session.end();
}
}));
use_effect(move || {
let mut ready = session.controller().ready;
if !*ready.peek() {
ready.set(true);
}
});
use_drop(move || session.release());
}
fn use_shortcut_listener(session: SearchSession, id: &str, enabled: bool) {
let id = id.to_string();
use_effect(use_reactive((&id, &enabled), move |(id, enabled)| {
session.stop_listener();
if enabled {
session.start_listener(id);
}
}));
}
fn dialog_attributes(
id: &str,
labels: &ResolvedLabels,
shortcut: bool,
status: Option<SearchDialogStatus>,
extra: Vec<Attribute>,
) -> Vec<Attribute> {
let text = |name: &'static str, value: String| Attribute::new(name, value, None, false);
let mut attributes: Vec<Attribute> = extra
.into_iter()
.filter(|attribute| !RESERVED_ATTRIBUTES.contains(&attribute.name))
.collect();
attributes.extend([
text("aria-labelledby", format!("{id}-title")),
text("data-empty-label", labels.empty.clone()),
text("data-failure-label", labels.failure.clone()),
text("data-loading-label", labels.loading.clone()),
text("data-results-label", labels.results.clone()),
text("data-slot", "search-dialog".to_string()),
text("data-ui-owner", "dioxus".to_string()),
text("data-ui-search-dialog", String::new()),
text("id", id.to_string()),
]);
if shortcut {
attributes.push(text("data-shortcut", String::new()));
}
if let Some(status) = status {
attributes.push(text("data-ready", String::new()));
attributes.push(text("data-status", status.as_str().to_string()));
}
attributes
}
fn result_item(session: SearchSession, index: usize, result: SearchResult) -> Element {
let SearchResult {
title,
href,
description,
} = result;
let mounted_href = href.clone();
rsx! {
li { key: "{href}", class: "ui-search-dialog__item",
a {
class: "ui-search-dialog__result",
"data-slot": "search-dialog-result",
href: href.clone(),
onclick: move |event: MouseEvent| session.result_click(&event),
onkeydown: move |event: KeyboardEvent| session.result_key(&event, index),
onmounted: move |event: MountedEvent| session.mount_link(mounted_href.clone(), event.data()),
span { class: "ui-search-dialog__result-title", "{title}" }
if let Some(description) = description {
span { class: "ui-search-dialog__result-description", "{description}" }
}
}
}
}
}
fn search_dialog_content(
session: SearchSession,
id: &str,
labels: &ResolvedLabels,
status: SearchDialogStatus,
) -> Element {
let results = session.results.read().clone();
let status_message = status_text(status, results.len(), labels);
let retry_class = button_class(
ButtonVariant::Outline,
ButtonSize::Default,
Some("ui-search-dialog__retry"),
);
let (title_id, field_id) = (format!("{id}-title"), format!("{id}-query"));
rsx! {
DialogHeader {
DialogTitle { id: title_id, "{labels.title}" }
DialogClose { variant: ButtonVariant::Outline, "{labels.close}" }
}
DialogBody { class: "ui-search-dialog__body",
Label { r#for: field_id.clone(), "{labels.field}" }
input {
autocomplete: "off",
class: "ui-input ui-search-field",
"data-slot": "search-dialog-field",
id: field_id,
r#type: "search",
oncompositionstart: move |_| session.set_composing(true),
oncompositionend: move |_| session.composition_end(),
oninput: move |event: FormEvent| session.input(event.value()),
onkeydown: move |event: KeyboardEvent| session.field_key(&event),
onmounted: move |event: MountedEvent| session.mount_field(event.data()),
}
p {
class: "ui-search-dialog__status",
"data-slot": "search-dialog-status",
role: "status",
"{status_message}"
}
button {
class: retry_class,
"data-slot": "search-dialog-retry",
hidden: status != SearchDialogStatus::Error,
r#type: "button",
onclick: move |_| session.retry(),
span { class: "ui-button__content", "{labels.retry}" }
}
ol { class: "ui-search-dialog__results", "data-slot": "search-dialog-results",
for (index, result) in results.into_iter().enumerate() {
{result_item(session, index, result)}
}
}
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct SearchDialogProps {
#[props(into)]
pub id: String,
pub search: Callback<String, SearchDialogFuture>,
pub dialog: Option<SearchDialogController>,
#[props(default)]
pub labels: SearchDialogLabels,
#[props(default = true)]
pub shortcut: bool,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = dialog)]
pub attributes: Vec<Attribute>,
}
#[component]
pub fn SearchDialog(props: SearchDialogProps) -> Element {
let own = use_search_dialog();
let controller = props.dialog.unwrap_or(own);
let id = use_id_or(Some(props.id.as_str()));
let labels = ResolvedLabels::new(&props.labels);
let session = use_search_session(controller, props.search, &id);
use_search_lifecycle(session, controller);
use_shortcut_listener(session, &id, props.shortcut);
let status = *controller.status.read();
let ready = *controller.ready.read();
let handle = use_dialog_handle(Some(controller.dialog), None, false, None);
let class = compose([Some("ui-dialog ui-search-dialog"), props.class.as_deref()]);
let children = search_dialog_content(session, &id, &labels, status);
let attributes = dialog_attributes(
&id,
&labels,
props.shortcut,
ready.then_some(status),
props.attributes,
);
render_dialog(DialogShell {
handle,
kind: DialogKind::Dialog,
alert: false,
class,
layout: Some("centered"),
surface: surface(Glass::Off),
dismiss_on_escape: true,
dismiss_on_outside_press: true,
initial_focus: Some(session.field),
attributes,
children,
})
}
#[derive(Props, Clone, PartialEq)]
pub struct SearchDialogTriggerProps {
pub dialog: SearchDialogController,
#[props(into)]
pub target: String,
#[props(into)]
pub fallback_href: String,
#[props(into)]
pub label: Option<String>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = a)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[component]
pub fn SearchDialogTrigger(props: SearchDialogTriggerProps) -> Element {
let controller = props.dialog;
let ready = *controller.ready.read();
let hint = if ready { *controller.hint.read() } else { None };
let mut node = use_signal(|| None::<Rc<MountedData>>);
let class = compose([Some(TRIGGER_CLASS), props.class.as_deref()]);
let custom = has_content(&props.children);
let label = label_or(props.label.as_deref(), TRIGGER_LABEL);
let hint_text = hint.unwrap_or(DEFAULT_HINT);
let open = move || {
controller.dialog.set_trigger(node.peek().clone());
controller.dialog.open();
};
rsx! {
a {
aria_controls: ready.then(|| props.target.clone()),
aria_haspopup: ready.then_some("dialog"),
aria_keyshortcuts: hint.map(|_| KEY_SHORTCUTS),
class,
"data-ready": ready.then_some(""),
"data-shortcut": hint.map(|_| ""),
"data-slot": "search-dialog-trigger",
"data-ui-search-dialog-trigger": props.target.clone(),
href: props.fallback_href.clone(),
role: ready.then_some("button"),
onclick: move |event: MouseEvent| {
if *controller.ready.peek() && event.default_action_enabled() && is_plain_activation(&event) {
event.prevent_default();
open();
}
},
onkeydown: move |event: KeyboardEvent| {
if *controller.ready.peek() && event.default_action_enabled() && is_space(&event.key()) {
event.prevent_default();
open();
}
},
onmounted: move |event: MountedEvent| node.set(Some(event.data())),
..props.attributes,
span { class: "ui-button__content",
if custom {
{props.children}
} else {
span { "{label}" }
}
Kbd {
aria_hidden: "true",
class: "ui-search-dialog-trigger__shortcut",
"data-slot": "search-dialog-shortcut",
"{hint_text}"
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn labels() -> ResolvedLabels {
ResolvedLabels::new(&SearchDialogLabels::default())
}
#[test]
fn labels_trim_and_keep_defaults_for_blank_values() {
let resolved = ResolvedLabels::new(&SearchDialogLabels {
title: Some(" Find docs \u{feff}".to_string()),
empty: Some(" \t ".to_string()),
..SearchDialogLabels::default()
});
assert_eq!(resolved.title, "Find docs");
assert_eq!(resolved.empty, "No results found.");
assert_eq!(resolved.close, "Close");
assert_eq!(resolved.loading, "Searching…");
}
#[test]
fn status_text_covers_every_status() {
let labels = labels();
assert_eq!(status_text(SearchDialogStatus::Idle, 3, &labels), "");
assert_eq!(
status_text(SearchDialogStatus::Loading, 0, &labels),
"Searching…"
);
assert_eq!(
status_text(SearchDialogStatus::Results, 2, &labels),
"Results found: 2"
);
assert_eq!(
status_text(SearchDialogStatus::Empty, 0, &labels),
"No results found."
);
assert_eq!(
status_text(SearchDialogStatus::Error, 0, &labels),
"Search could not be loaded."
);
let custom = ResolvedLabels::new(&SearchDialogLabels {
results: Some("{count} of {count}".to_string()),
..SearchDialogLabels::default()
});
assert_eq!(
status_text(SearchDialogStatus::Results, 4, &custom),
"4 of 4"
);
}
#[test]
fn result_links_keep_web_and_relative_links_only() {
assert_eq!(
resolve_search_result_href(" https://Example.com/docs?q=1#top "),
Some("https://example.com/docs?q=1#top".to_string())
);
assert_eq!(
resolve_search_result_href("/docs/start"),
Some("/docs/start".to_string())
);
assert_eq!(
resolve_search_result_href("#intro"),
Some("#intro".to_string())
);
for unsafe_href in [
"",
" ",
"javascript:alert(1)",
"JavaScript:alert(1)",
"java\tscript:alert(1)",
"data:text/html,hi",
"mailto:team@example.com",
"https://user:secret@example.com/",
"//evil.example/path",
"/docs\\start",
"/docs/\u{0}start",
] {
assert_eq!(
resolve_search_result_href(unsafe_href),
None,
"{unsafe_href:?}"
);
}
}
#[test]
fn long_links_are_rejected_in_linear_time() {
let long = format!("https://example.com/{}", "a".repeat(100_000));
assert_eq!(resolve_search_result_href(&long), None);
let colons = ":".repeat(100_000);
assert_eq!(resolve_search_result_href(&colons), None);
}
#[test]
fn normalizing_drops_untitled_unsafe_and_duplicate_results() {
let results = normalize_search_results(vec![
SearchResult::new(" Start ", "/docs/start").with_description(" First steps "),
SearchResult::new(" ", "/docs/blank"),
SearchResult::new("Script", "javascript:alert(1)"),
SearchResult::new("Again", " /docs/start "),
SearchResult::new("Theming", "https://example.com/theming").with_description(" "),
]);
assert_eq!(
results,
vec![
SearchResult::new("Start", "/docs/start").with_description("First steps"),
SearchResult::new("Theming", "https://example.com/theming"),
]
);
}
#[test]
fn normalizing_many_results_keeps_order() {
let many: Vec<SearchResult> = (0..10_000)
.map(|index| {
SearchResult::new(format!("Page {index}"), format!("/p/{}", index % 5_000))
})
.collect();
let results = normalize_search_results(many);
assert_eq!(results.len(), 5_000);
assert_eq!(results[4_999].title, "Page 4999");
}
#[test]
fn keys_move_between_the_field_and_results() {
let none = Modifiers::empty();
assert_eq!(
resolve_key(&Key::Enter, none, false, 3, None),
Some(KeyAction::Follow(0))
);
assert_eq!(resolve_key(&Key::Enter, none, false, 3, Some(1)), None);
assert_eq!(
resolve_key(&Key::ArrowDown, none, false, 3, None),
Some(KeyAction::Focus(0))
);
assert_eq!(
resolve_key(&Key::ArrowUp, none, false, 3, None),
Some(KeyAction::Focus(2))
);
assert_eq!(
resolve_key(&Key::ArrowDown, none, false, 3, Some(2)),
Some(KeyAction::Focus(0))
);
assert_eq!(
resolve_key(&Key::ArrowUp, none, false, 3, Some(0)),
Some(KeyAction::Focus(2))
);
assert_eq!(
resolve_key(&Key::ArrowDown, none, false, 3, Some(1)),
Some(KeyAction::Focus(2))
);
}
#[test]
fn keys_do_nothing_without_results_or_with_modifiers() {
let none = Modifiers::empty();
assert_eq!(resolve_key(&Key::Enter, none, false, 0, None), None);
assert_eq!(resolve_key(&Key::ArrowDown, none, true, 3, None), None);
assert_eq!(resolve_key(&Key::ArrowDown, none, false, 3, Some(3)), None);
assert_eq!(
resolve_key(&Key::ArrowDown, Modifiers::SHIFT, false, 3, None),
None
);
assert_eq!(
resolve_key(&Key::Enter, Modifiers::CONTROL, false, 3, None),
None
);
assert_eq!(resolve_key(&Key::Tab, none, false, 3, None), None);
assert_eq!(
resolve_key(&Key::ArrowDown, Modifiers::CAPS_LOCK, false, 3, None),
Some(KeyAction::Focus(0))
);
}
#[test]
fn the_shortcut_needs_exactly_one_of_control_or_command() {
let k = Key::Character("k".to_string());
assert!(is_shortcut(&k, Modifiers::CONTROL, false, false));
assert!(is_shortcut(&k, Modifiers::META, false, false));
assert!(is_shortcut(
&Key::Character("K".to_string()),
Modifiers::META,
false,
false
));
assert!(!is_shortcut(
&k,
Modifiers::CONTROL | Modifiers::META,
false,
false
));
assert!(!is_shortcut(&k, Modifiers::empty(), false, false));
assert!(!is_shortcut(
&k,
Modifiers::CONTROL | Modifiers::SHIFT,
false,
false
));
assert!(!is_shortcut(
&k,
Modifiers::CONTROL | Modifiers::ALT,
false,
false
));
assert!(!is_shortcut(&k, Modifiers::CONTROL, true, false));
assert!(!is_shortcut(&k, Modifiers::CONTROL, false, true));
assert!(!is_shortcut(
&Key::Character("j".to_string()),
Modifiers::CONTROL,
false,
false
));
}
#[test]
fn the_hint_follows_the_platform() {
assert_eq!(shortcut_hint("MacIntel"), "⌘K");
assert_eq!(shortcut_hint("iPhone"), "⌘K");
assert_eq!(shortcut_hint("Win32"), "Ctrl K");
assert_eq!(shortcut_hint(""), "Ctrl K");
assert_eq!(shortcut_hint(&"x".repeat(100_000)), "Ctrl K");
}
#[test]
fn dialog_attributes_ignore_reserved_names() {
let attributes = dialog_attributes(
"site-search",
&labels(),
true,
Some(SearchDialogStatus::Loading),
vec![
Attribute::new("id", "other", None, false),
Attribute::new("aria-describedby", "hint", None, false),
],
);
let text = |name: &str| {
attributes
.iter()
.filter(|attribute| attribute.name == name)
.map(|attribute| match &attribute.value {
dioxus::dioxus_core::AttributeValue::Text(value) => value.clone(),
_ => String::new(),
})
.collect::<Vec<_>>()
};
assert_eq!(text("id"), ["site-search"]);
assert_eq!(text("aria-describedby"), ["hint"]);
assert_eq!(text("aria-labelledby"), ["site-search-title"]);
assert_eq!(text("data-shortcut"), [""]);
assert_eq!(text("data-ready"), [""]);
assert_eq!(text("data-status"), ["loading"]);
}
}