utils.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. import ViewPosition from './position';
  6. import ViewTreeWalker from './treewalker';
  7. /**
  8. * Contains utility functions for working on view.
  9. *
  10. * @module engine/view/utils
  11. */
  12. /**
  13. * For given {@link module:engine/view/text~Text view text node}, it finds previous or next sibling that is contained
  14. * in the same container element. If there is no such sibling, `null` is returned.
  15. *
  16. * @param {module:engine/view/text~Text} node Reference node.
  17. * @param {Boolean} getNext If `true` next touching sibling will be returned. If `false` previous touching sibling will be returned.
  18. * @returns {module:engine/view/text~Text|null} Touching text node or `null` if there is no next or previous touching text node.
  19. */
  20. export function getTouchingTextNode( node, getNext ) {
  21. const treeWalker = new ViewTreeWalker( {
  22. startPosition: getNext ? ViewPosition.createAfter( node ) : ViewPosition.createBefore( node ),
  23. direction: getNext ? 'forward' : 'backward'
  24. } );
  25. for ( const value of treeWalker ) {
  26. if ( value.item.is( 'containerElement' ) ) {
  27. // ViewContainerElement is found on a way to next ViewText node, so given `node` was first/last
  28. // text node in it's container element.
  29. return null;
  30. } else if ( value.item.is( 'text' ) ) {
  31. // Found a text node in the same container element.
  32. return value.item;
  33. }
  34. }
  35. return null;
  36. }