8
0

findlinkrange.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module link/findlinkrange
  7. */
  8. import Range from '@ckeditor/ckeditor5-engine/src/model/range';
  9. import Position from '@ckeditor/ckeditor5-engine/src/model/position';
  10. /**
  11. * Walks backward and forward from the start position, node by node, as long as they have the same `linkHref` attribute value and return
  12. * a {@link module:engine/model/range~Range Range} with the found link.
  13. *
  14. * @param {module:engine/model/position~Position} position The start position.
  15. * @param {String} value The `linkHref` attribute value.
  16. * @returns {module:engine/model/range~Range} The link range.
  17. */
  18. export default function findLinkRange( position, value ) {
  19. return new Range( _findBound( position, value, true ), _findBound( position, value, false ) );
  20. }
  21. // Walks forward or backward (depends on the `lookBack` flag), node by node, as long as they have the same `linkHref` attribute value
  22. // and returns a position just before or after (depends on the `lookBack` flag) the last matched node.
  23. //
  24. // @param {module:engine/model/position~Position} position The start position.
  25. // @param {String} value The `linkHref` attribute value.
  26. // @param {Boolean} lookBack Whether the walk direction is forward (`false`) or backward (`true`).
  27. // @returns {module:engine/model/position~Position} The position just before the last matched node.
  28. function _findBound( position, value, lookBack ) {
  29. // Get node before or after position (depends on `lookBack` flag).
  30. // When position is inside text node then start searching from text node.
  31. let node = position.textNode || ( lookBack ? position.nodeBefore : position.nodeAfter );
  32. let lastNode = null;
  33. while ( node && node.getAttribute( 'linkHref' ) == value ) {
  34. lastNode = node;
  35. node = lookBack ? node.previousSibling : node.nextSibling;
  36. }
  37. return lastNode ? Position.createAt( lastNode, lookBack ? 'before' : 'after' ) : position;
  38. }