findlinkrange.js 1.7 KB

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