This Blog Post Was Written Using Draft.js
Published: 2016-02-25 15:07:29

<p>Procrastination can be a wonderful thing in programming: Wait around long enough and the open-source universe will present itself to you. For quite some time I had been meaning to recreate the in-browser document editor on the backend of this website from <a href="https://www.tinymce.com/" target="_blank">TinyMCE</a> to something that was less of an&nbsp;opinionated "product" and more extensible so I could add syntax highlighting, toggling between wysiwyg, markup and markdown, and whatever interesting features came to mind in the future, and in a sane manner. Ideally it would play well with <a href="https://facebook.github.io/react/" target="_blank">ReactJS</a>, since that is what I wanted to use for the dynamic parts of this website and is absolutely my go-to environment for implementing complex UI.</p>
<p>And then <a href="https://facebook.github.io/draft-js/" target="_blank">Draft.js</a>, a React framework for building text editors, was announced. It does not just provide everything I need out of the box, so it is going to be some hard work to implement the features I want, but it is the right choice. Since the project already has <a href="https://github.com/facebook/draft-js" target="_blank">almost&nbsp;4,000 stars on GitHub</a>, and is used in production by Facebook on major projects like <a href="https://www.facebook.com/notes/" target="_blank">Notes</a> and <a href="https://www.messenger.com/" target="_blank">Messenger</a>, I can expect that this is a Framework that will evolve for the better and remain stable. The React ecosystem is a really great one to be a part of and I am happy to be using something that not only plays well, is built to make perfect use of the application lifecycle.</p>
<p><iframe class=" fluidvids-elem fluidvids-elem fluidvids-elem fluidvids-elem" src="https://www.youtube.com/embed/feUYwoLhE_4" width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen"></iframe></p>
<h2>React is the right choice for rich text editing</h2>
<p>Text editing is a fundamental state synchronization issue. As I make modifications to a portion of the document, I want those changes to be reflected in the transpiled markup&nbsp;without any loss of state or potential for asynchronous outcomes and it needs to happen efficiently. Declaratively rendering the entire document using intelligent diffing based on one central state is the perfect pattern for this. The longer a user stays in an application and the more interactions they have with that application, the bigger the risk of state asynchronization becomes. React is explicitly built to make this less of an issue and is ideologically aligned with the end goal of UI stability.</p>
<h2>The&nbsp;React community gives me confidence</h2>
<p>The number of people ready to jump in on any big project the React team announces makes working within the environment a pleasure. By the time I got wind of Draft.js, the same day it was announced, I already saw <a title="Github issues for Draft.js" href="https://github.com/facebook/draft-js/issues" target="_blank">Github issues</a> relating to questions I had about the framework. I quickly&nbsp;found <a href="https://github.com/evanc/backdraft-js" target="_blank">a project</a> making ground on transpilation from Draft.js blocks to markup, which inspired my solution. Even though&nbsp;Draft.js is new, the combination of community support and the backing of a 300 billion dollar company&nbsp;made me feel very comfortable spiking on it immediately.</p>
<h2>My Basic Implementation</h2>
<p>I rushed to get this into my code because the timing was perfect and I was excited to use it, but right now it is fairly basic and missing a lot of the features I will be implementing over the next few weeks or so. But I am confident I will be able to gradually add the features I need while gaining a better understanding of this flexible API. I made immediate use of the <code>convertFromRaw</code> and <code>convertToRaw</code> methods for transpilation to and from HTML, though it is a work in progress. I used of the <code>RichUtils</code> in order to help manage the complex rich text styling. I have not yet examined the depth of a lot of this functionality but plopping it in was easy enough. Although some of the concepts of Draft.js are complicated, getting started by looking at the examples was quite straightforward.</p>
<p>Here is my <code>render()</code> method, with the code mostly lifted straight from the Draft.js <a href="https://github.com/facebook/draft-js/blob/master/examples/rich/rich.html" target="_blank">rich editor example code</a>.</p>
<pre class="language-markup"><code>render() {
  const {editorState} = this.state;
  let className = 'RichEditor-editor';
  var contentState = editorState.getCurrentContent();
  let markedUpBlocks = backdraft(convertToRaw(contentState), MARKUP);
  if (!contentState.hasText()) {
    if (contentState.getBlockMap().first().getType() !== 'unstyled') {
    className += ' RichEditor-hidePlaceholder';
    }
  }

  return (
    &lt;div className="RichEditor-root"&gt;
      &lt;BlockStyleControls
        editorState={editorState}
        onToggle={this.toggleBlockType}
      /&gt;
      &lt;InlineStyleControls
        editorState={editorState}
        onToggle={this.toggleInlineStyle}
       /&gt;
      &lt;div className={className} onClick={this.focus}&gt;
        &lt;Editor
          blockStyleFn={getBlockStyle}
          customStyleMap={styleMap}
          editorState={editorState}
          handleKeyCommand={this.handleKeyCommand}
          onChange={this.onChange}
          ref="editor"
          spellCheck={true}
         /&gt;
        &lt;/div&gt;
      &lt;div&gt;
        &lt;input type="hidden" name="article[body_html]" id="article_body_html" value={markedUpBlocks.join("")} /&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  );
}</code></pre>
<h2>Why do I need such a complex editor?</h2>
<p>This is very much a project of interest for me and I have run into numerous use cases that correlate with the problems that Draft.js tries to solve. Those problems include things like dynamically generating content such as highlighted tags as a user types, organizing rich data alongside text in an intuitive manner and other similar situations. Dynamic rich text editing is useful more often than we realize and I think developers&nbsp;settle for flimsy implementations a lot of the time. This project involves full-on rich classical document text-editing, which in my opinion is &ldquo;base case&rdquo; and a great place to start given the interface I had in mind, but the areas in which this sort of interactivity can play a big role are many. This API is going to be an important one for web development and I am excited to learn it.</p>
<h2>In conclusion</h2>
<p>Getting this implemented was straightforward, with a gentle and progressive learning curve. It was very nice to have something useful after to work with without even going past the tip of the iceberg in learning this framework. It seemed silly at first that Facebook has not provided some basic markup and markdown transpilation but the reasoning is that the different requirements for each use case make it unrealistic to offer a one-size-fits-all solution. This makes sense for me and I believe the basic API for which to build on for these functionalities works wonderfully. I will open-source anything good that comes from my efforts and I encourage others to do the same. I expect in not too long there will be many plug and play options for all the different data conversion needs. Leaving this to the community of excited React developers has lots of potential.</p>