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
//! `Mentions`: a textarea that suggests names after a trigger character such as `@`.

// cspell:words onmousedown

use std::rc::Rc;

use dioxus::prelude::*;

use super::SelectOption;
use crate::class::compose;
use crate::hooks::{Controllable, use_controllable, use_unique_id};
use crate::overlay::{DismissLayer, focus_element};

/// Props for [`Mentions`].
#[derive(Props, Clone, PartialEq)]
pub struct MentionsProps {
    /// Controlled text. Leave unset to let the field keep its own text.
    #[props(into)]
    pub value: Option<String>,
    /// Initial text when uncontrolled.
    #[props(default, into)]
    pub default_value: String,
    /// Called with the new text on every edit and after a mention is inserted.
    pub on_value_change: Option<EventHandler<String>>,
    /// Accessible name of the textarea. Defaults to `Mentions`.
    #[props(default = "Mentions".to_string(), into)]
    pub label: String,
    /// Form field name of the textarea.
    #[props(into)]
    pub name: Option<String>,
    /// The people or things that can be mentioned. An option is suggested while its value starts
    /// with the text typed after the trigger, ignoring case; choosing it inserts
    /// `{trigger}{value} `. Disabled options are never suggested.
    #[props(default)]
    pub options: Vec<SelectOption>,
    /// Placeholder text of the textarea.
    #[props(into)]
    pub placeholder: Option<String>,
    /// The text that starts a mention. Defaults to `@`.
    #[props(default = "@".to_string(), into)]
    pub trigger: String,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute, applied to the wrapper.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
}

/// Whether a byte is a JavaScript `\w` word character: an ASCII letter, digit, or underscore.
fn is_word_byte(byte: u8) -> bool {
    byte.is_ascii_alphanumeric() || byte == b'_'
}

/// Byte index where the mention that ends `text` starts: the leftmost `trigger` followed only by
/// word characters up to the end, as lumen-react's `${trigger}\w*$` regular expression finds it.
///
/// One backward scan finds the trailing run of word characters; a match must end inside that run,
/// so a single forward substring search from just before it settles the answer in linear time.
fn mention_start(text: &str, trigger: &str) -> Option<usize> {
    let bytes = text.as_bytes();
    let mut run_start = bytes.len();

    while run_start > 0 && is_word_byte(bytes[run_start - 1]) {
        run_start -= 1;
    }

    let mut from = run_start.saturating_sub(trigger.len());

    while !text.is_char_boundary(from) {
        from += 1;
    }

    text[from..].find(trigger).map(|offset| from + offset)
}

/// The lowercase query typed after the trigger at the end of `text`, or `None` when `text` does
/// not end in a mention. `Some("")` means the trigger was just typed.
pub(crate) fn mentions_query(text: &str, trigger: &str) -> Option<String> {
    mention_start(text, trigger).map(|start| text[start + trigger.len()..].to_ascii_lowercase())
}

/// Replaces the mention that ends `text[..caret]` with `{trigger}{mention} ` and returns the new
/// text with the caret position after the inserted space. Text after the caret is kept. When
/// there is no mention before the caret, the text is unchanged.
pub(crate) fn mentions_insert(
    text: &str,
    caret: usize,
    trigger: &str,
    mention: &str,
) -> (String, usize) {
    let mut caret = caret.min(text.len());

    while !text.is_char_boundary(caret) {
        caret -= 1;
    }

    let (before, after) = text.split_at(caret);
    let mut next = String::with_capacity(text.len() + trigger.len() + mention.len() + 1);

    if let Some(start) = mention_start(before, trigger) {
        next.push_str(&before[..start]);
        next.push_str(trigger);
        next.push_str(mention);
        next.push(' ');
    } else {
        next.push_str(before);
    }

    let caret = next.len();
    next.push_str(after);

    (next, caret)
}

/// The enabled options whose value starts with the query, ignoring case; none without a query.
pub(crate) fn mentions_suggestions<'a>(
    options: &'a [SelectOption],
    query: Option<&str>,
) -> Vec<&'a SelectOption> {
    let Some(query) = query else {
        return Vec::new();
    };

    options
        .iter()
        .filter(|option| !option.disabled && option.value.to_lowercase().starts_with(query))
        .collect()
}

/// The active-option change for a navigation key, like lumen-react: Home and End jump to the
/// ends, and the arrows wrap. `current` is the stored index, which may be stale.
pub(crate) fn mentions_next_active(key: &Key, current: i64, len: usize) -> Option<i64> {
    let len = i64::try_from(len).ok().filter(|len| *len > 0)?;

    match key {
        Key::Home => Some(0),
        Key::End => Some(len - 1),
        Key::ArrowDown => Some((current + 1).rem_euclid(len)),
        Key::ArrowUp => Some((current - 1 + len).rem_euclid(len)),
        _ => None,
    }
}

/// The stored active index clamped to the visible suggestions, or `None` when there are none.
fn resolved_active(active: i64, len: usize) -> Option<usize> {
    let last = len.checked_sub(1)?;

    Some(usize::try_from(active.max(0)).map_or(last, |index| index.min(last)))
}

/// Alt, Ctrl, and Meta (Command) shortcuts belong to the platform, not the suggestions.
fn has_shortcut_modifier(event: &KeyboardEvent) -> bool {
    let modifiers = event.modifiers();

    modifiers.contains(Modifiers::ALT)
        || modifiers.contains(Modifiers::CONTROL)
        || modifiers.contains(Modifiers::META)
        || modifiers.contains(Modifiers::SUPER)
}

/// State shared by the event handlers. Every field is `Copy`.
#[derive(Clone, Copy)]
struct MentionsState {
    value: Controllable<String>,
    query: Signal<Option<String>>,
    active: Signal<i64>,
    textarea: Signal<Option<Rc<MountedData>>>,
}

impl MentionsState {
    fn close(mut self) {
        if self.query.peek().is_some() {
            self.query.set(None);
        }

        if *self.active.peek() != -1 {
            self.active.set(-1);
        }
    }

    /// Inserts a mention at the caret. Dioxus cannot read the caret position, so the caret is
    /// taken to be at the end of the text.
    fn insert(self, trigger: &str, mention: &str) {
        let text = self.value.peek();
        let (next, _caret) = mentions_insert(&text, text.len(), trigger, mention);

        self.value.set(next);
        self.close();
        focus_element(self.textarea.peek().clone());
    }
}

/// A textarea that suggests mentions: typing the trigger (`@` by default) followed by letters,
/// digits, or underscores lists the matching options.
///
/// `ArrowDown` and `ArrowUp` move through the suggestions (wrapping), `Home` and `End` jump to the
/// ends, `Enter` or a click inserts `{trigger}{value} `, and `Escape` closes the list, as in
/// `@santi020k/lumen-react`.
///
/// Dioxus cannot read the caret position, so the mention is always the text at the end of the
/// field: typing a trigger in the middle of existing text does not open suggestions.
#[component]
pub fn Mentions(props: MentionsProps) -> Element {
    let unique = use_unique_id();
    let value = use_controllable(
        props.value.clone(),
        || props.default_value.clone(),
        props.on_value_change,
    );
    let query = use_signal(|| None::<String>);
    let active = use_signal(|| -1_i64);
    let textarea = use_signal(|| None::<Rc<MountedData>>);
    let state = MentionsState {
        value,
        query,
        active,
        textarea,
    };

    let list_id = format!("ui-mentions-{unique}-list");
    let current = value.get();
    let visible = mentions_suggestions(&props.options, query.read().as_deref());
    let expanded = !visible.is_empty();
    let resolved = resolved_active(*active.read(), visible.len());
    let active_id = resolved.map(|index| format!("{list_id}-option-{index}"));
    let class = compose([Some("ui-mentions"), props.class.as_deref()]);
    let options = props.options.clone();
    let input_trigger = props.trigger.clone();
    let key_trigger = props.trigger.clone();

    rsx! {
        div {
            class,
            "data-ui-mentions": "true",
            "data-ui-mentions-trigger": props.trigger.clone(),
            ..props.attributes,
            if expanded {
                DismissLayer { on_dismiss: move |()| state.close() }
            }
            textarea {
                aria_activedescendant: active_id,
                aria_autocomplete: "list",
                aria_controls: list_id.clone(),
                aria_expanded: if expanded { "true" } else { "false" },
                aria_label: props.label,
                class: "ui-textarea ui-mentions__input",
                "data-ui-mentions-input": "true",
                name: props.name,
                placeholder: props.placeholder,
                role: "combobox",
                rows: "3",
                // An absent attribute is an empty field, which keeps server-rendered markup equal
                // to lumen-react's; removing `value` also clears the field on every renderer.
                value: (!current.is_empty()).then_some(current),
                oninput: move |event: FormEvent| {
                    let next = event.value();
                    let next_query = mentions_query(&next, &input_trigger);
                    let mut query = state.query;
                    let mut active = state.active;

                    state.value.set(next);
                    active.set(if next_query.is_some() { 0 } else { -1 });
                    query.set(next_query);
                },
                onkeydown: move |event: KeyboardEvent| {
                    if !event.default_action_enabled()
                        || event.is_composing()
                        || has_shortcut_modifier(&event)
                    {
                        return;
                    }

                    let query = state.query.peek().clone();
                    let visible = mentions_suggestions(&options, query.as_deref());
                    let expanded = !visible.is_empty();
                    let key = event.key();

                    if key == Key::Escape && expanded {
                        event.prevent_default();
                        event.stop_propagation();
                        state.close();

                        return;
                    }

                    if expanded {
                        let current = *state.active.peek();

                        if let Some(next) = mentions_next_active(&key, current, visible.len()) {
                            event.prevent_default();

                            let mut active = state.active;
                            active.set(next);

                            return;
                        }
                    }

                    if key == Key::Enter {
                        let index = resolved_active(*state.active.peek(), visible.len());

                        if let Some(option) = index.map(|index| visible[index]) {
                            event.prevent_default();
                            state.insert(&key_trigger, &option.value);
                        }
                    } else if key == Key::Tab {
                        // Dioxus Native has no blur events; leaving with Tab closes the list.
                        state.close();
                    }
                },
                onblur: move |_| state.close(),
                onmounted: move |event| {
                    let mut textarea = state.textarea;
                    textarea.set(Some(event.data()));
                },
            }
            ul {
                class: "ui-mentions__list",
                "data-ui-mentions-list": "true",
                hidden: !expanded,
                id: list_id.clone(),
                role: "listbox",
                for (index, option) in visible.into_iter().enumerate() {
                    li { key: "{index}",
                        button {
                            aria_selected: if resolved == Some(index) { "true" } else { "false" },
                            class: "ui-mentions__option",
                            "data-ui-mentions-option": "true",
                            "data-value": option.value.clone(),
                            id: "{list_id}-option-{index}",
                            role: "option",
                            tabindex: "-1",
                            r#type: "button",
                            onclick: {
                                let trigger = props.trigger.clone();
                                let mention = option.value.clone();
                                move |event: MouseEvent| {
                                    // Keeps focus in the textarea on Dioxus Native, which would
                                    // otherwise clear it after a click on a button.
                                    event.prevent_default();
                                    state.insert(&trigger, &mention);
                                }
                            },
                            onmousedown: move |event: MouseEvent| event.prevent_default(),
                            "{option.label}"
                        }
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        Key, SelectOption, mention_start, mentions_insert, mentions_next_active, mentions_query,
        mentions_suggestions, resolved_active,
    };

    #[test]
    fn queries_follow_the_trailing_trigger() {
        assert_eq!(mentions_query("Hello @Al", "@").as_deref(), Some("al"));
        assert_eq!(mentions_query("Hello @", "@").as_deref(), Some(""));
        assert_eq!(mentions_query("@a_1", "@").as_deref(), Some("a_1"));
        assert_eq!(mentions_query("Hello @al ", "@"), None);
        assert_eq!(mentions_query("Hello @al-x", "@"), None);
        assert_eq!(mentions_query("Hello", "@"), None);
        assert_eq!(mentions_query("", "@"), None);
        assert_eq!(mentions_query("a@b@cd", "@").as_deref(), Some("cd"));
        assert_eq!(mentions_query("#topic", "#").as_deref(), Some("topic"));
        assert_eq!(mentions_query("@topic", "#"), None);
    }

    #[test]
    fn non_ascii_letters_end_a_mention_like_javascript_word_characters() {
        assert_eq!(mentions_query("@café", "@"), None);
        assert_eq!(mentions_query("café @jo", "@").as_deref(), Some("jo"));
        assert_eq!(mentions_query("→@x", "@").as_deref(), Some("x"));
    }

    #[test]
    fn multi_character_and_word_triggers_match_the_leftmost_occurrence() {
        // `@@@abc` with trigger `@@`: the regex fails at 0 (the third `@` is not a word
        // character) and matches at 1.
        assert_eq!(mention_start("@@@abc", "@@"), Some(1));
        assert_eq!(mentions_query("@@@abc", "@@").as_deref(), Some("abc"));
        // A word-character trigger can start inside the trailing word run.
        assert_eq!(mention_start("zoo", "o"), Some(1));
        assert_eq!(mentions_query("zoo", "o").as_deref(), Some("o"));
        // An empty trigger matches the trailing word run, like `\w*$`.
        assert_eq!(mentions_query("hi there", "").as_deref(), Some("there"));
        assert_eq!(mentions_query("hi ", "").as_deref(), Some(""));
        // A multi-byte trigger.
        assert_eq!(mentions_query("ping ï¼ ana", "ï¼ ").as_deref(), Some("ana"));
        assert_eq!(mentions_query("é@", "@").as_deref(), Some(""));
    }

    #[test]
    fn inserting_replaces_the_query_and_keeps_text_after_the_caret() {
        assert_eq!(
            mentions_insert("Hello @al", 9, "@", "alice"),
            ("Hello @alice ".to_string(), 13)
        );
        assert_eq!(
            mentions_insert("Hello @al tail", 9, "@", "alice"),
            ("Hello @alice  tail".to_string(), 13)
        );
        assert_eq!(
            mentions_insert("@", 1, "@", "bob"),
            ("@bob ".to_string(), 5)
        );
        assert_eq!(
            mentions_insert("#ta", 3, "#", "tasks"),
            ("#tasks ".to_string(), 7)
        );
        assert_eq!(
            mentions_insert("no mention", 10, "@", "bob"),
            ("no mention".to_string(), 10)
        );
        // An out-of-range or mid-character caret is clamped to a character boundary.
        assert_eq!(
            mentions_insert("@al", 99, "@", "alice"),
            ("@alice ".to_string(), 7)
        );
        assert_eq!(mentions_insert("é@a", 1, "@", "x"), ("é@a".to_string(), 0));
    }

    #[test]
    fn suggestions_start_with_the_query_and_skip_disabled_options() {
        let options = vec![
            SelectOption::from("alice"),
            SelectOption::new("Alfred", "Alfred P."),
            SelectOption::from("albert").disabled(true),
            SelectOption::from("bob"),
        ];
        let values = |query: Option<&str>| -> Vec<String> {
            mentions_suggestions(&options, query)
                .into_iter()
                .map(|option| option.value.clone())
                .collect()
        };

        assert_eq!(values(None), Vec::<String>::new());
        assert_eq!(values(Some("")), ["alice", "Alfred", "bob"]);
        assert_eq!(values(Some("al")), ["alice", "Alfred"]);
        assert_eq!(values(Some("lice")), Vec::<String>::new());
    }

    #[test]
    fn navigation_keys_wrap_and_jump_like_lumen_react() {
        assert_eq!(mentions_next_active(&Key::ArrowDown, 0, 3), Some(1));
        assert_eq!(mentions_next_active(&Key::ArrowDown, 2, 3), Some(0));
        assert_eq!(mentions_next_active(&Key::ArrowUp, 0, 3), Some(2));
        assert_eq!(mentions_next_active(&Key::Home, 2, 3), Some(0));
        assert_eq!(mentions_next_active(&Key::End, 0, 3), Some(2));
        assert_eq!(mentions_next_active(&Key::ArrowDown, 7, 3), Some(2));
        assert_eq!(mentions_next_active(&Key::Enter, 0, 3), None);
        assert_eq!(mentions_next_active(&Key::ArrowDown, 0, 0), None);
    }

    #[test]
    fn the_active_index_is_clamped_to_the_suggestions() {
        assert_eq!(resolved_active(-1, 3), Some(0));
        assert_eq!(resolved_active(1, 3), Some(1));
        assert_eq!(resolved_active(9, 3), Some(2));
        assert_eq!(resolved_active(0, 0), None);
    }

    #[test]
    fn adversarial_input_is_parsed_in_linear_time() {
        let words = "a".repeat(200_000);
        let triggers = "@".repeat(200_000);
        let mixed = "@a ".repeat(100_000);

        assert_eq!(mentions_query(&words, "@"), None);
        assert_eq!(
            mentions_query(&format!("@{words}"), "@").map(|query| query.len()),
            Some(200_000)
        );
        assert_eq!(mentions_query(&triggers, "@").as_deref(), Some(""));
        assert_eq!(mentions_query(&mixed, "@"), None);
        assert_eq!(
            mentions_query(&words, &"a".repeat(1_000)).map(|query| query.len()),
            Some(199_000)
        );
        assert_eq!(
            mentions_query(&triggers, &"@".repeat(5_000)).as_deref(),
            Some("")
        );

        let (next, caret) = mentions_insert(&format!("{mixed}@b"), usize::MAX, "@", "bob");
        assert!(next.ends_with("@bob "));
        assert_eq!(caret, next.len());
    }
}