Closed eduludi closed 2 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?
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 🤷♂️
It's possible to get the selected text as
string
, so I can pass it as second argument ofeditor.insertAtom()
?I'm trying to use
editor.cursorDidChange
to detect when user selects a text, so at this point I can grabeditor.range
'shead
andtail
offsets.Any ideas? Thanks!