findlinkrange.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 link/findlinkrange
  7. */
  8. /**
  9. * Returns a range containing the entire link in which the given `position` is placed.
  10. *
  11. * It can be used e.g. to get the entire range on which the `linkHref` attribute needs to be changed when having a
  12. * selection inside a 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, model ) {
  19. return model.createRange( _findBound( position, value, true, model ), _findBound( position, value, false, model ) );
  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, model ) {
  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 ? model.createPositionAt( lastNode, lookBack ? 'before' : 'after' ) : position;
  38. }