facebook / lexical

Lexical is an extensible text editor framework that provides excellent reliability, accessibility and performance.
https://lexical.dev
MIT License
18.27k stars 1.53k forks source link

Bug: Importing from Markdown strips leading/trailing spaces #4843

Open robfig opened 11 months ago

robfig commented 11 months ago

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.

kivohin commented 8 months ago

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;
};
hieuzeta commented 8 months ago

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

robfig commented 8 months ago

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.