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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
//! `SearchDialog` and `SearchDialogTrigger`: a modal site search fed by an async provider, and the
//! link that opens it.
//!
//! The markup matches lumen-react's `SearchDialog`. The dialog shell is the same one [`Dialog`]
//! renders (`<dialog open>` with a modal dismiss layer), so focus moves to the search field when it
//! opens and back to the trigger when it closes. The Ctrl+K and Command+K shortcut and following
//! the first result with Enter run through `document::eval`, so they work on web and desktop but
//! not on Dioxus Native, which has no JavaScript or document listeners.
//!
//! [`Dialog`]: super::Dialog

// cspell:words feff oncompositionend oncompositionstart

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};

/// Classes of the trigger link, which looks like an outline button.
const TRIGGER_CLASS: &str =
    "ui-button ui-button--outline ui-button--default-size ui-search-dialog-trigger";
/// Visible trigger text without a custom label or children.
const TRIGGER_LABEL: &str = "Search";
/// Shortcut announced on a trigger once the shortcut listener runs. Both modifiers open the dialog.
const KEY_SHORTCUTS: &str = "Control+K Meta+K";
/// Hint the trigger shows before the platform is known.
const DEFAULT_HINT: &str = "Ctrl K";

/// Listens for Ctrl+K and Command+K on the document, like the core controller in lumen-react.
/// Receives the dialog id, reports `["ready", platform]` once installed and `["open", ""]` when the
/// shortcut should open the dialog, and takes `"restore"` (focus what had focus before the
/// shortcut) and `"stop"`. Values travel through the eval channel, never through the script text.
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);";

/// Clicks the first result link of the dialog with the received id, so client routers and the
/// result's own click handler see an ordinary activation.
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();";

/// Attributes the dialog root sets itself; the same names in `attributes` are ignored.
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",
];

/// One search result. [`SearchDialog`] shows a result only when it has a title and an `http:`,
/// `https:`, or relative link, and drops later results that repeat a link.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SearchResult {
    /// Visible title.
    pub title: String,
    /// Link the result opens.
    pub href: String,
    /// Optional second line.
    pub description: Option<String>,
}

impl SearchResult {
    /// A result without a description.
    pub fn new(title: impl Into<String>, href: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            href: href.into(),
            description: None,
        }
    }

    /// Adds a description below the title.
    #[must_use]
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }
}

/// The future a [`SearchDialog`] `search` provider returns: the results for a query, or an error
/// message, which shows the failure status with a retry button.
pub type SearchDialogFuture = Pin<Box<dyn Future<Output = Result<Vec<SearchResult>, String>>>>;

/// What a [`SearchDialog`] shows below its field.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SearchDialogStatus {
    /// No query, or the dialog is closed. The status region is empty.
    #[default]
    Idle,
    /// Waiting for the provider.
    Loading,
    /// At least one result.
    Results,
    /// The provider returned no usable result.
    Empty,
    /// The provider failed; a retry button is shown.
    Error,
}

impl SearchDialogStatus {
    /// The `data-status` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Idle => "idle",
            Self::Loading => "loading",
            Self::Results => "results",
            Self::Empty => "empty",
            Self::Error => "error",
        }
    }
}

/// Text of a [`SearchDialog`]. Unset or blank fields keep the English default.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SearchDialogLabels {
    /// Close button. Default: "Close".
    pub close: Option<String>,
    /// Status with no results. Default: "No results found.".
    pub empty: Option<String>,
    /// Status after the provider fails. Default: "Search could not be loaded.".
    pub failure: Option<String>,
    /// Accessible name of the search field. Default: "Search query".
    pub field: Option<String>,
    /// Status while waiting. Default: "Searching…".
    pub loading: Option<String>,
    /// Status with results; `{count}` becomes the number of results. Default:
    /// "Results found: {count}".
    pub results: Option<String>,
    /// Retry button. Default: "Retry search".
    pub retry: Option<String>,
    /// Dialog title. Default: "Search this site".
    pub title: Option<String>,
}

/// Labels with defaults applied.
#[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"),
        }
    }
}

/// Whitespace that JavaScript's `String.prototype.trim` removes.
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)
}

/// A trimmed label, or `fallback` when it is missing or blank.
fn label_or(value: Option<&str>, fallback: &str) -> String {
    value
        .map(js_trim)
        .filter(|text| !text.is_empty())
        .unwrap_or(fallback)
        .to_string()
}

/// Text of the live status region; `Idle` is empty so nothing is announced.
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(),
    }
}

/// A trimmed result link when it is an `http:`, `https:`, or relative URL without credentials,
/// control characters, or backslashes. `javascript:` and every other scheme return `None`.
fn resolve_search_result_href(value: &str) -> Option<String> {
    resolve_safe_href(js_trim(value))
}

/// Keeps results with a title and a safe link, trims their text, and drops later results whose
/// link is already listed.
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()
}

/// What a key does inside the dialog.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum KeyAction {
    /// Focus the result at this index.
    Focus(usize),
    /// Follow the result at this index.
    Follow(usize),
}

fn has_command_modifier(modifiers: Modifiers) -> bool {
    modifiers.intersects(Modifiers::ALT | Modifiers::CONTROL | Modifiers::META | Modifiers::SHIFT)
}

/// The keyboard model of `resolveLumenSearchDialogKey`. `index` is `None` for the search field, or
/// the focused result. `ArrowDown` and `ArrowUp` move between the field and the results and wrap
/// among results; Enter in the field follows the first result.
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,
    }
}

/// True for Ctrl+K or Command+K without other modifiers, like `isLumenSearchDialogShortcut`.
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")
}

/// Shortcut hint for a platform string, such as `navigator.platform` or a user agent.
fn shortcut_hint(platform: &str) -> &'static str {
    if ["Mac", "iPhone", "iPad", "iPod"]
        .iter()
        .any(|name| platform.contains(name))
    {
        "⌘K"
    } else {
        DEFAULT_HINT
    }
}

/// A primary-button click without modifiers. Modified clicks open the link elsewhere and keep the
/// dialog open.
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 == " ")
}

/// Open state, readiness, and status of a [`SearchDialog`], shared with its
/// [`SearchDialogTrigger`]s.
///
/// Create it with [`use_search_dialog`]. It is `Copy`, so event handlers can capture it.
#[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 {
    /// Whether the dialog is open. Reading it subscribes the component.
    pub fn is_open(&self) -> bool {
        self.dialog.is_open()
    }

    /// Opens the dialog. Focus moves to the search field.
    pub fn open(&self) {
        self.dialog.open();
    }

    /// Closes the dialog.
    pub fn close(&self) {
        self.dialog.close();
    }

    /// What the dialog shows below its field. Reading it subscribes the component.
    pub fn status(&self) -> SearchDialogStatus {
        *self.status.read()
    }

    /// Runs the current query again while the dialog is open, for example after the data behind
    /// the provider changes.
    pub fn refresh(&self) {
        let mut refresh = self.refresh;
        let next = refresh.peek().wrapping_add(1);
        refresh.set(next);
    }
}

/// A closed search dialog controller. Pass it to [`SearchDialogTrigger`]s and to the `dialog`
/// prop of the [`SearchDialog`] they open.
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),
    })
}

/// The running shortcut script and the task that reads its messages.
#[derive(Clone, Copy)]
struct ShortcutListener {
    eval: Eval,
    task: Task,
}

/// Plain state of one mounted [`SearchDialog`]. Borrows of it stay short: no user code, spawn,
/// or focus call runs while it is borrowed.
struct SessionState {
    controller: SearchDialogController,
    search: Callback<String, SearchDialogFuture>,
    id: String,
    query: String,
    /// Bumped by every run, close, and unmount; a response from an older generation is ignored.
    generation: u64,
    request: Option<Task>,
    composing: bool,
    shortcut_opened: bool,
    /// Mounted result links by href, for arrow-key focus.
    links: HashMap<String, Rc<MountedData>>,
    listener: Option<ShortcutListener>,
}

/// Request sequencing, results, and focus targets of one mounted [`SearchDialog`]. `Copy`, so
/// event handlers and tasks can capture it.
#[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)
    }

    /// Like [`Self::update`], for unmounting, when the state may already be gone.
    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());
        }
    }

    /// Ignores the response of the request in flight and cancels its task.
    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();
        }
    }

    /// Runs the current query: idle without a query or while closed, otherwise loading until the
    /// provider answers. A newer run makes the older response stale.
    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 {
            // Links that stay mounted keep their entry; new ones register when they mount.
            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
        });
    }

    /// Called when the dialog closes: the request is dropped and the status cleared. Focus goes
    /// back to what had it before a shortcut opened the dialog.
    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);
    }

    /// Clicks the first result through the page, so its click handler and client routers run.
    /// Dioxus Native has no script support, so Enter does nothing there.
    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 {
            // Escape cancels the composition, not the dialog.
            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);
        }
    }

    /// Following a result closes the dialog, even when a client router cancels the click; a
    /// modified click opens another tab and keeps it open.
    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();
    }

    /// Installs the document shortcut listener. Without script support the send fails and no
    /// listener, hint, or `aria-keyshortcuts` appears.
    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);
    }

    /// Runs when the dialog unmounts. Any handle may already be gone, so nothing here panics.
    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
}

/// Runs the query when the dialog opens or the controller asks for a refresh, ends the session
/// when it closes, marks the controller ready once mounted, and releases everything on unmount.
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());
}

/// Starts the document shortcut listener while `enabled`, and restarts it when the id changes.
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);
        }
    }));
}

/// Attributes of the `<dialog>`, like `resolveLumenSearchDialogAttributes` plus the enhanced
/// `data-ready` and `data-status`.
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
}

/// One result row.
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}" }
                }
            }
        }
    }
}

/// Header and body of the dialog, in lumen-react's order.
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)}
                }
            }
        }
    }
}

/// Props for [`SearchDialog`].
#[derive(Props, Clone, PartialEq)]
pub struct SearchDialogProps {
    /// Dialog id. A [`SearchDialogTrigger`] `target` names it; the title and field ids derive
    /// from it.
    #[props(into)]
    pub id: String,
    /// Returns the results for a query. A newer query, closing the dialog, or unmounting it drops
    /// the pending future, so a stale response never shows.
    pub search: Callback<String, SearchDialogFuture>,
    /// A controller from [`use_search_dialog`], shared with its [`SearchDialogTrigger`]s.
    pub dialog: Option<SearchDialogController>,
    /// Overrides any of the default title, field, status, close, and retry labels.
    #[props(default)]
    pub labels: SearchDialogLabels,
    /// Opens the dialog with Ctrl+K or Command+K outside text fields (web and desktop). Defaults
    /// to true.
    #[props(default = true)]
    pub shortcut: bool,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<dialog>` or global attribute. The search attributes and `id` win over the same
    /// names here.
    #[props(extends = GlobalAttributes, extends = dialog)]
    pub attributes: Vec<Attribute>,
}

/// A modal site search: a field, a live status, a retry button, and result links from an async
/// provider. Arrow keys move between the field and the results, Enter follows the first result,
/// and following a result closes the dialog.
#[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,
    })
}

/// Props for [`SearchDialogTrigger`].
#[derive(Props, Clone, PartialEq)]
pub struct SearchDialogTriggerProps {
    /// The controller of the dialog this link opens.
    pub dialog: SearchDialogController,
    /// The `id` of the [`SearchDialog`] to open.
    #[props(into)]
    pub target: String,
    /// Search page the link opens before the dialog is ready, without script support, or on a
    /// modified click.
    #[props(into)]
    pub fallback_href: String,
    /// Visible text when the trigger has no children. Default: "Search".
    #[props(into)]
    pub label: Option<String>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<a>` or global attribute.
    #[props(extends = GlobalAttributes, extends = a)]
    pub attributes: Vec<Attribute>,
    /// Custom content in place of the label.
    pub children: Element,
}

/// A link to the search page that opens its [`SearchDialog`] once the dialog is mounted. While
/// the shortcut listener runs it shows the platform's shortcut hint and announces
/// `aria-keyshortcuts`.
#[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"]);
    }
}