lexical icon indicating copy to clipboard operation
lexical copied to clipboard

Feature: Allow passing prop of type `SerializedEditorState` as editorState in LexicalComposer initialConfig

Open Amethystix opened this issue 2 years ago • 3 comments

Hi team! I'm working on a project using lexical, and found that although I'm storing my editor state as JSON in my database, since my ORM converts the editor state to an object when I query for it, the type I have that I pass into the default editor state is SerializedEditorState, and I have to stringify this object every single time, despite the fact that editor.parseEditorState being used on this default state can accept the SerializedEditorState type.

I would be happy to contribute this myself, as I see it looks to be a simple change to LexicalComposer.tsx (unless I'm off-base here, and there's some other complexities; am pretty new to this library)

While on the subject, just wanted to mention that passing in an invalid JSON string causes an unhandled Exception to be thrown, and I was wondering if there might be a more graceful way of handling an invalid editor state (perhaps just assuming no default editor state exists and starting anew?)

Amethystix avatar Jan 16 '23 21:01 Amethystix

Not to be a +1 GitHub commenter, but I totally second this. I forgot to actually file the issue (thanks @Amethystix!), but I did post it on Discord.

I have this ugly function that I use in my editor component to allow this, but I'd love official support for this, without the cost of json -> string -> json.

function stringifyIfJSON(
  editorState: AtlasContentEditorOptions["initialState"]
) {
  if (
    !editorState ||
    isEditorState(editorState) ||
    typeof editorState === "string" ||
    typeof editorState === "function"
  )
    return editorState;
  return JSON.stringify(editorState);
}

isEditorState is even worse lol.

function isEditorState(
  editorState: AtlasContentEditorOptions["initialState"]
): editorState is EditorState {
  return (editorState as any)?.constructor?.name === "EditorState";
}

DaniGuardiola avatar Jan 17 '23 04:01 DaniGuardiola

Code reference: https://github.com/facebook/lexical/blob/4c30b5215f0269c069c6c01f5eea973163a77321/packages/lexical-react/src/LexicalComposer.tsx#L135-L156

StyleT avatar Apr 05 '24 22:04 StyleT

When I created a dupe of this one I sketched out some code, if anyone wants an easy PR to take it across the line #6039

etrepum avatar May 06 '24 21:05 etrepum