NormalizedRange.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict';
  2. /**
  3. * Licensed Materials - Property of IBM
  4. * IBM Cognos Products: BI Cloud (C) Copyright IBM Corp. 2015, 2017
  5. * US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
  6. */
  7. define(['../../../../lib/@waca/core-client/js/core-client/ui/core/Class', './NormalizedPosition'], function (Class, NormalizedPosition) {
  8. /*
  9. * Represents a range from the document model, but with normalized positions
  10. */
  11. var NormalizedRange = Class.extend({
  12. /*
  13. * @param {range} a Range object from the browser
  14. */
  15. init: function init(range) {
  16. this.original = range;
  17. this.start = new NormalizedPosition(range.startContainer, range.startOffset);
  18. this.end = new NormalizedPosition(range.endContainer, range.endOffset);
  19. },
  20. /**
  21. * @return true iff this range isn't a selection, but rather a cursor location
  22. */
  23. isCursor: function isCursor() {
  24. return this.start.equals(this.end);
  25. },
  26. /**
  27. * @param {string} [selector] a selector to specify whether to restrict which DOM elements the new selection should be defined in terms of
  28. * @return a Range object for use in selection, tweaked for best accuracy in a browser
  29. */
  30. toDocumentRange: function toDocumentRange(selector) {
  31. var range = document.createRange();
  32. var start = this.start.chooseDocumentPosition(false, selector);
  33. if (!start) {
  34. return null;
  35. }
  36. range.setStart(start.container, start.offset);
  37. var end = null;
  38. if (this.isCursor()) {
  39. end = start; //use identical parameters to start
  40. } else {
  41. //set favourEarlier to true to collapse the selection to only the nodes with actual content
  42. end = this.end.chooseDocumentPosition(true, selector);
  43. }
  44. range.setEnd(end.container, end.offset);
  45. return range;
  46. }
  47. });
  48. return NormalizedRange;
  49. });
  50. //# sourceMappingURL=NormalizedRange.js.map