Slate: Cursor absolute position

Created on 13 Sep 2016  路  2Comments  路  Source: ianstormtaylor/slate

What would be the best way to get cursor/caret absolute position in the viewport?

Basically to implement something like Medium when you select new line you will see toolbox popup on the left (to insert image, video etc)

question

Most helpful comment

Hey @podviaznikov!

Depending on what exactly you're looking for there are two cases:

  1. Positioning something relative to the cursor itself. For a good example of this, check out the built-in hovering menu example.
  2. Positioning something relative to the block the cursor is currently in. This sounds like what you're talking about with the Medium editor. In this case, you'd probably want to add a component in your React tree at the same level as the Slate editor, and pass in the same state={state} object. And then inside that component, you'd look for the currently selected block and use the Slate.findDOMNode util function to get a reference to it, and find the coordinates of it the regular DOM way.

I've actually been meaning to open-source a component I built that makes it super easy, but haven't gotten to it yet. Here's a quick gist of it copy-pasted to give you a start: https://gist.github.com/ianstormtaylor/7924e6abc71c1efa40411a4553afe4dc

Hope that helps!

All 2 comments

Hey @podviaznikov!

Depending on what exactly you're looking for there are two cases:

  1. Positioning something relative to the cursor itself. For a good example of this, check out the built-in hovering menu example.
  2. Positioning something relative to the block the cursor is currently in. This sounds like what you're talking about with the Medium editor. In this case, you'd probably want to add a component in your React tree at the same level as the Slate editor, and pass in the same state={state} object. And then inside that component, you'd look for the currently selected block and use the Slate.findDOMNode util function to get a reference to it, and find the coordinates of it the regular DOM way.

I've actually been meaning to open-source a component I built that makes it super easy, but haven't gotten to it yet. Here's a quick gist of it copy-pasted to give you a start: https://gist.github.com/ianstormtaylor/7924e6abc71c1efa40411a4553afe4dc

Hope that helps!

Thank you @ianstormtaylor! That is exactly what I need.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

markolofsen picture markolofsen  路  3Comments

gorillatron picture gorillatron  路  3Comments

ianstormtaylor picture ianstormtaylor  路  3Comments

chriserickson picture chriserickson  路  3Comments

AlexeiAndreev picture AlexeiAndreev  路  3Comments