Moment For Technology

Complete control over editor content via Quill API (with find replace implementation)

Posted on Dec. 1, 2022, 2:05 p.m. by 王宇軒
Category: The front end Tag: The front end api Angular.js

This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!

DevUI is an open source front-end solution for back-end products in enterprises. It advocates the design values of immersion, flexibility and simplicity. It advocates designers to serve the real needs and design for the majority of people, and rejects the sensationalizing and eye-pleasing design. If you are developing ToB tools, DevUI is a great choice!

The following articles are related to this article, you may also like:

Modularity in Quill, a Modern Rich Text Editor

Quill Rich Text Editor in Practice

How to Insert a Dragon into an Editor?

"Today is children's Day, the whole snake to play in the editor"

Content Rendering in Quill, a modern rich Text editor

Quill Basic Usage and Configuration

The introduction

This is the second in the Quill series.

In the last article, we introduced the basic use and configuration of Quill. I believe you can build a simple rich text editor using Quill.

However, the actual business scenario may be more complex and have more customized requirements. Can Quill meet them?

Quill is an API-driven rich text editor with complete control over its content through the API. Let's take a look.

1 Control of content

The most basic operation of a rich text editor is to add/delete/modify/search content. For example:

  • Add some text somewhere in the editor
  • Select a section of the editor and delete it
  • Select a section of text and add some format to it
  • Take a piece of it and transform it

This is easy to do directly with the keyboard and mouse, but what about the API?

1.1 delete

The deleteText() method takes two main parameters:

  • Where is index deleted
  • Length How much content to delete

For example, I want to delete the following Hello:

this.quill.deleteText(0, 6);
Copy the code

For example, IF I want to delete all the contents in the editor, but we don't know how many contents there are, do we need to count them one by one?

Not necessarily, Quill provides a method called getLength() that queries the total number of characters in the editor (as described in the section on querying).

So it's easy to delete everything:

this.quill.deleteText(0, this.quill.getLength());
Copy the code

Another common situation is when we want to delete a selection in the editor. How do we do that?

Quill provides a method getSelection() to get editor selection (more on controlling selection later) that can be easily implemented:

Const {index, length} = this.quill.getSelection(); // Get the index and length const {index, length} = this.quill.getSelection(); this.quill.deleteText(index, length);Copy the code

Isn't it very convenient?

1.2 check

In the search section, Quill hosts all the content in the editor, so it knows exactly what's inside. Quill knows:

  • What's in the specified location
  • How much content
  • What is its format

You can use the getText() method to get plain text content in a similar way to the deleteText() method described earlier:

GetText (0, 6); this.quill.gettext (0, 6); // Get the full text this.quill.gettext () without passing any arguments; // Get the selected text const {index, length} = this.quill.getSelection(); this.quill.getText(index, length);Copy the code

Now that you know what the content is, it's easy to get the length of the content:

const length = this.quill.getText().length;
Copy the code

Quill provides a simple method called getLength() to get the length of the entire text directly:

const length = this.quill.getLength();
Copy the code

To get the length of the selected text, use the getSelection() method described earlier:

const length = this.quill.getSelection().length;
Copy the code

1.3 to add

1.3.1 Inserting text

Adding formatted content to the editor is the most common requirement, and Quill provides a very rich API for this scenario, starting with the insertText() method.

This method can add both plain text and formatted text.

Inserting plain text requires passing two arguments:

  • Index Specifies where the text is inserted
  • Text What text is inserted
This.quill.inserttext (0, 'DevUI is an open source front-end solution for back-end products in the enterprise ');Copy the code

Inserting formatted text requires passing two additional arguments:

  • Format Specifies the name of the format
  • Value Specifies the value in the value format

Let's say I want to insert a hyperlinked DevUI behind the current cursor:

const range = this.quill.getSelection();
if (range) {
  this.quill.insertText(range.index, 'DevUI', 'link', 'https://devui.design/');
}
Copy the code

1.3.2 Inserting embedded Content

Insert the embedded content, insertEmbed(), which I'm sure you're familiar with, and I've done this before

This API has been used several times in the three articles.

The difference between this method and insertText() is that there is no second argument because it does not insertText.

For example, insert the B station style divider:

const index = this.quill.getSelection().index;
this.quill.insertEmbed(index, 'divider', {
  url: 'assets/images/divider.png',
  width: '660px',
});
Copy the code

Like inserting a dragon:

const index = this.quill.getSelection().index;
this.quill.insertEmbed(index, 'dragon', {
  id: 'canvas-dragon',
});
Copy the code

For example, insert the snake game:

const index = this.quill.getSelection().index;
this.quill.insertEmbed(index, 'snake', {
  id: 'canvas-snake',
});
Copy the code

1.3.3 Replace existing content with plain text

Both methods add text to existing content.

What if you want to directly replace the existing text with new content?

Use the following two set methods:

  • SetText sets plain text
  • SetContents sets the formatted text

The setText() method takes only one argument:

  • Text Specifies the plain text to be inserted
this.quill.setText('Hello DevUI! ');Copy the code

If the text argument is passed an empty string, the editor is emptied:

this.quill.setText('');
Copy the code

1.3.4 Replace existing content with delta data

The setContents() method is powerful enough to render the content of the editor with the specified delta data.

Let's say we want to turn our current rich text into a snake game:

this.quill.setContents([
  { insert: { snake: { id: 'snake' } } }
]);
Copy the code

Normally delta data is stored in a database, and you can use this method when you use delta to initialize editor content.

1.4 change

The setContents() method has a brother called updateContents(), and both of them are really good at it.

The updateContents() method uses delta to update the specified content in the editor.

For example, if I want to make the selected Quill content DevUI and add a hyperlink, we need to call multiple methods without using the updateContents() method:

const { index, length } = this.quill.getSelection();
this.quill.deleteText(index, length);
this.quill.insertText(index, 'DevUI', 'link', 'https://devui.design/');
Copy the code

Let's see how to do this using the updateContents() method:

this.quill.updateContents([
  { retain: index },
  { delete: length },
  { insert: 'DevUI', attributes: { link: 'https://devui.design/' } }
]);
Copy the code

Both methods have the same effect, but the latter requires only one method to be called.

The updateContents() method allows us to manipulate the editor content by manipulating the JSON data delta without having to manually call the API to change the content, which is a great convenience in some scenarios.

2 Format control

2.1 delete

In addition to being able to delete editor content, we may also need to clear the format of a section of content, which can be done using the removeFormat() method, which is used in much the same way as deleteText(), which is not covered here.

This.quill.removeformat (0, 6); this.quill.removeFormat(0, 6); This.quill.removeformat (0, this.quill.getLength()); // Clear the format of the selected text const {index, length} = this.quill.getSelection(); this.quill.removeFormat(index, length);Copy the code

2.2 check

Getting a single format

The getText() method only gets plain text and doesn't know what format is in it. To get the format of the specified text, you can use the getFormat() method, which works the same way.

// Get the format of the selected text const {index, length} = this.quill.getSelection(); const format = this.quill.getFormat(index, length);Copy the code

For example, in bold:

{ bold: true }
Copy the code

Hyperlink format:

{ link: "https://juejin.cn/post/6976023288753586184" }
Copy the code

Get Delta format

However, the getFormat() method can only get a single format. If you want to know the full format information for a given content, you need to use a more powerful API: GetContents (), which gets the delta form of the content, and the delta format describes not only what the content is, but what the format of that content is.

Let's take a look at the content and format of the selected item below.

Call the getContents() method:

const { index, length } = this.quill.getSelection();
const contents = this.quill.getContents(index, length);
console.log('contents:', contents);
Copy the code

The following information is printed:

{ops: [{insert: 'delete content'}, {attributes: {header: 2}, insert: '\n'}, {attributes: {code: true}, insert: 'delete'}, // Attributes: {code: true}, insert: 'delete'}, 'deleteText()'}, // insert: '{attributes: {list: 'bullet'}, insert:'; '\n'}, // unordered list {insert: 'length how much content to delete '}, {attributes: {list: 'bullet'}, insert: '\n'}, // unordered list {insert: 'length how much content to delete '}, {attributes: {list: 'bullet'}, insert: '\n'}, // unordered list {insert: 'length how much content to delete '}, {attributes: {list: 'bullet'}, 'for example I want to put the following'}, {attributes: {code: true}, insert: 'Hello '}, // inline code format {insert: }, {attributes: {'code-block': true}, insert: '\n'}, // code block format {insert: '\n' } ] }Copy the code

From the above delta structure it is easy to get the format information of the editor content:

  • Delete the contentIs the header two format
  • delete/deleteText()/Hello Is an inline code format
  • Where is index deletedandLength How much content to deleteIs an unordered list format
  • this.quill.deleteText(0, 6);Is a code block format
  • Everything else is plain text

Is it clear?

2.3 to add

In addition to deleting and finding formats, you can also set formatting, and Quill provides three ways to set formatting:

  • Format (format, value) Sets the format of the selected text
  • FormatLine (index, length, format, value) sets the row (block level) format
  • FormatText (Index, Length, format, value) Sets the text format for the specified position
This.quill. format('color', 'pink'); // Set the selected text to pink this.quill.format('color', 'pink'); FormatText (10, 10, 'color', 'pink'); // Set characters 10-20 to pink this.quill.formattext (10, 10, 'color', 'pink'); This.quill. formatLine(0, 1, 'list', 'ordered');Copy the code

3. Control of electoral districts

3.1 check

3.1.1 Querying Selection Information

The method getSelection() to get the current selection or cursor, which we have used many times before, shows that this method is a very useful high-frequency method.

This method returns the current selection without passing any arguments:

  • Index Start position of selection
  • Length Selection length
{
  index: 0,
  length: 3
}
Copy the code

If there is only the cursor and nothing is selected, the length returned is 0.

If the editor has no cursor, null is returned.

3.1.2 Querying the Relative Location of the Text

In addition to querying selection position and length, you can query the relative position of the text at the specified position in the editor container using the getBounds() method, which takes two incoming parameters:

  • Index Start position of selection
  • Length Selection length

Let's say I want to look at the position of the first three characters in the editor:

const bounds = this.quill.getBounds(0, 3);
Copy the code

Return result:

{bottom: 49.100006103515625 height: 22.5 left: 18 right: 66 top: 26.600006103515625 width: 48}Copy the code

3.2 to add

In addition to viewing the current selection information, we can manually set the selection and cursor position using the setSelection() method, which takes two arguments:

  • Index Start position of selection
  • Length Selection length

If only the first parameter is set, only the cursor position will be set and the text will not be selected:

// Position the cursor after the 10th character this.quill.setSelection(10);Copy the code

Setting both parameters will select the text:

This.quill.setselection (0, 10);Copy the code

The selection and cursor are the basis for what follows, so this method is a very common one, along with the getSelection() method.

4 summary

Let's do a quick summary:

  • Control of content
    • DeleteText (index, length)
    • GetText (index, length)
    • Get the editor content length getLength()
    • InsertText (index, text, format, value)
    • Insert the embedded content insertEmbed(index, format, value)
    • Replace the content with plain text setText(text)
    • Replace existing contents with delta data setContents(delta)
    • Update content with delta
  • Format control
    • RemoveFormat (index, length)
    • Find a single format getFormat(index, length)
    • Get Delta getContents(index, length)
    • Set the format of the selected text format(format, value)
    • Format (index, length, format, value)
    • FormatText (index, length, format, value)
  • The control of electoral districts
    • GetSelection/cursor information getSelection()
    • Gets the relative position of the specified text getBounds(index, range)
    • SetSelection (index, range)

5 Case: Find the replacement function

Finally, let's take a look at the API we introduced earlier with a look-and-replace example.

// Const STR = 'Quill'; const length = str.length; // Const reg = new RegExp(STR, 'g'); let match; while ((match = reg.exec(this.quill.getText())) ! == null) {// The position of the target text in the document const index = match.index; // Highlight this.quill.formattext (index, length, 'background', '#ef0fff'); // Replace this.quill.deletetext (index, length); this.quill.insertText(index, 'DevUI', 'link', 'https://devui.design/'); }Copy the code

Find replace animation demo effects:

summary

This article focuses on the common Quill apis and the usage scenarios for each.

More on Quill practices will follow, focusing on DevUI not getting lost ?.

Welcome to add DevUI assistant wechat: Devui-official to discuss Angular technology and front-end technology.

Welcome to our DevUI component library and light up our little star ? :

Github.com/devcloudfe/...

Also welcome to use DevUI newly released DevUI Admin system, out of the box, 10 minutes to build a beautiful atmosphere of the background management system!

Join us

We are DevUI team, welcome to come here and build elegant and efficient man-machine design/RD system with us. Recruitment email: [email protected]

The text/DevUI Kagol

Previous article recommended

Quill Basic Usage and Configuration

Modularity in Quill, a Modern Rich Text Editor

Quill Rich Text Editor in Practice

How to Insert a Dragon into an Editor?

"Today is children's Day, the whole snake to play in the editor"

Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.