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
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
//! AI surfaces: `PromptComposer`, `StreamMessage`, `SourceCitation`, `ToolActivity`,
//! `ApprovalCard`, `Reasoning`, `MessageActions`, and `PromptSuggestions`.
//!
//! They show application-owned state; none of them calls a model or performs the requested
//! operation. Each emits a typed request that the application must still authorize.

// cspell:words feff hexdigit onreset

use std::collections::HashMap;

use dioxus::prelude::*;

use crate::class::compose;
use crate::hooks::{use_controllable, use_unique_id};
use crate::{Button, ButtonSize, ButtonVariant, CopyButton, Label};

const VERTICAL_STACK_GROUP: &str = "ui-stack ui-stack--vertical ui-stack--gap-group ui-stack--align-stretch ui-stack--justify-start";
const VERTICAL_STACK_RELATED: &str = "ui-stack ui-stack--vertical ui-stack--gap-related ui-stack--align-stretch ui-stack--justify-start";
const HORIZONTAL_STACK_RELATED: &str = "ui-stack ui-stack--horizontal ui-stack--gap-related ui-stack--align-stretch ui-stack--justify-start ui-stack--wrap";

/// Default most characters a [`PromptComposer`] accepts.
pub const PROMPT_COMPOSER_DEFAULT_LIMIT: u32 = 4000;

/// A usable prompt length limit: 1 to `i32::MAX`, defaulting to 4000 for zero.
pub fn normalize_prompt_composer_limit(limit: Option<u32>) -> u32 {
    match limit {
        None | Some(0) => PROMPT_COMPOSER_DEFAULT_LIMIT,
        Some(limit) => limit.min(2_147_483_647),
    }
}

/// Whether a prompt can be sent: not blank and within `limit` UTF-16 code units, like the
/// browser's `maxlength`.
pub fn can_submit_prompt_composer(text: &str, limit: u32) -> bool {
    !text.trim().is_empty()
        && text.encode_utf16().count()
            <= usize::try_from(normalize_prompt_composer_limit(Some(limit))).unwrap_or(usize::MAX)
}

/// The request a [`PromptComposer`] emits when the user sends a prompt.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PromptComposerSubmitDetail {
    /// The prompt, trimmed.
    pub text: String,
}

/// Props for [`PromptComposer`].
#[derive(Props, Clone, PartialEq)]
pub struct PromptComposerProps {
    /// Controlled prompt text.
    #[props(into)]
    pub value: Option<String>,
    /// Initial text when uncontrolled; also the value a form reset restores.
    #[props(default, into)]
    pub default_value: String,
    /// Called with the text on every edit.
    pub on_value_change: Option<EventHandler<String>>,
    /// Called with the trimmed prompt when the user sends it.
    pub on_prompt_submit: Option<EventHandler<PromptComposerSubmitDetail>>,
    /// Called when the user asks to stop a pending response.
    pub on_stop: Option<EventHandler<()>>,
    /// Disables the input and both buttons.
    #[props(default)]
    pub disabled: bool,
    /// Marks a response in progress: disables sending and shows the stop button.
    #[props(default)]
    pub pending: bool,
    /// Sends on Enter; Shift+Enter still inserts a new line.
    #[props(default)]
    pub submit_on_enter: bool,
    /// Most characters accepted. Defaults to 4000.
    pub max_length: Option<u32>,
    /// Visible label of the input. Defaults to `Message`.
    #[props(default = "Message".to_string(), into)]
    pub label: String,
    /// Send button text. Defaults to `Send`.
    #[props(default = "Send".to_string(), into)]
    pub send_label: String,
    /// Stop button text. Defaults to `Stop`.
    #[props(default = "Stop".to_string(), into)]
    pub stop_label: String,
    /// Form id. The input id becomes `{id}-input`; generated when unset.
    #[props(into)]
    pub id: Option<String>,
    /// Extra controls before the send button, such as an attachment button.
    pub actions: Option<Element>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<form>` or global attribute.
    #[props(extends = GlobalAttributes, extends = form)]
    pub attributes: Vec<Attribute>,
    /// Content after the buttons, such as a hint.
    pub children: Element,
}

/// An accessible prompt input with send and stop requests.
///
/// The form never submits to a server: sending calls `on_prompt_submit` with the trimmed text.
#[component]
pub fn PromptComposer(props: PromptComposerProps) -> Element {
    let generated = use_unique_id();
    let input_id = props
        .id
        .as_ref()
        .map_or(generated, |id| format!("{id}-input"));
    let default_value = props.default_value.clone();
    let draft = use_controllable(
        props.value.clone(),
        || props.default_value.clone(),
        props.on_value_change,
    );
    let text = draft.get();
    let limit = normalize_prompt_composer_limit(props.max_length);
    let (disabled, pending) = (props.disabled, props.pending);
    let send_disabled = disabled || pending || !can_submit_prompt_composer(&text, limit);
    let submit_on_enter = props.submit_on_enter;
    let (on_submit, on_stop) = (props.on_prompt_submit, props.on_stop);
    let class = compose([Some("ui-form ui-prompt-composer"), props.class.as_deref()]);
    let submit = move || {
        let current = draft.peek();

        if disabled || pending || !can_submit_prompt_composer(&current, limit) {
            return;
        }

        if let Some(handler) = on_submit {
            handler.call(PromptComposerSubmitDetail {
                text: current.trim().to_string(),
            });
        }
    };

    rsx! {
        form {
            aria_busy: pending.then_some("true"),
            class,
            "data-disabled": "{disabled}",
            "data-pending": "{pending}",
            "data-status": if pending { "submitting" } else { "idle" },
            "data-submit-on-enter": "{submit_on_enter}",
            "data-ui-prompt-composer": "true",
            id: props.id.clone(),
            method: "post",
            onsubmit: move |event| {
                event.prevent_default();
                submit();
            },
            onreset: move |_| {
                if !draft.is_controlled() {
                    draft.set(default_value.clone());
                }
            },
            ..props.attributes,
            Label { r#for: "{input_id}", "{props.label}" }
            textarea {
                class: "ui-textarea",
                "data-ui-prompt-input": "true",
                disabled,
                id: "{input_id}",
                maxlength: "{limit}",
                name: "prompt",
                required: true,
                rows: "3",
                value: "{text}",
                oninput: move |event| draft.set(event.value()),
                onkeydown: move |event| {
                    let modifiers = event.modifiers();

                    if !submit_on_enter || event.key() != Key::Enter || event.is_composing()
                        || modifiers.shift() || modifiers.alt() || modifiers.ctrl() || modifiers.meta()
                    {
                        return;
                    }

                    event.prevent_default();
                    submit();
                },
            }
            div {
                class: HORIZONTAL_STACK_RELATED,
                "data-direction": "horizontal",
                "data-ui-stack": "true",
                if let Some(actions) = props.actions {
                    {actions}
                }
                Button {
                    "data-ui-prompt-send": "true",
                    disabled: send_disabled,
                    r#type: "submit",
                    // Dioxus Native reports no submit events, so the button sends the prompt itself
                    // and keeps the browser from submitting the form again.
                    onclick: move |event: MouseEvent| {
                        event.prevent_default();
                        submit();
                    },
                    "{props.send_label}"
                }
                Button {
                    "data-ui-prompt-stop": "true",
                    disabled,
                    hidden: !pending,
                    variant: ButtonVariant::Secondary,
                    onclick: move |_| {
                        if pending
                            && !disabled
                            && let Some(handler) = on_stop
                        {
                            handler.call(());
                        }
                    },
                    "{props.stop_label}"
                }
            }
            {props.children}
        }
    }
}

/// Lifecycle of a [`StreamMessage`] or a [`Reasoning`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum StreamMessageStatus {
    /// Not started.
    #[default]
    Idle,
    /// Content is arriving; the content region is marked busy.
    Streaming,
    /// Finished.
    Complete,
    /// Failed.
    Error,
    /// Stopped by the user.
    Canceled,
}

impl StreamMessageStatus {
    /// The `data-status` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Idle => "idle",
            Self::Streaming => "streaming",
            Self::Complete => "complete",
            Self::Error => "error",
            Self::Canceled => "canceled",
        }
    }
}

/// Props for [`StreamMessage`].
#[derive(Props, Clone, PartialEq)]
pub struct StreamMessageProps {
    /// Lifecycle state.
    #[props(default)]
    pub status: StreamMessageStatus,
    /// Concise status announced politely, such as `Writing a reply`.
    #[props(into)]
    pub status_label: String,
    /// Accessible name of the message. Defaults to `Assistant`.
    #[props(default = "Assistant".to_string(), into)]
    pub label: String,
    /// Controls after the status, such as copy or retry.
    pub actions: Option<Element>,
    /// Citations shown after the message, usually [`SourceCitation`]s.
    pub sources: Option<Element>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<article>` or global attribute.
    #[props(extends = GlobalAttributes, extends = article)]
    pub attributes: Vec<Attribute>,
    /// The streamed content. It is not a live region, so tokens are not announced one by one.
    pub children: Element,
}

/// An assistant message that separates streaming content from concise status announcements.
#[component]
pub fn StreamMessage(props: StreamMessageProps) -> Element {
    let class = compose([
        Some("ui-message ui-message--assistant ui-stream-message"),
        props.class.as_deref(),
    ]);
    let streaming = props.status == StreamMessageStatus::Streaming;

    rsx! {
        article {
            aria_label: "{props.label}",
            class,
            "data-from": "assistant",
            "data-status": props.status.as_str(),
            ..props.attributes,
            div {
                aria_busy: if streaming { "true" } else { "false" },
                aria_live: "off",
                class: "ui-prose",
                "data-slot": "prose",
                "data-ui-stream-content": "true",
                {props.children}
            }
            div {
                class: HORIZONTAL_STACK_RELATED,
                "data-direction": "horizontal",
                "data-ui-stack": "true",
                span { aria_live: "polite", role: "status", "{props.status_label}" }
                if let Some(actions) = props.actions {
                    {actions}
                }
            }
            if let Some(sources) = props.sources {
                {sources}
            }
        }
    }
}

fn is_unsafe_url_character(character: char) -> bool {
    u32::from(character) <= 32 || character == '\u{7f}' || character == '\\'
}

fn is_forbidden_host_character(byte: u8) -> bool {
    !byte.is_ascii_graphic()
        || matches!(
            byte,
            b'#' | b'%'
                | b'/'
                | b':'
                | b'<'
                | b'>'
                | b'?'
                | b'@'
                | b'['
                | b'\\'
                | b']'
                | b'^'
                | b'|'
        )
}

const HEX_DIGITS: &[u8; 16] = b"0123456789ABCDEF";

fn percent_encode(out: &mut String, text: &str, extra: &[u8]) {
    for character in text.chars() {
        if character.is_ascii() && !extra.contains(&(character as u8)) {
            out.push(character);
        } else {
            let mut buffer = [0; 4];

            for byte in character.encode_utf8(&mut buffer).bytes() {
                out.push('%');
                out.push(char::from(HEX_DIGITS[usize::from(byte >> 4)]));
                out.push(char::from(HEX_DIGITS[usize::from(byte & 0x0f)]));
            }
        }
    }
}

fn is_dot_segment(segment: &str, double: bool) -> bool {
    let lower = segment.to_ascii_lowercase();

    if double {
        matches!(lower.as_str(), ".." | ".%2e" | "%2e." | "%2e%2e")
    } else {
        matches!(lower.as_str(), "." | "%2e")
    }
}

/// Resolves `rest` (`/path?query#fragment`) the way the URL parser serializes it.
fn serialize_path(rest: &str) -> String {
    let (before_fragment, fragment) = match rest.split_once('#') {
        Some((head, fragment)) => (head, Some(fragment)),
        None => (rest, None),
    };
    let (path, query) = match before_fragment.split_once('?') {
        Some((path, query)) => (path, Some(query)),
        None => (before_fragment, None),
    };
    let mut segments: Vec<&str> = Vec::new();
    let raw: Vec<&str> = path.split('/').skip(1).collect();

    for (index, segment) in raw.iter().enumerate() {
        let last = index + 1 == raw.len();

        if is_dot_segment(segment, true) {
            segments.pop();

            if last {
                segments.push("");
            }
        } else if is_dot_segment(segment, false) {
            if last {
                segments.push("");
            }
        } else {
            segments.push(segment);
        }
    }

    let mut out = String::new();

    if segments.is_empty() {
        out.push('/');
    }

    for segment in segments {
        out.push('/');
        percent_encode(&mut out, segment, b"\"<>`{}");
    }

    if let Some(query) = query {
        out.push('?');
        percent_encode(&mut out, query, b"\"<>'");
    }

    if let Some(fragment) = fragment {
        out.push('#');
        percent_encode(&mut out, fragment, b"\"<>`");
    }

    out
}

fn web_citation_href(value: &str) -> Option<String> {
    let (scheme, rest) = value.split_once(':')?;
    let scheme = scheme.to_ascii_lowercase();
    let default_port = match scheme.as_str() {
        "http" => "80",
        "https" => "443",
        _ => return None,
    };
    let rest = rest.trim_start_matches('/');
    let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    let (authority, path) = rest.split_at(authority_end);

    if authority.contains('@') {
        return None;
    }

    let (host, port) = if let Some(inner) = authority.strip_prefix('[') {
        let (address, after) = inner.split_once(']')?;

        if address.is_empty()
            || !address
                .bytes()
                .all(|byte| byte.is_ascii_hexdigit() || byte == b':' || byte == b'.')
        {
            return None;
        }

        (
            format!("[{}]", address.to_ascii_lowercase()),
            after.strip_prefix(':'),
        )
    } else {
        let (host, port) = match authority.split_once(':') {
            Some((host, port)) => (host, Some(port)),
            None => (authority, None),
        };

        if host.is_empty() || host.bytes().any(is_forbidden_host_character) {
            return None;
        }

        (host.to_ascii_lowercase(), port)
    };

    let port = match port {
        None | Some("") => None,
        Some(port) if port.len() <= 5 && port.bytes().all(|byte| byte.is_ascii_digit()) => {
            let number: u32 = port.parse().ok()?;

            if number > 65_535 {
                return None;
            }

            let number = number.to_string();
            (number != default_port).then_some(number)
        }
        Some(_) => return None,
    };

    let mut href = format!("{scheme}://{host}");

    if let Some(port) = port {
        href.push(':');
        href.push_str(&port);
    }

    let path = if path.starts_with('/') {
        path.to_string()
    } else {
        format!("/{path}")
    };
    href.push_str(&serialize_path(&path));

    Some(href)
}

/// A safe citation destination: an `http` or `https` URL without credentials (serialized the way
/// the browser URL parser does for common inputs), or a local absolute path such as `/docs`.
/// Executable schemes, protocol-relative URLs, and URLs with control characters, spaces, or
/// backslashes return `None`.
pub fn resolve_source_citation_href(value: &str) -> Option<String> {
    if value.chars().any(is_unsafe_url_character) {
        return None;
    }

    if value.starts_with('/') && !value.starts_with("//") {
        return Some(value.to_string());
    }

    web_citation_href(value)
}

/// Props for [`SourceCitation`].
#[derive(Props, Clone, PartialEq)]
pub struct SourceCitationProps {
    /// Destination. Unsafe values render the citation as plain text.
    #[props(into)]
    pub href: String,
    /// Visible name of the source.
    #[props(into)]
    pub label: 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>,
    /// Text after the label, such as a page number.
    pub children: Element,
}

/// A named source link restricted to safe web URLs and local paths.
#[component]
pub fn SourceCitation(props: SourceCitationProps) -> Element {
    let href = resolve_source_citation_href(&props.href);

    if let Some(href) = href {
        let class = compose([Some("ui-link ui-source-citation"), props.class.as_deref()]);

        return rsx! {
            a {
                class,
                "data-slot": "link",
                "data-variant": "default",
                href,
                rel: "noopener noreferrer",
                ..props.attributes,
                "{props.label}"
                {props.children}
            }
        };
    }

    let class = compose([Some("ui-source-citation"), props.class.as_deref()]);

    rsx! {
        span { class, "{props.label}" {props.children} }
    }
}

/// Lifecycle of a [`ToolActivity`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ToolActivityStatus {
    /// Waiting to run.
    #[default]
    Queued,
    /// In progress.
    Running,
    /// Finished successfully.
    Success,
    /// Failed.
    Error,
    /// Stopped.
    Canceled,
}

impl ToolActivityStatus {
    /// The `data-status` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Queued => "queued",
            Self::Running => "running",
            Self::Success => "success",
            Self::Error => "error",
            Self::Canceled => "canceled",
        }
    }
}

/// Props for [`ToolActivity`].
#[derive(Props, Clone, PartialEq)]
pub struct ToolActivityProps {
    /// Summary text naming the tool call.
    #[props(into)]
    pub label: String,
    /// Lifecycle state.
    #[props(default)]
    pub status: ToolActivityStatus,
    /// Concise status, exposed as a status region.
    #[props(into)]
    pub status_label: String,
    /// Controlled disclosure state.
    pub open: Option<bool>,
    /// Initial disclosure state when uncontrolled.
    #[props(default)]
    pub default_open: bool,
    /// Called with the new disclosure state.
    pub on_open_change: Option<EventHandler<bool>>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<details>` or global attribute.
    #[props(extends = GlobalAttributes, extends = details)]
    pub attributes: Vec<Attribute>,
    /// Tool input, progress, or results.
    pub children: Element,
}

/// A disclosure of application-owned tool progress and results.
#[component]
pub fn ToolActivity(props: ToolActivityProps) -> Element {
    let open = use_controllable(props.open, || props.default_open, props.on_open_change);
    let class = compose([
        Some("ui-collapsible ui-tool-activity"),
        props.class.as_deref(),
    ]);

    rsx! {
        details {
            class,
            "data-status": props.status.as_str(),
            "data-ui-collapsible": "true",
            open: open.get(),
            ..props.attributes,
            summary {
                onclick: move |event| {
                    event.prevent_default();
                    open.set(!open.peek());
                },
                "{props.label}"
            }
            div {
                class: VERTICAL_STACK_RELATED,
                "data-direction": "vertical",
                "data-ui-stack": "true",
                span { role: "status", "{props.status_label}" }
                {props.children}
            }
        }
    }
}

/// State of an [`ApprovalCard`] request.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ApprovalCardStatus {
    /// Waiting for a decision; the buttons are enabled.
    #[default]
    Pending,
    /// Approved.
    Approved,
    /// Rejected.
    Rejected,
}

impl ApprovalCardStatus {
    /// The `data-status` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Pending => "pending",
            Self::Approved => "approved",
            Self::Rejected => "rejected",
        }
    }
}

/// The decision an [`ApprovalCard`] requests.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ApprovalCardResponse {
    /// Approve the request.
    Approve,
    /// Reject the request.
    Reject,
}

impl ApprovalCardResponse {
    /// The `data-ui-approval-response` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Approve => "approve",
            Self::Reject => "reject",
        }
    }
}

/// The request an [`ApprovalCard`] emits. The application must still authorize the operation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ApprovalCardResponseDetail {
    /// The pending request id.
    pub request_id: String,
    /// The decision.
    pub response: ApprovalCardResponse,
}

/// Props for [`ApprovalCard`].
#[derive(Props, Clone, PartialEq)]
pub struct ApprovalCardProps {
    /// Heading and accessible name, such as `Delete 3 files`.
    #[props(into)]
    pub label: String,
    /// Application-owned id of the pending request.
    #[props(into)]
    pub request_id: String,
    /// Request state; only pending requests accept a decision.
    #[props(default)]
    pub status: ApprovalCardStatus,
    /// Concise status, exposed as a status region.
    #[props(into)]
    pub status_label: String,
    /// Disables both buttons.
    #[props(default)]
    pub disabled: bool,
    /// Approve button text. Defaults to `Approve`.
    #[props(default = "Approve".to_string(), into)]
    pub approve_label: String,
    /// Reject button text. Defaults to `Reject`.
    #[props(default = "Reject".to_string(), into)]
    pub reject_label: String,
    /// Called with the decision.
    pub on_response: Option<EventHandler<ApprovalCardResponseDetail>>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Details of the request.
    pub children: Element,
}

/// Collects an explicit decision for an application-owned pending request.
#[component]
pub fn ApprovalCard(props: ApprovalCardProps) -> Element {
    // The markup of a comfortable default `Card`, written out so the root can spread attributes.
    let class = compose([
        Some("ui-card ui-card--comfortable ui-approval-card"),
        props.class.as_deref(),
    ]);
    let locked = props.disabled || props.status != ApprovalCardStatus::Pending;
    let buttons_disabled = locked || props.request_id.is_empty();
    let respond = {
        let request_id = props.request_id.clone();
        let on_response = props.on_response;

        move |response: ApprovalCardResponse| {
            if buttons_disabled {
                return;
            }

            if let Some(handler) = on_response {
                handler.call(ApprovalCardResponseDetail {
                    request_id: request_id.clone(),
                    response,
                });
            }
        }
    };
    let approve = respond.clone();

    rsx! {
        div {
            aria_label: "{props.label}",
            class,
            "data-density": "comfortable",
            "data-disabled": "{props.disabled}",
            "data-request-id": "{props.request_id}",
            "data-slot": "card",
            "data-status": props.status.as_str(),
            "data-ui-approval-card": "true",
            "data-variant": "default",
            ..props.attributes,
            div {
                class: VERTICAL_STACK_GROUP,
                "data-direction": "vertical",
                "data-ui-stack": "true",
                strong { "{props.label}" }
                {props.children}
                span { role: "status", "{props.status_label}" }
                div {
                    class: HORIZONTAL_STACK_RELATED,
                    "data-direction": "horizontal",
                    "data-ui-stack": "true",
                    Button {
                        "data-ui-approval-response": "approve",
                        disabled: locked,
                        onclick: move |_| approve(ApprovalCardResponse::Approve),
                        "{props.approve_label}"
                    }
                    Button {
                        "data-ui-approval-response": "reject",
                        disabled: locked,
                        variant: ButtonVariant::Secondary,
                        onclick: move |_| respond(ApprovalCardResponse::Reject),
                        "{props.reject_label}"
                    }
                }
            }
        }
    }
}

/// The inputs of [`resolve_reasoning_open`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ReasoningOpenOptions {
    /// The status before the change.
    pub previous: StreamMessageStatus,
    /// The new status.
    pub next: StreamMessageStatus,
    /// Whether the disclosure is open now.
    pub open: bool,
    /// The person opened or closed the disclosure themselves; their choice always wins.
    pub user_toggled: bool,
    /// Close once when streaming ends.
    pub collapse_on_complete: bool,
}

/// Whether a [`Reasoning`] disclosure is open after its status changes, like
/// `resolveLumenReasoningOpen` in `@santi020k/lumen-core`.
///
/// It opens when streaming starts and closes once when streaming ends (unless
/// `collapse_on_complete` is off). Once the person has opened or closed it, their choice wins.
pub fn resolve_reasoning_open(options: ReasoningOpenOptions) -> bool {
    let ReasoningOpenOptions {
        previous,
        next,
        open,
        user_toggled,
        collapse_on_complete,
    } = options;

    if user_toggled || previous == next {
        return open;
    }

    if next == StreamMessageStatus::Streaming {
        return true;
    }

    if previous == StreamMessageStatus::Streaming && collapse_on_complete {
        return false;
    }

    open
}

/// Disclosure state of a [`Reasoning`]: whether it is open, the status it last followed, and
/// whether the person toggled it.
#[derive(Clone, Copy, PartialEq, Eq)]
struct ReasoningState {
    open: bool,
    status: StreamMessageStatus,
    user_toggled: bool,
}

/// Props for [`Reasoning`].
#[derive(Props, Clone, PartialEq)]
pub struct ReasoningProps {
    /// Summary text, such as `Thinking…` or `Thought for 12 seconds`. Localize it in the app.
    #[props(into)]
    pub label: String,
    /// Lifecycle of the reasoning. Defaults to `Complete`; it opens while `Streaming`.
    #[props(default = StreamMessageStatus::Complete)]
    pub status: StreamMessageStatus,
    /// Closes once when streaming ends, unless the person already opened or closed it. Defaults
    /// to `true`.
    #[props(default = true)]
    pub collapse_on_complete: bool,
    /// Initial disclosure state. Leave it unset to start open only while streaming.
    pub default_open: Option<bool>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<details>` or global attribute.
    #[props(extends = GlobalAttributes, extends = details)]
    pub attributes: Vec<Attribute>,
    /// The reasoning. It is not a live region, so streamed tokens are not announced one by one.
    pub children: Element,
}

/// A collapsible view of a model's reasoning.
///
/// It opens while `status` is `Streaming` and closes once when streaming ends; once the person
/// opens or closes it, their choice wins. The summary toggles the disclosure in Rust on every
/// renderer instead of relying on the browser's native `<details>` behavior.
#[component]
pub fn Reasoning(props: ReasoningProps) -> Element {
    let status = props.status;
    let mut state = use_signal(|| ReasoningState {
        open: props
            .default_open
            .unwrap_or(status == StreamMessageStatus::Streaming),
        status,
        user_toggled: false,
    });
    let current = *state.peek();

    // A status change opens or closes the disclosure once, during render like lumen-react.
    if current.status != status {
        state.set(ReasoningState {
            open: resolve_reasoning_open(ReasoningOpenOptions {
                previous: current.status,
                next: status,
                open: current.open,
                user_toggled: current.user_toggled,
                collapse_on_complete: props.collapse_on_complete,
            }),
            status,
            user_toggled: current.user_toggled,
        });
    }

    let open = state.read().open;
    let class = compose([Some("ui-reasoning"), props.class.as_deref()]);
    let streaming = status == StreamMessageStatus::Streaming;

    rsx! {
        details {
            class,
            "data-collapse-on-complete": "{props.collapse_on_complete}",
            "data-status": status.as_str(),
            "data-ui-reasoning": "true",
            open,
            ..props.attributes,
            summary {
                onclick: move |event| {
                    event.prevent_default();
                    let current = *state.peek();
                    state.set(ReasoningState {
                        open: !current.open,
                        user_toggled: true,
                        ..current
                    });
                },
                span { class: "ui-reasoning__label", "{props.label}" }
            }
            div {
                aria_busy: if streaming { "true" } else { "false" },
                aria_live: "off",
                class: "ui-reasoning__content",
                "data-ui-reasoning-content": "true",
                {props.children}
            }
        }
    }
}

/// A rating recorded by [`MessageActions`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MessageFeedback {
    /// A good response.
    Positive,
    /// A bad response.
    Negative,
}

impl MessageFeedback {
    /// The `data-feedback` and `data-ui-message-action` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Positive => "positive",
            Self::Negative => "negative",
        }
    }
}

/// The rating after the person presses `pressed`, like `nextLumenMessageFeedback` in
/// `@santi020k/lumen-core`: pressing the current rating clears it, and pressing the other one
/// replaces it.
pub fn next_message_feedback(
    current: Option<MessageFeedback>,
    pressed: MessageFeedback,
) -> Option<MessageFeedback> {
    if current == Some(pressed) {
        None
    } else {
        Some(pressed)
    }
}

/// The request a [`MessageActions`] emits when the person rates a message.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MessageFeedbackDetail {
    /// The rated message.
    pub message_id: String,
    /// The new rating; `None` when the person cleared their earlier choice.
    pub value: Option<MessageFeedback>,
}

/// The request a [`MessageActions`] emits when the person asks for a new response. The
/// application owns regeneration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MessageRetryDetail {
    /// The message to regenerate.
    pub message_id: String,
}

/// Props for [`MessageActions`].
#[derive(Props, Clone, PartialEq)]
pub struct MessageActionsProps {
    /// Identifies the message in retry and feedback requests. Retry and rating stay disabled
    /// while it is empty.
    #[props(into)]
    pub message_id: String,
    /// Accessible name of the group. Defaults to `Message actions`.
    #[props(default = "Message actions".to_string(), into)]
    pub label: String,
    /// Text the copy button writes to the clipboard. Omit it to leave copy out.
    #[props(into)]
    pub copy_value: Option<String>,
    /// Copies through the app instead of the browser clipboard (see `CopyButton::on_copy`). Use it
    /// on Dioxus Native, which has no clipboard API.
    pub on_copy: Option<Callback<String, bool>>,
    /// Accessible name of the copy button. Defaults to `Copy`.
    #[props(default = "Copy".to_string(), into)]
    pub copy_label: String,
    /// Accessible name of the copy button after a copy. Defaults to `Copied`.
    #[props(default = "Copied".to_string(), into)]
    pub copied_label: String,
    /// Accessible name of the copy button after a failure. Defaults to `Could not copy`.
    #[props(default = "Could not copy".to_string(), into)]
    pub copy_error_label: String,
    /// Shows a retry button that requests a new response.
    #[props(default)]
    pub retry: bool,
    /// Accessible name of the retry button. Defaults to `Retry`.
    #[props(default = "Retry".to_string(), into)]
    pub retry_label: String,
    /// Shows the good and bad response pair. Defaults to `true`.
    #[props(default = true)]
    pub show_feedback: bool,
    /// Controlled rating: `Some(rating)`, where `rating` is `None` when unrated. Omit it to let
    /// the component keep the rating, starting from `default_feedback`.
    pub feedback: Option<Option<MessageFeedback>>,
    /// Initial rating when `feedback` is not controlled.
    pub default_feedback: Option<MessageFeedback>,
    /// Accessible name of the good response button. Defaults to `Good response`.
    #[props(default = "Good response".to_string(), into)]
    pub positive_label: String,
    /// Accessible name of the bad response button. Defaults to `Bad response`.
    #[props(default = "Bad response".to_string(), into)]
    pub negative_label: String,
    /// Turns off retry and rating, for example while the answer streams. Copy stays available.
    #[props(default)]
    pub disabled: bool,
    /// Called when the person asks for a new response.
    pub on_retry: Option<EventHandler<MessageRetryDetail>>,
    /// Called with the new rating; its `value` is `None` when the person cleared their choice.
    pub on_feedback: Option<EventHandler<MessageFeedbackDetail>>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Extra actions after the built-in buttons.
    pub children: Element,
}

/// Copy, retry, and rating actions under an assistant message.
///
/// Retry only requests a new response and rating only records a choice; the application owns
/// regeneration, storage, and any follow-up question. Pressing the current rating clears it.
/// Lumen's stylesheet hides the button text and draws icons; the text stays as each button's
/// accessible name.
#[component]
pub fn MessageActions(props: MessageActionsProps) -> Element {
    let rating = use_controllable(props.feedback, || props.default_feedback, None);
    let current = rating.get();
    let inactive = props.disabled || props.message_id.is_empty();
    let class = compose([Some("ui-message-actions"), props.class.as_deref()]);
    let pressed_state = |feedback: MessageFeedback| {
        if current == Some(feedback) {
            "true"
        } else {
            "false"
        }
    };
    let request_retry = {
        let message_id = props.message_id.clone();
        let on_retry = props.on_retry;

        move |_: MouseEvent| {
            if !inactive && let Some(handler) = on_retry {
                handler.call(MessageRetryDetail {
                    message_id: message_id.clone(),
                });
            }
        }
    };
    let rate = {
        let message_id = props.message_id.clone();
        let on_feedback = props.on_feedback;

        move |pressed: MessageFeedback| {
            if inactive {
                return;
            }

            let value = next_message_feedback(rating.peek(), pressed);
            rating.set(value);

            if let Some(handler) = on_feedback {
                handler.call(MessageFeedbackDetail {
                    message_id: message_id.clone(),
                    value,
                });
            }
        }
    };
    let rate_positive = rate.clone();

    rsx! {
        div {
            aria_label: "{props.label}",
            class,
            "data-disabled": "{props.disabled}",
            "data-feedback": current.map_or("", MessageFeedback::as_str),
            "data-message-id": "{props.message_id}",
            "data-ui-message-actions": "true",
            role: "group",
            ..props.attributes,
            if let Some(value) = props.copy_value {
                CopyButton {
                    copied_label: props.copied_label,
                    error_label: props.copy_error_label,
                    label: props.copy_label.clone(),
                    on_copy: props.on_copy,
                    size: ButtonSize::Icon,
                    value,
                    variant: ButtonVariant::Ghost,
                    "{props.copy_label}"
                }
            }
            if props.retry {
                Button {
                    "data-ui-message-action": "retry",
                    disabled: inactive,
                    size: ButtonSize::Icon,
                    variant: ButtonVariant::Ghost,
                    onclick: request_retry,
                    "{props.retry_label}"
                }
            }
            if props.show_feedback {
                Button {
                    aria_pressed: pressed_state(MessageFeedback::Positive),
                    "data-ui-message-action": MessageFeedback::Positive.as_str(),
                    disabled: inactive,
                    size: ButtonSize::Icon,
                    variant: ButtonVariant::Ghost,
                    onclick: move |_| rate_positive(MessageFeedback::Positive),
                    "{props.positive_label}"
                }
                Button {
                    aria_pressed: pressed_state(MessageFeedback::Negative),
                    "data-ui-message-action": MessageFeedback::Negative.as_str(),
                    disabled: inactive,
                    size: ButtonSize::Icon,
                    variant: ButtonVariant::Ghost,
                    onclick: move |_| rate(MessageFeedback::Negative),
                    "{props.negative_label}"
                }
            }
            {props.children}
        }
    }
}

/// A starter prompt offered by [`PromptSuggestions`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PromptSuggestion {
    /// Visible button text.
    pub label: String,
    /// The prompt it sends. Defaults to the label when unset or blank.
    pub value: Option<String>,
}

impl PromptSuggestion {
    /// A suggestion whose prompt is its label.
    pub fn new(label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            value: None,
        }
    }

    /// Sets the prompt when it differs from the label.
    #[must_use]
    pub fn with_value(mut self, value: impl Into<String>) -> Self {
        self.value = Some(value.into());
        self
    }
}

/// A suggestion ready to render: a visible label and the prompt it sends.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedPromptSuggestion {
    /// Visible button text, trimmed.
    pub label: String,
    /// The prompt, trimmed; the label when the suggestion has no prompt of its own.
    pub value: String,
}

/// The request a [`PromptSuggestions`] emits when the person chooses a suggestion.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PromptSuggestionDetail {
    /// The chosen prompt.
    pub value: String,
}

/// JavaScript white space and line terminators: the characters `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)
}

/// Keeps suggestions with a visible label, trims both fields, and falls back to the label as the
/// prompt, like `normalizeLumenPromptSuggestions` in `@santi020k/lumen-core`.
pub fn normalize_prompt_suggestions(
    suggestions: &[PromptSuggestion],
) -> Vec<ResolvedPromptSuggestion> {
    suggestions
        .iter()
        .filter_map(|suggestion| {
            let label = suggestion.label.trim_matches(is_js_whitespace);

            if label.is_empty() {
                return None;
            }

            let value = suggestion
                .value
                .as_deref()
                .map(|value| value.trim_matches(is_js_whitespace))
                .filter(|value| !value.is_empty())
                .unwrap_or(label);

            Some(ResolvedPromptSuggestion {
                label: label.to_string(),
                value: value.to_string(),
            })
        })
        .collect()
}

/// Distinct, order-stable keys for repeated suggestions that do not rely on the list index.
fn prompt_suggestion_keys(items: &[ResolvedPromptSuggestion]) -> Vec<String> {
    let mut seen: HashMap<(&str, &str), usize> = HashMap::new();

    items
        .iter()
        .map(|item| {
            let count = seen
                .entry((item.label.as_str(), item.value.as_str()))
                .or_insert(0);
            let key = format!("{:?}:{:?}#{count}", item.label, item.value);
            *count += 1;
            key
        })
        .collect()
}

/// Fills a prompt composer in the browser, like `fillLumenPromptComposer` in
/// `@santi020k/lumen-core`: the textarea gets the value through the native setter and an `input`
/// event, so a `PromptComposer` (Dioxus or any framework) sees the change. With `submit`, the
/// form is submitted once its send button is enabled, waiting up to a second for the composer to
/// render the new text. Values travel through the eval channel, never through the script text.
const FILL_PROMPT_COMPOSER: &str = r"const [id, value, submit] = await dioxus.recv();
const target = document.getElementById(id);
if (!target) return false;
const input = target instanceof HTMLTextAreaElement
  ? target
  : target.querySelector('textarea[data-ui-prompt-input]') ?? target.querySelector('textarea');
if (!(input instanceof HTMLTextAreaElement) || input.disabled || input.readOnly) return false;
const setValue = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')?.set;
if (setValue) setValue.call(input, value); else input.value = value;
input.dispatchEvent(new Event('input', { bubbles: true }));
input.focus();
input.setSelectionRange(value.length, value.length);
const form = input.form;
const send = form?.querySelector('button[data-ui-prompt-send]');
if (!submit || !form || !(send instanceof HTMLButtonElement)) return true;
const request = () => {
  if (send.isConnected && !send.disabled) form.requestSubmit(send);
};
if (!send.disabled) {
  request();
  return true;
}
const observer = new MutationObserver(() => {
  if (send.disabled) return;
  observer.disconnect();
  clearTimeout(timer);
  request();
});
const timer = setTimeout(() => observer.disconnect(), 1000);
observer.observe(send, { attributeFilter: ['disabled'], attributes: true });
return true;";

/// Fills the composer with id `target` on web and desktop. Dioxus Native has no JavaScript, so
/// the request fails quietly there and the app sets the composer value from
/// `on_suggestion_select` instead.
fn fill_prompt_composer(target: String, value: String, submit: bool) {
    let eval = document::eval(FILL_PROMPT_COMPOSER);
    let _ = eval.send((target, value, submit));
}

/// Props for [`PromptSuggestions`].
#[derive(Props, Clone, PartialEq)]
pub struct PromptSuggestionsProps {
    /// The starter prompts. Suggestions with a blank label are skipped.
    pub suggestions: Vec<PromptSuggestion>,
    /// Accessible name of the group. Defaults to `Suggested prompts`.
    #[props(default = "Suggested prompts".to_string(), into)]
    pub label: String,
    /// The id of a [`PromptComposer`] form or textarea. On web and desktop, choosing a suggestion
    /// fills it.
    #[props(into)]
    pub target: Option<String>,
    /// Submits the target composer after filling it.
    #[props(default)]
    pub submit_on_select: bool,
    /// Disables every suggestion.
    #[props(default)]
    pub disabled: bool,
    /// Called with the chosen prompt before the target composer is filled. On Dioxus Native, set
    /// a controlled composer's value here.
    pub on_suggestion_select: Option<EventHandler<PromptSuggestionDetail>>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Extra content after the suggestions.
    pub children: Element,
}

/// Starter prompts that fill a [`PromptComposer`].
///
/// Choosing a suggestion calls `on_suggestion_select`, then, on web and desktop, fills the
/// composer named by `target` and optionally submits it. It renders nothing when there are no
/// suggestions and no children.
#[component]
pub fn PromptSuggestions(props: PromptSuggestionsProps) -> Element {
    let items = normalize_prompt_suggestions(&props.suggestions);

    if items.is_empty() && !super::has_content(&props.children) {
        return rsx! {};
    }

    let keys = prompt_suggestion_keys(&items);
    let class = compose([Some("ui-prompt-suggestions"), props.class.as_deref()]);
    let (disabled, submit) = (props.disabled, props.submit_on_select);
    let on_select = props.on_suggestion_select;
    let target = props.target.clone().filter(|target| !target.is_empty());

    rsx! {
        div {
            aria_label: "{props.label}",
            class,
            "data-disabled": "{disabled}",
            "data-submit-on-select": "{submit}",
            "data-target": props.target,
            "data-ui-prompt-suggestions": "true",
            role: "group",
            ..props.attributes,
            for (item, key) in items.into_iter().zip(keys) {
                Button {
                    key: "{key}",
                    "data-ui-prompt-suggestion": "true",
                    "data-value": item.value.clone(),
                    disabled,
                    size: ButtonSize::Sm,
                    variant: ButtonVariant::Outline,
                    onclick: {
                        let (value, target) = (item.value.clone(), target.clone());

                        move |_| {
                            if disabled {
                                return;
                            }

                            if let Some(handler) = on_select {
                                handler.call(PromptSuggestionDetail { value: value.clone() });
                            }

                            if let Some(target) = target.clone() {
                                fill_prompt_composer(target, value.clone(), submit);
                            }
                        }
                    },
                    "{item.label}"
                }
            }
            {props.children}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        MessageFeedback, PromptSuggestion, ReasoningOpenOptions, ResolvedPromptSuggestion,
        StreamMessageStatus, can_submit_prompt_composer, next_message_feedback,
        normalize_prompt_composer_limit, normalize_prompt_suggestions, prompt_suggestion_keys,
        resolve_reasoning_open, resolve_source_citation_href,
    };

    #[test]
    fn prompt_limits_follow_lumen_core() {
        assert_eq!(normalize_prompt_composer_limit(None), 4000);
        assert_eq!(normalize_prompt_composer_limit(Some(0)), 4000);
        assert_eq!(
            normalize_prompt_composer_limit(Some(u32::MAX)),
            2_147_483_647
        );
        assert!(can_submit_prompt_composer(" hi ", 4000));
        assert!(!can_submit_prompt_composer("   ", 4000));
        assert!(!can_submit_prompt_composer("hello", 4));
        // Limits count UTF-16 code units like the browser.
        assert!(!can_submit_prompt_composer("😀😀", 3));
    }

    #[test]
    fn citations_accept_only_safe_destinations() {
        let cases = [
            (
                "https://example.com/report",
                Some("https://example.com/report"),
            ),
            ("HTTPS://Example.COM", Some("https://example.com/")),
            (
                "http://example.com:80/a?b=c#d",
                Some("http://example.com/a?b=c#d"),
            ),
            (
                "https://example.com:8443/x/../y/./z",
                Some("https://example.com:8443/y/z"),
            ),
            (
                "https://example.com/a\"b<c>",
                Some("https://example.com/a%22b%3Cc%3E"),
            ),
            (
                "https://example.com/café",
                Some("https://example.com/caf%C3%A9"),
            ),
            ("https:example.com", Some("https://example.com/")),
            ("/docs/guide", Some("/docs/guide")),
            ("//evil.example", None),
            ("javascript:alert(1)", None),
            ("https://user:pass@example.com", None),
            ("https://example.com/a b", None),
            ("https://exa\\mple.com", None),
            ("https://example.com:99999", None),
            ("https://", None),
            ("data:text/html,hi", None),
            ("", None),
        ];

        for (input, expected) in cases {
            assert_eq!(
                resolve_source_citation_href(input).as_deref(),
                expected,
                "{input}"
            );
        }
    }

    #[test]
    fn citation_resolution_is_linear_for_long_input() {
        let long = format!("https://example.com/{}", "a/".repeat(100_000));
        assert!(resolve_source_citation_href(&long).is_some());
        assert!(resolve_source_citation_href(&"/".repeat(200_000)).is_none());
    }

    #[test]
    fn reasoning_open_state_follows_lumen_core() {
        use StreamMessageStatus::{Complete, Error, Idle, Streaming};

        // (previous, next, open, user toggled, collapse on complete) => open
        let cases = [
            ((Idle, Streaming, false, false, true), true),
            ((Streaming, Complete, true, false, true), false),
            ((Streaming, Error, true, false, true), false),
            ((Streaming, Complete, true, false, false), true),
            ((Streaming, Complete, true, true, true), true),
            ((Idle, Streaming, false, true, true), false),
            ((Complete, Complete, true, false, true), true),
            ((Idle, Complete, false, false, true), false),
        ];

        for ((previous, next, open, user_toggled, collapse_on_complete), expected) in cases {
            let options = ReasoningOpenOptions {
                previous,
                next,
                open,
                user_toggled,
                collapse_on_complete,
            };

            assert_eq!(resolve_reasoning_open(options), expected, "{options:?}");
        }
    }

    #[test]
    fn message_feedback_toggles_and_clears() {
        use MessageFeedback::{Negative, Positive};

        assert_eq!(next_message_feedback(None, Positive), Some(Positive));
        assert_eq!(next_message_feedback(Some(Positive), Positive), None);
        assert_eq!(
            next_message_feedback(Some(Positive), Negative),
            Some(Negative)
        );
        assert_eq!(next_message_feedback(Some(Negative), Negative), None);
        assert_eq!(Positive.as_str(), "positive");
        assert_eq!(Negative.as_str(), "negative");
    }

    fn resolved(label: &str, value: &str) -> ResolvedPromptSuggestion {
        ResolvedPromptSuggestion {
            label: label.to_string(),
            value: value.to_string(),
        }
    }

    #[test]
    fn prompt_suggestions_keep_labeled_items_and_fall_back_to_the_label() {
        let suggestions = [
            PromptSuggestion::new(" Summarize ").with_value(" Summarize this thread "),
            PromptSuggestion::new("Plan a trip"),
            PromptSuggestion::new("Blank value").with_value("  "),
            PromptSuggestion::new("   "),
            PromptSuggestion::new("").with_value("No label"),
            // JavaScript's trim removes U+FEFF; Rust's does not.
            PromptSuggestion::new("\u{feff}Draft\u{3000}"),
        ];

        assert_eq!(
            normalize_prompt_suggestions(&suggestions),
            vec![
                resolved("Summarize", "Summarize this thread"),
                resolved("Plan a trip", "Plan a trip"),
                resolved("Blank value", "Blank value"),
                resolved("Draft", "Draft"),
            ]
        );
        assert_eq!(normalize_prompt_suggestions(&[]), []);
    }

    #[test]
    fn prompt_suggestion_normalization_is_linear_for_long_input() {
        let long = "x".repeat(100_000);
        let padded = format!(" {long} ");

        assert_eq!(
            normalize_prompt_suggestions(&[PromptSuggestion::new(padded)]),
            vec![resolved(&long, &long)]
        );
        assert_eq!(
            normalize_prompt_suggestions(&[PromptSuggestion::new(" ".repeat(200_000))]),
            []
        );
    }

    #[test]
    fn repeated_prompt_suggestions_get_distinct_keys() {
        let items = [
            resolved("Summarize", "Summarize this thread"),
            resolved("Plan", "Plan"),
            resolved("Summarize", "Summarize this thread"),
        ];
        let keys = prompt_suggestion_keys(&items);

        assert_eq!(keys.len(), 3);
        assert_ne!(keys[0], keys[2]);
        assert_ne!(keys[0], keys[1]);
        assert_eq!(keys, prompt_suggestion_keys(&items));
    }
}