Caret position "detection." IsHeading, isNewline, or previous line ends with "?"

I’m new to ProseMirror, started a couple days ago (but getting the hang of it pretty quickly).

I’m working on a floating menu and I want to make it “smart.” For instance, detect if the caret location is on an empty newline (or an empty node? Not 100% sure of the terminology just yet).

Or if it’s directly below an H2 heading. Or if the line before ends with a “?” (even if the line is in the paragraph above).

The menu part is easy.

But I can’t seem to find how to detect caret position to determine if it is on a new empty node/newline. Or at the end of t

I’ve tried things like $from.nodeBefore.textContent.

I’ve managed to detect when at the end of a paragraph (at least it seems to be working). I do this:

const { $from, $to } = editor.state.selection
const isAtEnd = ($from.parent.type.isTextblock && $from.parentOffset === $from.parent.content.size) || false

But I could be mistaken, or there’s an easier way? :slight_smile:

Forgive me if these are newbie/naive questions. I promise I’ll pick up on things very fast once I know. :wink:

Thank you in advance. :pray:

That code looks good.

Figuring out what text comes before the cursor will require two loops – one to exit nodes that the cursor is directly at the start of, and one to enter the nodes before that point until you find a text block. Something like (untested)…

let {$from} = editor.state.selection, {depth, pos} = $from
while (depth && $from.start(depth) == pos) {
  depth--
  pos--
}
let before = $from.node(depth).maybeChild($from.index(depth) - 1)
while (before && !before.isTextblock) before = before.lastChild
return before && before.isTextblock
1 Like

Interesting. Thank you.

I’ll give that a shot and let you know. Appreciate it. :raised_hands:

Works great! Thank you!