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};
#[derive(Props, Clone, PartialEq)]
pub struct MentionsProps {
#[props(into)]
pub value: Option<String>,
#[props(default, into)]
pub default_value: String,
pub on_value_change: Option<EventHandler<String>>,
#[props(default = "Mentions".to_string(), into)]
pub label: String,
#[props(into)]
pub name: Option<String>,
#[props(default)]
pub options: Vec<SelectOption>,
#[props(into)]
pub placeholder: Option<String>,
#[props(default = "@".to_string(), into)]
pub trigger: String,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = div)]
pub attributes: Vec<Attribute>,
}
fn is_word_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'_'
}
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)
}
pub(crate) fn mentions_query(text: &str, trigger: &str) -> Option<String> {
mention_start(text, trigger).map(|start| text[start + trigger.len()..].to_ascii_lowercase())
}
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)
}
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()
}
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,
}
}
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)))
}
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)
}
#[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);
}
}
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());
}
}
#[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",
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 {
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| {
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() {
assert_eq!(mention_start("@@@abc", "@@"), Some(1));
assert_eq!(mentions_query("@@@abc", "@@").as_deref(), Some("abc"));
assert_eq!(mention_start("zoo", "o"), Some(1));
assert_eq!(mentions_query("zoo", "o").as_deref(), Some("o"));
assert_eq!(mentions_query("hi there", "").as_deref(), Some("there"));
assert_eq!(mentions_query("hi ", "").as_deref(), Some(""));
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)
);
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());
}
}