lexical icon indicating copy to clipboard operation
lexical copied to clipboard

Bug: Cannot enter text in editor

Open vitonsky opened this issue 4 months ago • 9 comments

Lexical version: 0.46.0

Steps To Reproduce

Link to code example: https://stackblitz.com/edit/facebook-lexical-dcvkznsq?file=src%2Ftests%2Fsimple-rich-editor.dom.test.ts,src%2Ftests%2Findex.tsx,src%2Ftests%2Ftest-utils.tsx

The problem

Text cannot be enter in rich editor.

I've create test draft in our project and I want to make this test more complex, but I cannot to continue, because I'm stuck with even a trivial expectations:

test('Enter text in empty editor', async () => {
  const user = userEvent.setup({
    pointerEventsCheck: PointerEventsCheckLevel.Never,
  });
  const { render, getEditor } = renderSimpleRichEditor();
  const { container } = render;

  expect(getEditor()?.isEditable()).toBe(true);

  const textbox = within(container).getByRole('textbox');
  await user.click(textbox);
  await user.keyboard('x');

  screen.debug();

  const paragraphs = within(container).getAllByRole('paragraph');
  expect(paragraphs).toHaveLength(1);
  expect(paragraphs[0]).toHaveTextContent('x');
});

Here we want to just make sure we can enter text in editor after creation.

  • Create editor
  • Enter char x
  • Expect there will be paragraph with char x

But the actual DOM structure is

<body>
  <div>
    <div
      class="RichEditor"
      style="position: relative; display: flex; width: 100%; height: 100%; overflow: auto;"
    >
      <div
        contenteditable="true"
        data-lexical-editor="true"
        role="textbox"
        spellcheck="true"
        style="user-select: text; white-space: pre-wrap; word-break: break-word;"
      >
        <p
          dir="auto"
        >
          <br
            data-lexical-managed-linebreak="true"
          />
        </p>
      </div>
    </div>
  </div>
</body>

This bug does not reproduces in case the editor contains at least one text node:

test('Enter text in editor with text', async () => {
  const user = userEvent.setup({
    pointerEventsCheck: PointerEventsCheckLevel.Never,
  });
  const { render, getEditor } = renderSimpleRichEditor();
  const { container } = render;

  expect(getEditor()?.isEditable()).toBe(true);

  // Add text node
  getEditor()!.update(() => {
    const p = $getRoot().getLastChild();
    if (!$isParagraphNode(p)) return;

    const t = $createTextNode('Hello');
    p.append(t);
  });

  const textbox = within(container).getByRole('textbox');
  await user.click(textbox);
  await user.keyboard('x');

  screen.debug();

  const paragraphs = within(container).getAllByRole('paragraph');
  expect(paragraphs).toHaveLength(1);
  expect(paragraphs[0]).toHaveTextContent('x');
});

Also I cannot reproduce this bug in browser

Impact of fix

This bug impact on everyone who develop an editor based on Lexical, since there are not possible to implement tests to cover a trivial cases with editor life cycle, since one of first steps where user enter text in empty editor cannot be implemented.

Also this bug impact users of our app that is in alpha stage, currently it have hundred users. We cannot move forward with Lexical now, because we cannot implement feature and ensure this feature does work.

I provide specific test cases to reproduce bug. I ask maintainers to check it to figure out the root cause of that problem. It is very important for our project.

vitonsky avatar Jul 07 '26 11:07 vitonsky

This isn't a Lexical bug — it's a jsdom limitation with contenteditable.

In jsdom, CAN_USE_BEFORE_INPUT evaluates to false because jsdom's InputEvent doesn't have getTargetRanges. Lexical falls back to its onInput handler, which actually works fine — I verified by dispatching an input event directly on an empty editor and the text gets inserted:

const inputEvent = new InputEvent('input', {
  bubbles: true,
  data: 'x',
  inputType: 'insertText',
});
container.dispatchEvent(inputEvent);
// editor state → "x" ✓

The problem is with userEvent.keyboard() specifically. It fires beforeinput, which Lexical doesn't listen to (because CAN_USE_BEFORE_INPUT is false), so the event isn't prevented. userEvent then tries document.execCommand('insertText') to mutate the DOM itself — but jsdom doesn't implement that, so nothing happens. Your second test works because with an existing TextNode, userEvent can modify the text node directly without needing execCommand.

For testing user input in Lexical, the recommended approach is e2e tests with Playwright — that's what Lexical itself uses for all typing/input tests. jsdom doesn't really support contenteditable behavior, so trying to simulate typing through userEvent will keep hitting walls like this. If you do need a jsdom unit test for some reason, you can dispatch input events directly (like above) or mock CAN_USE_BEFORE_INPUT to true and use beforeinput — see LexicalEmptyEditorTyping.test.ts in the repo for an example.

mayrang avatar Jul 07 '26 12:07 mayrang

@mayrang I've tried to setup e2e tests via vitest, it does not work for us for now because problems with bundling. Our tests is quite simple actually, so unit tests is sweet spot here.

I cannot make unit test work with changes you've mention. My result is:

test('Enter text in empty editor', async () => {
  const { render, getEditor } = renderSimpleRichEditor();
  const { container } = render;

  expect(getEditor()?.isEditable()).toBe(true);

  const inputEvent = new InputEvent('input', {
    bubbles: true,
    data: 'x',
    inputType: 'insertText',
  });
  container.dispatchEvent(inputEvent);

  const paragraphs = within(container).getAllByRole('paragraph');
  expect(paragraphs).toHaveLength(1);
  expect(paragraphs[0]).toHaveTextContent('x');
});

It fails. Could you share the code that does work. You can fork my example above.

@etrepum let's re-open this issue for now to make it visible, since it is not solved yet.

The testing is very important feature of RichEditor. We cannot build anything serious based on Lexical in case we unable to make a strong unit tests against it.

vitonsky avatar Jul 07 '26 17:07 vitonsky

The problem is how you’re using jsdom, not lexical, there’s nothing for lexical to fix here - jsdom and your app’s tests are the broken components. You can see how playwright and vitest browser unit tests are used in the lexical monorepo. You can also polyfill jsdom with mixed results (lexical does a bit of this, though not so much for input). If you want your tests to show that your app works you should really test with actual browser engines because they all have different quirks from each other and jsdom.

etrepum avatar Jul 07 '26 17:07 etrepum

@etrepum what exactly we have to mock to make this test does work?

We cannot setup a playwright tests just for Lexical. There are many factors:

  • The step with build the app is required to run tests. But we need a lot of small unit tests. Many tests needed in custom editor config
  • We actively use Linux, including Fedora. Playwright requires a lot of packages to install and tries to run sudo apt to install packages on Fedora. There are no instructions how to start Playwright on Fedora, so extensive manual frictions is needed
  • vitest + playwright integration does not work well, and throws random errors with no context like undefined __dirname

That's not all factors, just these I faced today when I tried to setup a playwright tests for Lexical. The gist is Playwright configuration is too complex to setup it for testing Lexical.

Does Lexical docs have any info how to test it and how to configure the environment for testing?

Give us something to help us test Lexical.

We will contribute back some useful features. For example right now we develop a Markdown plugin for Lexical that is based on MD AST & remark plugins and ensure a stable roundtrips between Lexical state and markdown texts. That is significant better than standard markdown plugin that does not scale.

We need help with testing. Tell us how to test Lexical.

vitonsky avatar Jul 07 '26 18:07 vitonsky

The vitest browser tests via playwright work fine, we have been using them with no issues. Playwright e2e tests also work perfectly fine in lexical and several of the examples have their own smaller suites of e2e tests. While it’s not fedora all of the suites run in CI on Linux, worst case you could use something like docker.

I already have a draft @lexical/mdast extension that implements that feature https://github.com/facebook/lexical/pull/8794

etrepum avatar Jul 07 '26 18:07 etrepum

Correction — my earlier example with container.dispatchEvent(new InputEvent('input', ...)) doesn't actually work. I traced through the code path again and verified with a test: in jsdom, synthetic input events don't mutate the DOM, so Lexical's $updateSelectedTextFromDOM reads the unchanged DOM text and sees no change. Even manually mutating the DOM text node before dispatching the event doesn't work. I should have run the code before posting.

The core issue is that contenteditable editors rely on the browser mutating the DOM first, then the editor observing those mutations. jsdom doesn't implement contenteditable behavior, so there's no way to simulate real user input through events — this applies to all contenteditable editors (ProseMirror, Tiptap, Slate), not just Lexical.

As @etrepum mentioned, vitest browser mode with Playwright is what Lexical uses for input testing — it runs in a real browser engine and avoids the jsdom limitations entirely. Lexical's CI runs these on Ubuntu (pnpm vitest run --project browser). On Fedora, where playwright install-deps (apt-based) won't work, running inside a Docker container with an Ubuntu base image is the standard workaround, as @etrepum suggested.

mayrang avatar Jul 07 '26 19:07 mayrang

If you are absolutely dead-set on using jsdom unit tests, and not testing actual browser engine behavior, then you should go up a level and do the document modification with lexical rather than attempting to simulate text input with @testing-library/user-event. Use the editor to dispatch commands and/or updates that make the document changes.

etrepum avatar Jul 08 '26 03:07 etrepum

@etrepum our goal is to test the behavior of the code when user will interact with a rich editor via mouse and keyboard. The synthetically called events is subject of other tests in our project.

We have a reason why playwright cannot be used, so we have to use the JSDOM.

We already have such type of tests and it does work well for non-empty editor.

Could you explain from technical perspective why exactly it does not work for case when editor is empty and what we have to implement on our side to make it work.

vitonsky avatar Jul 12 '26 19:07 vitonsky

Your options are to use playwright or simulate the events at a higher level with lexical command dispatch (avoiding all of the missing JSDOM functionality).

What you’re trying to do doesn’t work because JSDOM is not a supported browser engine because it does not implement contentEditable correctly. Why specifically the empty case behaves differently than the non-empty case is not really material, you’re going to run into other broken cases if you try and go down this road. Best case even if you make jsdom work with mocking, you’re still not actually verifying that anything will work in a real environment because browser engines don’t work the same way as jsdom for input events and contentEditable.

etrepum avatar Jul 12 '26 20:07 etrepum