How to programmatically replace highlighted selection?


#1

I tried using tr.setSelection(new TextSelection($start, $end)) and while it’s setting the selection in the editor, the actual highlighted text isn’t changing.

Is it possible to programmatically replace the selected text / node? Or will I have to use decorations or some other trick to highlight the text?


#2

tr.setSelection should work. Did you also dispatch the resulting transaction?


#3

Yes the tr is dispatched. To be clear, a tooltip pops up on selection. I see the tooltip move but the highlight text stays the same.

ezgif-4-9fd8dbb191c0

Sample code I’ve tried:

    const $start = state.tr.doc.resolve($anchor.start())
    const $end = state.tr.doc.resolve($anchor.end())

    dispatch(
      state.tr.setSelection(new TextSelection($start, $end))
    )

#4

That’s definitely odd. Where does the tooltip get its position? What does the DOM selection (as in getSelection()) look like after this happens?


#5

the value from window.getSelection() shows the same values before n after but the selection via view.state.selection is updating itself correctly.

the code that gives the tooltip its position is largely taken from the example on the site

  get position () {
    const { view } = this.props
    if (view.state.selection.empty) return null
    const { from, to } = view.state.selection
    const start = view.coordsAtPos(from)
    const end = view.coordsAtPos(to)
    const box = (view as any).dom.offsetParent.getBoundingClientRect()
    const avgLeft = Math.max((start.left + end.left) / 2, start.left + 3)
    return { 
      left: avgLeft - box.left,
      bottom: box.bottom - start.top
    }
  }

Could this be a bug? Or do you think I’m handling something incorrectly in my code?


#6

Possibly (though this is well-exercised code, in general, and there’d have to be some corner case involved). Can you isolate it in a simple, vanilla editor setup?


#7

Implementation details changed a bit, but still will likely need this functionality at some point. So I’ll make sure to open up an issue later if problem persists.

Thanks for following up