-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
wordcount.ts
311 lines (267 loc) · 7.75 KB
/
wordcount.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/**
* @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @module word-count/wordcount
*/
import { type DocumentChangeEvent } from 'ckeditor5/src/engine.js';
import { Plugin, type Editor } from 'ckeditor5/src/core.js';
import { Template, View } from 'ckeditor5/src/ui.js';
import { env } from 'ckeditor5/src/utils.js';
import { modelElementToPlainText } from './utils.js';
import type { WordCountConfig } from './wordcountconfig.js';
import { throttle, isElement } from 'lodash-es';
/**
* The word count plugin.
*
* This plugin calculates all words and characters in all {@link module:engine/model/text~Text text nodes} available in the model.
* It also provides an HTML element that updates its state whenever the editor content is changed.
*
* The model's data is first converted to plain text using {@link module:word-count/utils~modelElementToPlainText}.
* The number of words and characters in your text are determined based on the created plain text. Please keep in mind
* that every block in the editor is separated with a newline character, which is included in the calculation.
*
* Here are some examples of how the word and character calculations are made:
*
* ```html
* <paragraph>foo</paragraph>
* <paragraph>bar</paragraph>
* // Words: 2, Characters: 7
*
* <paragraph><$text bold="true">foo</$text>bar</paragraph>
* // Words: 1, Characters: 6
*
* <paragraph>*&^%)</paragraph>
* // Words: 0, Characters: 5
*
* <paragraph>foo(bar)</paragraph>
* //Words: 1, Characters: 8
*
* <paragraph>12345</paragraph>
* // Words: 1, Characters: 5
* ```
*/
export default class WordCount extends Plugin {
/**
* The number of characters in the editor.
*
* @observable
* @readonly
*/
declare public characters: number;
/**
* The number of words in the editor.
*
* @observable
* @readonly
*/
declare public words: number;
/**
* The label used to display the words value in the {@link #wordCountContainer output container}.
*
* @observable
* @private
* @readonly
*/
declare public _wordsLabel: string | undefined;
/**
* The label used to display the characters value in the {@link #wordCountContainer output container}.
*
* @observable
* @private
* @readonly
*/
declare public _charactersLabel: string | undefined;
/**
* The configuration of this plugin.
*/
private _config: WordCountConfig;
/**
* The reference to a {@link module:ui/view~View view object} that contains the self-updating HTML container.
*/
private _outputView: View | undefined;
/**
* A regular expression used to recognize words in the editor's content.
*/
private readonly _wordsMatchRegExp: RegExp;
/**
* @inheritDoc
*/
constructor( editor: Editor ) {
super( editor );
this.set( 'characters', 0 );
this.set( 'words', 0 );
// Don't wait for the #update event to set the value of the properties but obtain it right away.
// This way, accessing the properties directly returns precise numbers, e.g. for validation, etc.
// If not accessed directly, the properties will be refreshed upon #update anyway.
Object.defineProperties( this, {
characters: {
get() {
return ( this.characters = this._getCharacters( this._getText() ) );
}
},
words: {
get() {
return ( this.words = this._getWords( this._getText() ) );
}
}
} );
this.set( '_wordsLabel', undefined );
this.set( '_charactersLabel', undefined );
this._config = editor.config.get( 'wordCount' ) || {};
this._outputView = undefined;
this._wordsMatchRegExp = env.features.isRegExpUnicodePropertySupported ?
// Usage of regular expression literal cause error during build (ckeditor/ckeditor5-dev#534).
// Groups:
// {L} - Any kind of letter from any language.
// {N} - Any kind of numeric character in any script.
new RegExp( '([\\p{L}\\p{N}]+\\S?)+', 'gu' ) :
/([a-zA-Z0-9À-ž]+\S?)+/gu;
}
/**
* @inheritDoc
*/
public static get pluginName() {
return 'WordCount' as const;
}
/**
* @inheritDoc
*/
public init(): void {
const editor = this.editor;
editor.model.document.on<DocumentChangeEvent>( 'change:data', throttle( this._refreshStats.bind( this ), 250 ) );
if ( typeof this._config.onUpdate == 'function' ) {
this.on<WordCountUpdateEvent>( 'update', ( evt, data ) => {
this._config.onUpdate!( data );
} );
}
if ( isElement( this._config.container ) ) {
this._config.container!.appendChild( this.wordCountContainer );
}
}
/**
* @inheritDoc
*/
public override destroy(): void {
if ( this._outputView ) {
this._outputView.element!.remove();
this._outputView.destroy();
}
super.destroy();
}
/**
* Creates a self-updating HTML element. Repeated executions return the same element.
* The returned element has the following HTML structure:
*
* ```html
* <div class="ck ck-word-count">
* <div class="ck-word-count__words">Words: 4</div>
* <div class="ck-word-count__characters">Characters: 28</div>
* </div>
* ```
*/
public get wordCountContainer(): HTMLElement {
const editor = this.editor;
const t = editor.t;
const displayWords = editor.config.get( 'wordCount.displayWords' );
const displayCharacters = editor.config.get( 'wordCount.displayCharacters' );
const bind = Template.bind( this, this );
const children = [];
if ( !this._outputView ) {
this._outputView = new View();
if ( displayWords || displayWords === undefined ) {
this.bind( '_wordsLabel' ).to( this, 'words', words => {
return t( 'Words: %0', words );
} );
children.push( {
tag: 'div',
children: [
{
text: [ bind.to( '_wordsLabel' ) ]
}
],
attributes: {
class: 'ck-word-count__words'
}
} );
}
if ( displayCharacters || displayCharacters === undefined ) {
this.bind( '_charactersLabel' ).to( this, 'characters', words => {
return t( 'Characters: %0', words );
} );
children.push( {
tag: 'div',
children: [
{
text: [ bind.to( '_charactersLabel' ) ]
}
],
attributes: {
class: 'ck-word-count__characters'
}
} );
}
this._outputView.setTemplate( {
tag: 'div',
attributes: {
class: [
'ck',
'ck-word-count'
]
},
children
} );
this._outputView.render();
}
return this._outputView.element!;
}
private _getText(): string {
let txt = '';
for ( const root of this.editor.model.document.getRoots() ) {
if ( txt !== '' ) {
// Add a delimiter, so words from each root are treated independently.
txt += '\n';
}
txt += modelElementToPlainText( root );
}
return txt;
}
/**
* Determines the number of characters in the current editor's model.
*/
private _getCharacters( txt: string ): number {
return txt.replace( /\n/g, '' ).length;
}
/**
* Determines the number of words in the current editor's model.
*/
private _getWords( txt: string ): number {
const detectedWords = txt.match( this._wordsMatchRegExp ) || [];
return detectedWords.length;
}
/**
* Determines the number of words and characters in the current editor's model and assigns it to {@link #characters} and {@link #words}.
* It also fires the {@link #event:update}.
*
* @fires update
*/
private _refreshStats(): void {
const txt = this._getText();
const words = this.words = this._getWords( txt );
const characters = this.characters = this._getCharacters( txt );
this.fire<WordCountUpdateEvent>( 'update', {
words,
characters
} );
}
}
/**
* An event fired after {@link ~WordCount#words} and {@link ~WordCount#characters} are updated.
*
* @eventName ~WordCount#update
*/
export type WordCountUpdateEvent = {
name: 'update';
args: [ { words: number; characters: number } ];
};