Accessing the current block type?

Hi,

My editor has a “block type” dropdown, with ‘Normal text’, ‘Heading 1’, ‘preformatted’ etc. I want to display the type of the “current” block.

For spans I was able to get that easily with ProseMirror.activeMarks, however I can’t find a way to get this information for blocks.

I tried with nodeAt on the document, but I’m getting the child node (a TextNode) and I can’t find a way to go up to the parent.

Any idea how I can get that info?

Hmmm, ProseMirror has changed recently how it sets up the commands. Assuming you have something like makeHeading1 where you can execute it using makeHeading1.run(pm). You can then do makeHeading1.active(pm) to determine if it is active. I do this on all of my paragraph/heading commands to find the currently active one.

http://prosemirror.net/ref.html#MenuItemSpec.active

Thank you for your response!

I’m not using the ‘menuitem’ and related helper, since I already had my toolbar before migrating to prosemirror. Is there a way to do it without using the menu related stuff?

@erwanl, yes, check at menu/menu.js how the the menuitems are implemented, than you can do it the same way in your own menubar. I am planning to do that myself next.

You can resolve the cursor position, and check, depending on the kind of node you’re interested in, either its direct parent, or all of its ancestor nodes. How you treat selections that span multiple blocks is up to you.

Thank you, I was able to find it with the code in menu/menu.js!

In case anybody else lands here while googling:

You can check for a certain block type in a selection using the following snippet:

const {$from, to, node} = state.selection
if (node) {
    return node.hasMarkup(nodeType, options.attrs)
} else {
    return to <= $from.end() && $from.parent.hasMarkup(nodeType, options.attrs)
}

Found here.