lexical icon indicating copy to clipboard operation
lexical copied to clipboard

Bug: Importing from Markdown strips leading/trailing spaces

Open robfig opened this issue 2 years ago • 3 comments

Lexical version: 0.11.3 (latest)

Steps To Reproduce

  1. Paste the contents of this string (xA0) into the beginning of a line in lexical playground: "    " , so that the line starts with leading spaces
  2. Click "Convert to markdown". Observe that those leading spaces are present in the Markdown
  3. Click "Convert from markdown". Observe the spaces are gone

Expected: Spaces are maintained

My application stores lexical content as markdown (it's used in other contexts). I replace normal spaces with non-breaking spaces so that multiple spaces and leading spaces are rendered as expected when the markdown export is viewed.

Importing that markdown content strips the leading spaces, however:

function importBlocks(
  lineText: string, 
  // ... 
) {
  const lineTextTrimmed = lineText.trim();
  const textNode = $createTextNode(lineTextTrimmed); 
  // ... 

I'm not sure what the utility of that is, but I would prefer if it did no stripping, or at least only stripped normal spaces.

Without doing a hard fork, I don't see any way for me to adjust this behavior to maintain the leading spaces.

robfig avatar Jul 28 '23 16:07 robfig

Still happens in lexical v0.12.2 and @lexical/react 0.12.2.

In this case $convertFromMarkdownString ends up stripping out a space character or new line character at the end of the markdown text:

import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { useEffect } from "react";
import { $convertFromMarkdownString, TRANSFORMERS } from "@lexical/markdown";

type Props = {
  markdown?: string;
};

export const OverrideStatePlugin = ({ markdown }: Props) => {
  const [editor] = useLexicalComposerContext();

  useEffect(() => {
    if (markdown != null && markdown != undefined) {
      editor.update(() => {
        $convertFromMarkdownString(markdown, TRANSFORMERS);
      });
    }
  }, [editor, markdown]);

  return null;
};

kivohin avatar Oct 20 '23 18:10 kivohin

I'm facing this issue also, is there any fixed about this? We need the trailing space but $convertFromMarkdownString stripped it

hieuzeta avatar Nov 03 '23 10:11 hieuzeta

I solved this outside of lexical by using a regex to replace leading/trailing spaces on each line with \x00 and then iterated through all text nodes undoing it after the import.

robfig avatar Nov 03 '23 11:11 robfig