bevacqua / woofmark

:dog2: Barking up the DOM tree. A modular, progressive, and beautiful Markdown and HTML editor
https://bevacqua.github.io/woofmark
MIT License
1.62k stars 74 forks source link

Cursor may move, select text or insert garbage when switching from markdown to HTML/wysiwyg #76

Open kakra opened 3 years ago

kakra commented 3 years ago

When switching from markdown to wysiwyg (or HTML for that matter), the cursor jumps to a different location, or the editor starts selecting text. It may even destroy the contents by inserting random characters (probably from the markers functions) and repeating existing text.

I'm not sure yet why that happens. To reproduce, certain conditions have to be met to trigger the bug.

Reproducer 1

Go to the demo, switch to markdown mode, place the cursor at the end of the line "Note that,".

  1. Switch to HTML or wysiwyg mode: The cursor jumps to the end of the text.
  2. Switch back to markdown: The cursor stays in position.
  3. Switch to HTML or wysiwyg again: The editor selects text at the top.

Repeating the example by staying above the blockquote doesn't trigger the above, e.g. place the cursor somewhere in the paragraph "Creating links is merely a matter..." and repeat the steps: The cursor does not move.

But this is not limited to blockquotes, in fact, I don't think the blockquote itself is the problem but rather it messes with the HTML tags in markdown mode somehow. Try the following example:

Reproducer 2

  1. Clear the editor, switch to wysiwyg mode.
  2. Enter "example", press shift+enter to insert a line break, enter "123456" in the second line.
  3. Place the cursor between chars 3 and 4 just entered.
  4. Switch to markdown mode: The cursor stays in place.
  5. Switch back to wysiwyg mode: The cursor moved to the end of the line.
  6. Switch back to markdown mode: The cursor stays in place (end of the line).
  7. Switch back to wysiwyg mode: The content of the line changes to 123456agfWoofmarkSelectionOpenMarkerbecbbaaadhcbheeffc with WoofmarkS selected, some inserted characters are random garbage.

When not using a line break (shift+enter) but a paragraph (just enter) in step 2, the problem does not occur.

I tried to debug this but I cannot find where things start to go crazy. Whatever variables I log to the console, their contents seem sane (except that InputState may contain a cursor position outside of the surrounding <p> tag).

kakra commented 3 years ago

I think I could narrow it down to the MarkdownIt rule processor.

kakra commented 3 years ago

I finally located the problem in megamark.js and added a pull request to fix this.