bustle / mobiledoc-kit

A toolkit for building WYSIWYG editors with Mobiledoc
https://bustle.github.io/mobiledoc-kit/demo/
MIT License
1.55k stars 151 forks source link

[Question] How to get selected text? #674

Closed eduludi closed 2 years ago

eduludi commented 5 years ago

It's possible to get the selected text as string, so I can pass it as second argument of editor.insertAtom()?

I'm trying to use editor.cursorDidChange to detect when user selects a text, so at this point I can grab editor.range's head and tail offsets.

Any ideas? Thanks!

eduludi commented 5 years ago

I solved this in my custom editor.cursorDidChange:

const { head, tail, isCollapsed } = editor.range

if (!isCollapsed) {
  const selectedText = head.section.markers
    // - converts markers from `LinkedList` to `Array`
    .map(m => m)

    // - reduce markers texts to a single string
    .reduce((acc, marker) => acc + (marker.isAtom ? ' ' : marker.text), '') // Atoms output a empty string, so we add a space to calculate the offsets.

    // - get selected text using range's head and tail offsets
    .substring(head.offset, tail.offset)

  // Do something with `selectedText ` here
  // ...
}

Is there a better way to do this? This feels a like digging too much into mobiledoc-kit internals.

Can mobiledoc-kit provide a method to achieve something like this in its own API?

sdhull commented 5 years ago

editor.cursor.selectedText(); or if you prefer native APIs (modern browsers): window.getSelection().toString();

Protip: I've cloned the repo so I can do things like git grep selected ... tho I guess you could search here on github too 🤷‍♂️