2

I´m trying to create a "one line" message component based on Lexical, but i´m unable to prevent the enter key to create a new paragraph.

Any ideas how to accomplish this?

I´ve added styling with

white-space: nowrap!important; 
      resize: none;

and i´ve tried to MaxLengthPlugin ( which works but if enter in there it creates two lines)

also tried to add

<EditorWrapper ref={onRef} data-testid="editor" 
        onKeyDown={event => {
            if (event.key === 'Enter') {
              event.preventDefault();
            } 
          }}>

I was expecting this to prevent the new paragraph with enter, but still adds a new paragraph in the editor.

4 Answers4

5

I was able to create a single line editor by using registerNodeTransform to remove the LineBreakNode as soon as it's created. It doesn't feel like the best solution, but it works.

editor.registerNodeTransform(LineBreakNode, (node) => {
  node.remove();
});

I also explored listening to the KEY_ENTER_COMMAND command, but that didn't prevent newlines from being pasted into the editor.

Monty
  • 86
  • 2
4

You can register the command INSERT_PARAGRAPH_COMMAND and then return true. By returning true you tell lexical that you have handled the paragraph insert and the default lexical code will not execute.

Example:

useEffect(() => {
   return editor.registerCommand(
      INSERT_PARAGRAPH_COMMAND, 
      () => {
          return true;
      },
      COMMAND_PRIORITY_EDITOR
);}, [editor]);
William
  • 221
  • 2
  • 4
0

If I understand correctly you only want to edit in one line and not allow multiple lines.

For this you can try to use INSERT_LINE_BREAK_COMMAND and prevent line breaks from being added by returning true for the command.

editor.registerCommand(INSERT_LINE_BREAK_COMMAND, () => true, COMMAND_PRIORITY_LOW)
Vlad
  • 385
  • 2
  • 13
0

I could achieve this by listening on the contenteditable element and use e.preventDefault() like so:

<LexicalComposer
  <PlainTextPlugin
    contentEditable={
      <ContentEditable
        onKeyDown={(e) => {
            e.preventDefault();
        }}
      />
    }
  />
</LexicalComposer>
ducci
  • 351
  • 1
  • 4
  • 15