-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
utils.ts
40 lines (31 loc) · 903 Bytes
/
utils.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
/**
* @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/utils
*/
import type { Element, Item } from 'ckeditor5/src/engine.js';
/**
* Returns a plain text representation of an element and its children.
*
* @returns Plain text representing the model's data.
*/
export function modelElementToPlainText( item: Item ): string {
if ( item.is( '$text' ) || item.is( '$textProxy' ) ) {
return item.data;
}
const element = item as Element;
let text = '';
let prev = null;
for ( const child of element.getChildren() ) {
const childText = modelElementToPlainText( child );
// If last block was finish, start from new line.
if ( prev && prev.is( 'element' ) ) {
text += '\n';
}
text += childText;
prev = child;
}
return text;
}