utils.js 869 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module word-count/utils
  7. */
  8. /**
  9. * Returns a plain text representation of an element and its children.
  10. *
  11. * @param {module:engine/model/element~Element} element
  12. * @returns {String} Plain text representing the model's data.
  13. */
  14. export function modelElementToPlainText( element ) {
  15. if ( element.is( 'text' ) || element.is( 'textProxy' ) ) {
  16. return element.data;
  17. }
  18. let text = '';
  19. let prev = null;
  20. for ( const child of element.getChildren() ) {
  21. const childText = modelElementToPlainText( child );
  22. // If last block was finish, start from new line.
  23. if ( prev && prev.is( 'element' ) ) {
  24. text += '\n';
  25. }
  26. text += childText;
  27. prev = child;
  28. }
  29. return text;
  30. }