Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] How to get selected text? #674

Closed
eduludi opened this issue Mar 14, 2019 · 2 comments
Closed

[Question] How to get selected text? #674

eduludi opened this issue Mar 14, 2019 · 2 comments

Comments

@eduludi
Copy link

eduludi commented Mar 14, 2019

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
Copy link
Author

eduludi commented Mar 14, 2019

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
Copy link

sdhull commented Mar 20, 2019

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 🤷‍♂️

@gpoitch gpoitch closed this as completed Aug 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants