Extensions

characterCount

Behaviour takes options 0.28 kB gzipped

Live character and word counts, with an optional hard limit.

The limit is enforced by refusing the command rather than truncating: silently cutting a user's paste in half is worse than telling them it did not fit.

Counted only when the document changes. The count used to be taken on every transaction — a caret move, a click, an arrow key — by serialising the whole document to JSON and walking that, so a toolbar showing a word count made every click cost the length of the document.

1 · Install

One package for every extension · there is no @matrajs/characterCount to install.

npm i @matrajs/core

2 · Add it to the editor

Import it and put it in the extensions array. That array is the whole feature list: what is not in it is not in your bundle and not in the document's schema.

import { createEditor, document, paragraph, text, characterCount } from '@matrajs/core'

const editor = createEditor({
  extensions: [document, paragraph, text, characterCount({ … })],
  element: document.querySelector('#editor'),
})

3 · Use it

Run a command, and give focus back · a click on a button takes it away.

editor.commands.countCharacters()
editor.focus()

Wired to a button:

const button = document.querySelector('#countCharacters')

button.addEventListener('click', () => {
  editor.commands.countCharacters()
  editor.focus()
})

Options

characterCount is a function · call it with an options object.

Option Type What it does
limit number Refuse edits that would take the document past this many characters.

Commands

Every one returns true if it changed the document and false if it could not · a command that does not apply where the caret is says so rather than throwing.

Command Call
countCharacters editor.commands.countCharacters()

← All 83 extensions

Edit this page on GitHub