neaumusic
neaumusic

Reputation: 10484

How to handle explicit breaks for markdown-to-jsx parsing?

I've been searching for a while now, and I can't seem to find any one mentioning this issue.

We use TipTap / ProseMirror as a text editor, and prosemirror-markdown's default serializer/parser utilize backslash-preceded newlines (\\n) to denote soft breaks, and I think there may be a similar issue with double-space-preceded newlines ( \n), which as far as I know, are explicit breaks in markdown (commonmark?)

In markdown-to-jsx which has over 5 million weekly downloads, I can't seem to determine why it isn't recognizing backslash preceded newlines. It seems to expect single newlines only (\n).

The issue is that the backslashes are rendered in the parsed jsx. I think the preceding spaces would be too.

Am I missing something? I'm messing around with forceBlock: true and forceInline: true but I don't know if these are relevant, and my text is already being rendered in a paragraph, it's just that the backslash newlines arent represented as <br>

Upvotes: 1

Views: 78

Answers (1)

neaumusic
neaumusic

Reputation: 10484

Ok, so I think this is a bug with markdown-to-jsx, and I filed it here.

Thankfully, double space preceded newlines seem to be recognized and parsed into <br> tags correctly.

Consequently, for us and for now, it works to adjust the prosemirror-markdown serializer function for hard breaks (where hardBreak is our node name from doc.type.schema)

export const markdownSerializer = new MarkdownSerializer({
  ...defaultMarkdownSerializer.nodes,
  // hardBreak: defaultMarkdownSerializer.nodes.hard_break,
  hardBreak(state, node, parent, index) {
    for (let i = index + 1; i < parent.childCount; i++)
      if (parent.child(i).type != node.type) {
        state.write("  \n"); // <-- this line is different, the default is "\\\n"
        return;
      }
  },
  {
    ...defaultMarkdownSerializer.marks,
  },
  {
    ...defaultMarkdownSerializer.options,
  }
});

Hopefully this helps other people.

This seems like the safest bet (for one of the many newline issues) translating between html, prosemirror, and markdown.

Upvotes: 0

Related Questions