Retrieve selected node start/end positions


#1

Hi,

I would like to change mark’s attribute, at current caret position, when just clicking on text.

My question is in the code below :

pm.on('selectionChange', () => {
  let sel = pm.selection;
  if (sel.from && sel.to) {
    // if selection length is 0 (just clicked on text) 
    if (sel.from.cmp(sel.to) === 0 ) {
      let node = pm.doc.nodeAfter(sel.from);
      if (node) {
        // my question is here
        // how to retrieve node position start and node position end
        // to replace mark at selection pos
      }
    }  
  }
}

#2

I’ve done something like this:

let start
if(node.isTextblock) {
  start = sel.from.shorten()
} else {
  start = sel.from
}
let end = start.move(1)

(I think that’s right, I’m going off of pure memory here)

The reason being, if your selection is in a text block the path component of from is the path to the node and the offset is the position within the text, but for a block selection the path component is the path to the parent node and the offset is the blocks position in relation to it’s siblings


#3

Maybe i didn’t explain well what i’m looking for. Let’s take an example with this document :

Hello ! Bold text and italic text.

The 3 text nodes are :

  • Hello !_ (width 8)
  • Bold text (width 9)
  • and italic text (width 15)

I would like to have :

  • if I click anywhere on node “Hello !” => startingpos : [0:0], endpos : [0:8]
  • if I click anywhere on node “Bold text” => startingpos: [0:8], endpos [0:17]
  • if I click anywhere on last node => startingpos [0:17] endpos [0:32]

Thanks.


#4

This is currently a bit of a pain, but you can use chunkBefore or chunkAfter (depending on which directly you want to bias towards) to get the start of the text node at a given position.


#5

Hi, I have this exact problem. Is there a new way to do this? The links don’t seem to lead anywhere anymore.


#6

You’ll want to use a resolved position for this in the current interface.


#7

Thanks for the fast response! I see textOffset there which I think gets me where I want.