'how to get text by range or offset in from element?

  • Goal When the user type something like @ I want to get all the text that com after the @ in order to build mention functionality from scratch without a package. Also, I want to do it i an oritigal way instead of slicing the text. For example there maybe something like curr.get_text_content_at_range(0,10)

  • Problem When i tried the following method the line console.log(text[i:f]); does not return the correct text after the @ sign. so I hat to i+2 and f+2 like this console.log(text[i+2:f+2]);

<p class="my_element" contenteditable="true"></p>
fn selection() -> Option<usize> {
    let sel = window().unwrap_throw().get_selection().unwrap().unwrap().get_range_at(0).unwrap().end_offset().unwrap();
    Some((sel + 2) as usize)
}
pub(crate) fn mention_handler(&mut self) {
    let mut curr: Option<Element> = None;
    let mut i: Option<usize> = None;

    let closure = Closure::wrap(Box::new(move |event: web_sys::KeyboardEvent| {
        let range = window().unwrap_throw().get_selection().unwrap().unwrap().get_range_at(0).unwrap();
        curr = Some(range.common_ancestor_container().unwrap().parent_element().unwrap());
        if event.key() == "@" {
            i = Mention::selection();
        }

        if i != None{
            let text = &curr.clone().unwrap().text_content().unwrap();
            log_1(&format!("{:#?},{:#?}", i, Mention::selection()).into());
            log_1(&format!("{:#?}", &text[i.unwrap()..Mention::selection().unwrap()]).into());
        }

    }) as Box<dyn FnMut(_)>);

    self.editor.add_event_listener_with_callback("keyup", closure.as_ref().unchecked_ref());
    closure.forget();
}
  • Note
    • curr = curr html element
    • f = final value
    • f = initial value


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source