facebookarchive / draft-js

A React framework for building text editors.
https://draftjs.org/
MIT License
22.58k stars 2.64k forks source link

contentState.hasText() uncaught error when content is converted from html with empty content #2283

Open EJLearner opened 4 years ago

EJLearner commented 4 years ago

Do you want to request a feature or report a bug? Report a bug

What is the current behavior? convertFromHTML returns zero contentBlocks for an empty string or an empty tag like <p></p> or <em></em>. When I use that result to create a ContentState with ContentState.createFromBlockArray(), the ContentState can't be used in ContentState.hasText().

**If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem.

  1. convert empty tag like e.g. convertFromHTML('

    ')

  2. use the result in ContentState.createFromBlockArray()
  3. Try to use that content state in content.hasText()
import { ContentState, convertFromHTML } from 'draft-js';

const { contentBlocks, entityMap } = convertFromHTML('<p></p>');
const content = ContentState.createFromBlockArray(contentBlocks, entityMap);
const hasText = content.hasText();

// throws TypeError: Cannot read property 'getLength' of undefined

https://jsfiddle.net/rzrshrp/wpLz9st3/21/

What is the expected behavior? contentState.hasText() returns false

Which versions of Draft.js, and which browser / OS are affected by this issue? Did this work in previous versions of Draft.js? I've only tested with 0.11.13 in Chrome on Windows 10 but I'm assuming this affects all browsers.

This was reported in issue #2226. The createWithContent function was protected from this error but hasText still gives errors for me.

folkjc commented 4 years ago

I think Draft assumes that you will have at least one block in your blockMap. Since your block array is an empty array, when it runs getLength() on the first block (which is undefined) it throws an error.

EJLearner commented 4 years ago

I think Draft assumes that you will have at least one block in your blockMap. Since your block array is an empty array, when it runs getLength() on the first block (which is undefined) it throws an error.

Do you think that Is the desired behavior? createWithContent was modified so that an error isn't thrown for an empty array so I feel that hasText() would be similarly protected.

folkjc commented 4 years ago

Probably. The blank editor on draftjs.org starts with one ContentBlock. If you want to make a blank ContentState, you could always use ContentState.createFromText("").