utils.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. import TreeWalker from '/ckeditor5/engine/model/treewalker.js';
  7. import Delta from '/ckeditor5/engine/model/delta/delta.js';
  8. /**
  9. * Returns tree structure as a simplified string. Elements are uppercase and characters are lowercase.
  10. * Start and end of an element is marked the same way, by the element's name (in uppercase).
  11. *
  12. * let element = new Element( 'div', [], [ 'abc', new Element( 'p', [], 'foo' ), 'xyz' ] );
  13. * modelUtils.getNodesAndText( element ); // abcPfooPxyz
  14. *
  15. * @param {engine.model.Range} range Range to stringify.
  16. * @returns {String} String representing element inner structure.
  17. */
  18. export function getNodesAndText( range ) {
  19. let txt = '';
  20. const treeWalker = new TreeWalker( { boundaries: range } );
  21. for ( let value of treeWalker ) {
  22. let node = value.item;
  23. let nodeText = node.text || node.character;
  24. if ( nodeText ) {
  25. txt += nodeText.toLowerCase();
  26. } else {
  27. txt += node.name.toUpperCase();
  28. }
  29. }
  30. return txt;
  31. }
  32. /**
  33. * Returns object JSON representation. It pases an object by JSON.stringify and JSON.parse functions.
  34. *
  35. * @param {Object|Array} object
  36. */
  37. export function jsonParseStringify( object ) {
  38. return JSON.parse( JSON.stringify( object ) );
  39. }
  40. /**
  41. * Adds given {@link engine.model.operation.Operation operation} to a newly created {@link engine.model.delta.Delta delta}
  42. * and returns it back. Every operation, when applied, have to be added to a delta. This helper function is useful in those
  43. * tests which focus on operations, not deltas.
  44. *
  45. * @param {engine.model.operation.Operation} operation Operation to wrap
  46. * @returns {engine.model.operation.Operation}
  47. */
  48. export function wrapInDelta( operation ) {
  49. const delta = new Delta();
  50. delta.addOperation( operation );
  51. return operation;
  52. }