8
0

findlinkrange.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /**
  2. * @license Copyright (c) 2003-2018, 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. * Returns a range containing the entire link in which the given `position` is placed.
  12. *
  13. * It can be used e.g. to get the entire range on which the `linkHref` attribute needs to be changed when having a
  14. * selection inside a link.
  15. *
  16. * @param {module:engine/model/position~Position} position The start position.
  17. * @param {String} value The `linkHref` attribute value.
  18. * @returns {module:engine/model/range~Range} The link range.
  19. */
  20. export default function findLinkRange( position, value ) {
  21. return new Range( _findBound( position, value, true ), _findBound( position, value, false ) );
  22. }
  23. // Walks forward or backward (depends on the `lookBack` flag), node by node, as long as they have the same `linkHref` attribute value
  24. // and returns a position just before or after (depends on the `lookBack` flag) the last matched node.
  25. //
  26. // @param {module:engine/model/position~Position} position The start position.
  27. // @param {String} value The `linkHref` attribute value.
  28. // @param {Boolean} lookBack Whether the walk direction is forward (`false`) or backward (`true`).
  29. // @returns {module:engine/model/position~Position} The position just before the last matched node.
  30. function _findBound( position, value, lookBack ) {
  31. // Get node before or after position (depends on `lookBack` flag).
  32. // When position is inside text node then start searching from text node.
  33. let node = position.textNode || ( lookBack ? position.nodeBefore : position.nodeAfter );
  34. let lastNode = null;
  35. while ( node && node.getAttribute( 'linkHref' ) == value ) {
  36. lastNode = node;
  37. node = lookBack ? node.previousSibling : node.nextSibling;
  38. }
  39. return lastNode ? Position.createAt( lastNode, lookBack ? 'before' : 'after' ) : position;
  40. }