Potential bug: Code Mirror line widget above the first line disturbs cursor location

Hi There,

After adding a line widget, CodeMirror’s cursor seems to be off.


Two ways to remove it:

  1. if I start typing, this goes away
  2. if I scroll down so that the line widget goes out of sight, this goes away
  • Running editor.refresh or lineWidget.changed doesn’t fix it.
  • Also tried setting the cursor to (0, 0) and then refreshing. That didn’t fix it either.
  • Also tried setting and resetting the document value

When I enter a character manually, it resets to normal, but somehow when I edit programmatically it behaves as if the line widget is not there.

Is this a bug or is there a way around this?

1 Like

Sounds like a bug. Can you create a minimal script that reproduces it?

1 Like

Got it - here it is: https://codesandbox.io/s/loving-hodgkin-30t2x?file=/src/App.js.

When you click on the editor, you can see that the cursor goes into the widget itself, not the line.

Couple of quirks here that may affect the set-up:

  • the DOM element is being rendered using React
  • I’m adding the line widget above the first (0-th) line.

I think the combination of both triggers the bug.

By the way, it would be extremely helpful if there was some sort of programmatic workaround for this or even ideas for possible avenues other than the couple of things we’ve tried above.

P.S. I copied the bug into GitHub to track it there: https://github.com/codemirror/CodeMirror/issues/6359.

I ran into this same behavior when inserting images as widgets. This appears to be due to the asynchronous nature of loading images. I was able to solve this by calling the .changed() method on the returned LineWidget object after the image finishes loading (via the onload attribute). Here is a pseudo example:

let lineWidget
let image = document.createElement('img')
let line = 0

image.src = '/path/to/image'
image.onload = () => lineWidget.changed()

lineWidget = doc.addLineWidget(line, image)

As for why this works sometimes, I assume it could be a race condition between the image (or element) loading in the DOM and the CodeMirror editor rendering the lines. I’m not sure if this is exactly the same problem, but the side effects definitely match.