search
HomeCMS TutorialWordPressRevisiting Squire: an efficient HTML5 rich text editor

重温 Squire:高效的 HTML5 富文本编辑器

What is Squire?

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

Squire is not suitable for creating and editing WYSIWYG website pages. However, for many rich text input and web applications, Squire may be just what you need. It provides power without bloat. It is also licensed from MIT for flexible reuse.

In this tutorial, I'll show you how to download Squire and use it to build a sample input form. If you want to see Squire in action, visit the demo.

Where did the 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. Since it's based in Australia and operates under different laws than the United States, FastMail users have slightly improved privacy protections. You can read more about it here: FastMail says it's not subject to NSA surveillance.

As the FastMail team writes in their blog, they have used CKeditor before:

While not a bad choice, like most other editors it is designed for creating websites rather than writing emails. So by default, simply inserting an image brings up a dialog box with three tabs and more options than you might imagine... It also comes with its own UI toolkit and framework that we have to It took a lot of customization to fit the rest of the new UI we were building; it was a pain to maintain.
Since we care about speed and performance, we also care about code size. The version of CKEditor we used for the previous (classic) UI only included the plugins we needed and was a 159 KB download (gzipped; 441 KB uncompressed). This is code only, styles and images are not included.

They decided to build Squire from scratch. With a compressed and gzipped JavaScript size of just 11.5 KB (34.7 KB uncompressed) and no dependencies, Squire is extremely lightweight.

The results are impressive. The combined code weight required to load the entire compose screen, base libraries, mail and contact model code, and all UI code to render the entire screen is now just 149.4 KB (459.7 KB uncompressed), which is smaller than CKEditor alone.

Squire has no dependencies. There are no XHR wrappers, widget libraries or lightbox overlays. The toolbar has no user interface, which eliminates the bloat that comes with loading two UI toolkits. This is just a simple <textarea></textarea> component that can be manipulated via JavaScript.

How Squire works

Squire uses the selection and range APIs to manipulate the DOM. This eliminates common cross-browser incompatibilities. Again from the FastMail Blog:

Making a rich text editor is notoriously difficult because different browsers are extremely inconsistent in this regard. These APIs were all introduced by Microsoft during the heyday of IE and then copied by other vendors in various incompatible ways... Most rich text editors execute the command and then try to clean up the mess the browser created. With Squire, we neatly bypass this problem.
The general idea of ​​Squire is to allow the browser to do as much as possible (not a lot unfortunately), but control anything that deviates from what is required, or where there are significant cross-browser differences.

Install Squire重温 Squire:高效的 HTML5 富文本编辑器

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

Third, edit the <style></style> block in document.html to add the default style you want the editor to use (or link to an external style sheet).

Use Squire

Let’s take a look at the demo application that comes with Squire. When using Squire, you can use <iframe src="path/to/document.html"></iframe> instead of the <textarea></textarea> element.

In demo:

<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 that loads Squire:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<style type="text/css">
...
  a {
    text-decoration: underline;
  }
  h1 {
    font-size: 138.5%;
  }
...
  blockquote {
    border-left: 2px solid blue;
    margin: 0;
    padding: 0 10px;
  }
</style>
</head>
<body>
<script type="text/javascript" src="squire.js"></script>
</body>
</html>

When using Squire, you can attach an event listener to the iframe's load event. When this event fires, you can get a reference to the editor object via iframe.contentWindow.editor. For example, a demo iframe includes:

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

该演示有两种类型的链接,用于在 Squire 中操作内容。可以对任何选定文本进行操作的简单命令如下所示:

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

需要额外用户输入的复杂命令如下所示;他们添加了提示符 c:

<span id="setFontSize" class="prompt">字体大小</span>

演示应用程序如下所示:

重温 Squire:高效的 HTML5 富文本编辑器

演示页面顶部的 JavaScript 侦听对这些 span 命令的任何点击。如果提示类存在,它会从用户收集更多信息:

<script type="text/javascript" charset="utf-8">
var editor;
document.addEventListener( 'click', function ( e ) {
  var id = e.target.id,
      value;
  if ( id && editor && editor[ id ] ) {
    if ( e.target.className === 'prompt' ) {
      value = prompt( 'Value:' );
    }
    editor[ id ]( value );
  }
}, false );
</script>

然后,它使用命令和任何用户提供的值调用 Squire 编辑器。然后,Squire 将命令应用于当前选定的文本:

编辑器[ id ]( value );

您可以了解有关 Squire 的更多信息,并在自述文件中查看其完整的 API 文档。

扩展演示

作为示例,让我们添加两个读取 Squire 编辑器状态的命令。我们将在演示命令标题的底部添加两个链接:

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

当您选择某些文本并单击它时,所选内容将在警报中弹出,如下所示。

重温 Squire:高效的 HTML5 富文本编辑器

让我们来看看更美观的演示及其工具栏:

重温 Squire:高效的 HTML5 富文本编辑器

此页面的头块集成了 Bootstrap 的样式表和名为 Squire-UI 的样式表。它还为此 Squire-UI 提供 JavaScript。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta charset="UTF-8">
    <title>Squire</title>
    <!--[if IE 8]>
    <script type="text/javascript" src="build/ie8.js"></script>
    <![endif]-->
    <link href='//fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>

    <link href="build/Squire-UI.css" rel="stylesheet" type="text/css" />
    <link href="build/bootstrap/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <script src="build/jQuery/jQuery.js" type="text/javascript"></script>
    <script src="build/squire-raw.js" type="text/javascript"></script>
    <script src="build/Squire-UI.js" type="text/javascript"></script>

It also offers static html for a textarea in the body
<div class="container">
    <div class="row">
        <div class="col-centered">
           <textarea id="foo"></textarea>
        </div>
    </div>

但在加载时,其 JQuery $(document).ready 函数将静态 #foo 文本区域替换为其 SquireUI

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

工具栏配置是通过相当复杂的 JQuery、AJAX、HTML5 和 CSS 配置来实现的。它正在加载此 HTML 页面以显示大部分工具栏:http://neilj.github.io/Squire/build/Squire-UI.html。

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

以下是 Squire-UI.html 源代码的子集,以便您可以查看正在加载的内容:

<div class="menu" contenteditable="false">
    <div class="group">
        <div data-action="bold"  class="item"><i class="fa fa-bold"></i></div>
        <div data-action="italic"  class="item"><i  class="fa fa-italic"></i></div>
        <div data-action="underline"  class="item"><i class="fa fa-underline"></i></div>
        <div id="selectFont" data-action="selectFont"  class="item">
            <i class="fa fa-font"></i>
        </div>
    </div>
    <div class="group">
        <div id="makeLink" data-action="makeLink" class="item"><i class="fa fa-link"></i></div>
        <div data-action="makeOrderedList"  class="item"><i class="fa fa-list"></i></div>
        <div id="insertImage" data-action="insertImage"  class="item">
            <i class="fa fa-picture-o"></i>
        </div>
        <div data-action="increaseQuoteLevel"  class="item"><i class="fa fa-quote-right"></i></div>
    </div>
...

如果他们在分发代码中提供简化的 Bootstrap 工具栏作为附加组件,那就太好了,但您当然可以从他们在上面自己的演示中所做的事情中学习。

我希望您发现 Squire 对您自己的应用程序很有用。请随时在下面发表更正、问题或评论。您还可以通过 Twitter @reifman 联系我或直接向我发送电子邮件。

相关链接

  • Squire:FastMail 的富文本编辑器
  • Squire演示页面
  • Github 上的 Squire 代码库

The above is the detailed content of Revisiting Squire: an efficient HTML5 rich text editor. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the security considerations when using WordPress?What are the security considerations when using WordPress?Apr 29, 2025 am 12:01 AM

TosecureaWordPresssite,followthesesteps:1)RegularlyupdateWordPresscore,themes,andpluginstopatchvulnerabilities.2)Usestrong,uniquepasswordsandenabletwo-factorauthentication.3)OptformanagedWordPresshostingorsecuresharedhostingwithawebapplicationfirewal

How does WordPress compare to other website builders?How does WordPress compare to other website builders?Apr 28, 2025 am 12:04 AM

WordPressexcelsoverotherwebsitebuildersduetoitsflexibility,scalability,andopen-sourcenature.1)It'saversatileCMSwithextensivecustomizationoptionsviathemesandplugins.2)Itslearningcurveissteeperbutofferspowerfulcontroloncemastered.3)Performancecanbeopti

5  WordPress Plugins for Developers To Use in 20255 WordPress Plugins for Developers To Use in 2025Apr 27, 2025 am 08:25 AM

Seven Must-Have WordPress Plugins for 2025 Website Development Building a top-tier WordPress website in 2025 demands speed, responsiveness, and scalability. Achieving this efficiently often hinges on strategic plugin selection. This article highlig

What would you use WordPress for?What would you use WordPress for?Apr 27, 2025 am 12:14 AM

WordPresscanbeusedforvariouspurposesbeyondblogging.1)E-commerce:WithWooCommerce,itcanbecomeafullonlinestore.2)Membershipsites:PluginslikeMemberPressenableexclusivecontentareas.3)Portfoliosites:ThemeslikeAstraallowstunninglayouts.Ensuretomanageplugins

Is WordPress good for creating a portfolio website?Is WordPress good for creating a portfolio website?Apr 26, 2025 am 12:05 AM

Yes,WordPressisexcellentforcreatingaportfoliowebsite.1)Itoffersnumerousportfolio-specificthemeslike'Astra'foreasycustomization.2)Pluginssuchas'Elementor'enableintuitivedesign,thoughtoomanycanslowthesite.3)SEOisenhancedwithtoolslike'YoastSEO',boosting

What are the advantages of using WordPress over coding a website from scratch?What are the advantages of using WordPress over coding a website from scratch?Apr 25, 2025 am 12:16 AM

WordPressisadvantageousovercodingawebsitefromscratchdueto:1)easeofuseandfasterdevelopment,2)flexibilityandscalability,3)strongcommunitysupport,4)built-inSEOandmarketingtools,5)cost-effectiveness,and6)regularsecurityupdates.Thesefeaturesallowforquicke

What makes WordPress a Content Management System?What makes WordPress a Content Management System?Apr 24, 2025 pm 05:25 PM

WordPressisaCMSduetoitseaseofuse,customization,usermanagement,SEO,andcommunitysupport.1)Itsimplifiescontentmanagementwithanintuitiveinterface.2)Offersextensivecustomizationthroughthemesandplugins.3)Providesrobustuserrolesandpermissions.4)EnhancesSEOa

How to add a comment box to WordPressHow to add a comment box to WordPressApr 20, 2025 pm 12:15 PM

Enable comments on your WordPress website to provide visitors with a platform to participate in discussions and share feedback. To do this, follow these steps: Enable Comments: In the dashboard, navigate to Settings > Discussions, and select the Allow Comments check box. Create a comment form: In the editor, click Add Block and search for the Comments block to add it to the content. Custom Comment Form: Customize comment blocks by setting titles, labels, placeholders, and button text. Save changes: Click Update to save the comment box and add it to the page or article.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment