Advertisement
  1. Web Design
  2. HTML/CSS
  3. Bootstrap

Using Squire, a Lightweight HTML5 Rich Text Editor

Scroll to top
Final product imageFinal product imageFinal product image
What You'll Be Creating

What Is Squire?

Squire is an extremely lightweight HTML5 rich text editor best suited for your applications' rich input forms and simple document creation. It provides cross-browser support but deliberately avoids the complexity of supporting older browsers. It works best beginning with Opera 10, Firefox 3.5, Safari 4, Chrome 9 and IE8.

Squire is not meant for creating and editing WYSIWYG website pages. However, for many rich text input and web application purposes, Squire may be just what you need. It provides the power without the bloat. It's also MIT licensed for flexible reuse.

In this tutorial, I'll show you how to download Squire and build sample input forms with it. If you'd like to see Squire in action, visit the demo.

Where Did Squire Come From?

The FastMail team built Squire to simplify their webmail editor requirements. FastMail is an excellent cloud-based email alternative to Gmail—I'm a daily FastMail user. Because it's based in Australia and operates under different laws than in the U.S., there are slightly improved privacy protections for FastMail users. You can read more about this here: FastMail Says It's Free of NSA Surveillance.

As the FastMail team wrote on their blog, they previously used CKeditor:

While not a bad choice, like most other editors out there it was designed for creating websites, not writing emails. As such, simply inserting an image by default presented a dialog with three tabs and more options than you could believe possible...It also came with its own UI toolkit and framework, which we would have had to heavily customise to fit in with the rest of the new UI we were building; a pain to maintain.
With our focus on speed and performance, we were also concerned about the code size. The version of CKEditor we use for our previous (classic) UI, which only includes the plugins we need, is a 159 KB download (when gzipped; uncompressed it’s 441 KB). That’s just the code, excluding styles and images.

They decided to start from scratch and build Squire. At only 11.5 KB of JavaScript after minification and gzip (34.7 KB uncompressed) and with no dependencies, Squire is extremely lightweight. 

The results are impressive. The combined code weight required to load their whole compose screen, base library, mail and contacts model code and all the UI code to render the entire screen now comes to only 149.4 KB (459.7 KB uncompressed)—less than CKEditor alone.

Squire has no dependencies. There's no XHR wrapper, widget library or lightbox overlays. There's no user interface for a toolbar, which eliminates the bloat of having two UI toolkits loaded. It's just a simple <textarea> component which can be manipulated through JavaScript.

How Squire Works

Squire manipulates the DOM using selection and range APIs. This eliminates common cross-browser incompatibilities. Again, from the FastMail blog:

Making a rich text editor is notoriously difficult due to the fact that different browsers are extremely inconsistent in this area. The APIs were all introduced by Microsoft back in the IE heyday, and were then copied by the other vendors in various incompatible ways ... most rich text editors execute a command, then try to clean up the mess the browser created. With Squire, we neatly bypass this.
The general philosophy of Squire is to allow the browser to do as much as it can (which unfortunately is not very much), but take control anywhere it deviates from what is required, or there are significant cross-browser differences.
Installing Squire

First, visit the Squire Github page and clone or download the source code:

Squire on GithubSquire on GithubSquire on Github

Second, copy the contents of the build/ directory into your application.

Third, edit the <style> block in document.html to add the default styles you would like the editor to use (or link to an external stylesheet).

Using Squire

Let's look at the demo application included with Squire. When using Squire, instead of a <textarea> element, you use an <iframe src="path/to/document.html">

In the demo that's:

1
<iframe src="build/document.html" onload="top.editor=this.contentWindow.editor" width="500" height="500"></iframe>

Document.html is a blank canvas with default styles and it loads Squire:

1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
<meta charset="UTF-8">
5
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
6
<title></title>
7
<style type="text/css">
8
...
9
  a {
10
    text-decoration: underline;
11
  }
12
  h1 {
13
    font-size: 138.5%;
14
  }
15
...
16
  blockquote {
17
    border-left: 2px solid blue;
18
    margin: 0;
19
    padding: 0 10px;
20
  }
21
</style>
22
</head>
23
<body>
24
<script type="text/javascript" src="squire.js"></script>
25
</body>
26
</html>

When using Squire, you attach an event listener to the load event of the iframe. When this fires, you can grab a reference to the editor object through iframe.contentWindow.editor. For example, the demo iframe includes:

onload="top.editor=this.contentWindow.editor"

The demo has two types of links for manipulating content within Squire. Simple commands that can operate with any selected text look like this:

<span id="bold">Bold</span>

And complex commands that require additional user input look like this; they add the prompt c:

<span id="setFontSize" class="prompt">Font size</span>

Here's what the demo application looks like:

Squire HTML DemoSquire HTML DemoSquire HTML Demo

The JavaScript at the top of the demonstration page listens for any clicks to these span commands. If the prompt class exists, it collects more information from the user:

1
<script type="text/javascript" charset="utf-8">
2
var editor;
3
document.addEventListener( 'click', function ( e ) {
4
  var id = e.target.id,
5
      value;
6
  if ( id && editor && editor[ id ] ) {
7
    if ( e.target.className === 'prompt' ) {
8
      value = prompt( 'Value:' );
9
    }
10
    editor[ id ]( value );
11
  }
12
}, false );
13
</script>

Then, it calls the Squire editor with the command and any user-supplied value. Squire then applies the command to the currently selected text:

editor[ id ]( value );

You can learn more about Squire and see its complete API documentation in the ReadMe.

Extending the Demo

Just as an example, let's add two commands that read the state of the Squire editor. We'll add two links to the bottom of the demo's command header:

1
  <p>
2
  <a href="#" onclick="alert(editor['getSelectedText']());">get selection</a> | 
3
  <a href="#" onclick="alert(editor['getDocument']());">get doc</a>
4
  </p>
5
</header>

When you select some text and click on it, the selection will pop up in the alert as shown below.

Squire HTML Demo ExtendedSquire HTML Demo ExtendedSquire HTML Demo Extended

Let's examine the more aesthetically pleasing demo and its toolbar:

Squire Live Demo with BootstrapSquire Live Demo with BootstrapSquire Live Demo with Bootstrap

The head block for this page integrates stylesheets for Bootstrap and one called Squire-UI. It also provides JavaScript for this Squire-UI.

1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
5
    <meta charset="UTF-8">
6
    <title>Squire</title>
7
    <!--[if IE 8]>

8
    <script type="text/javascript" src="build/ie8.js"></script>

9
    <![endif]-->
10
    <link href='//fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
11
12
    <link href="build/Squire-UI.css" rel="stylesheet" type="text/css" />
13
    <link href="build/bootstrap/bootstrap.min.css" rel="stylesheet" type="text/css" />
14
    <script src="build/jQuery/jQuery.js" type="text/javascript"></script>
15
    <script src="build/squire-raw.js" type="text/javascript"></script>
16
    <script src="build/Squire-UI.js" type="text/javascript"></script>
17
18
It also offers static html for a textarea in the body
19
<div class="container">
20
    <div class="row">
21
        <div class="col-centered">
22
           <textarea id="foo"></textarea>
23
        </div>
24
    </div>

But on load, its JQuery $(document).ready function replaces the static #foo textarea with its SquireUI.

1
    <script>
2
    $(document).ready(function () {
3
      UI = new SquireUI({replace: 'textarea#foo', height: 300});
4
    });
5
    </script>

The toolbar configuration is implemented with a fairly complex configuration of JQuery, AJAX, HTML5 and CSS. It's loading this HTML page to display most of the toolbar: http://neilj.github.io/Squire/build/Squire-UI.html.

1
$(div).load(options.buildPath + 'Squire-UI.html', function() {
2
      this.linkDrop = new Drop({
3
        target: $('#makeLink').first()[0],
4
        content: $('#drop-link').html(),
5
        position: 'bottom center',
6
        openOn: 'click'
7
      });

Here's a subset of the source code for Squire-UI.html so you can see what's being loaded:

1
<div class="menu" contenteditable="false">
2
    <div class="group">
3
        <div data-action="bold"  class="item"><i class="fa fa-bold"></i></div>
4
        <div data-action="italic"  class="item"><i  class="fa fa-italic"></i></div>
5
        <div data-action="underline"  class="item"><i class="fa fa-underline"></i></div>
6
        <div id="selectFont" data-action="selectFont"  class="item">
7
            <i class="fa fa-font"></i>
8
        </div>
9
    </div>
10
    <div class="group">
11
        <div id="makeLink" data-action="makeLink" class="item"><i class="fa fa-link"></i></div>
12
        <div data-action="makeOrderedList"  class="item"><i class="fa fa-list"></i></div>
13
        <div id="insertImage" data-action="insertImage"  class="item">
14
            <i class="fa fa-picture-o"></i>
15
        </div>
16
        <div data-action="increaseQuoteLevel"  class="item"><i class="fa fa-quote-right"></i></div>
17
    </div>
18
...

It might have been nice if they had provided a simplified Bootstrap toolbar in the distribution code as an add-on, but you can certainly learn from what they did in their own demo above.

I hope you find Squire useful for your own applications. Please feel free to post corrections, questions or comments below. You can also reach me on Twitter @reifman or email me directly.

Related Links

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Web Design tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.