In the part 1, I wrote about how to set up simple editor with draft-js. But it was not the end, I had to do more. My side project needed the editor with below features:

  • Change text color
  • Change font size / font family
  • Support drag and drop images
  • Emoji/Hashtag

Hmmm, I searched lots about those features on google. Lots of good library built on top draft-js supported them. It was still ok for me to use those libs even I didn’t know what happened behind them. But actually, I felt annoying when doing something that I didn’t understand. Then I tried to study how to build something like it. I wonder what I should start now. Hmm after thinking, I decided to figure how draft-js structure their state.

Second Phase - Go deeper

Internal

In a nutshell, I found:

EditorState

It is an Immutable Record that represents the entire state of a Draft editor, including:

  • The current text content state
  • The current selection state
  • The fully decorated representation of the contents
  • Undo/redo stacks
  • The most recent type of change made to the contents
ContentState

It is an Immutable Record that represents the full state of:

  • The entire contents of an editor: text, block and inline styles, and entity ranges.
  • Two selection states of an editor: before and after the rendering of these contents.
ContentBlock

A block is analogous to a single line of data w/o newline(i.e could be a long wrapped line or a paragraph). And since there can be multiple blocks or lines of data, they are represented in an array called “blocks”.

It is an Immutable Record that represents the full state of a single block of editor content, including:

  • Plain text contents of the block
  • Type, e.g. paragraph, header, list item
  • Entity, inline style, and depth information

Tada, inline style, entity were the keys for my features. Color, Font size, Font family can be toggled by inline style through methods of ContentBlock. So what is entity

Entities enable engineers to introduce levels of richness beyond styled text to their editors. Links, mentions, and embedded content can all be implemented using entities.

Wow, i found it. The key here is Entity.

So the questions I needed to answer were:

  • How to construct Entity? How many kinds of Entity draft-js support
  • How to add own Entity to ContentState

Hmmm too late to write more. Next part will come soon.