Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

expandRangeToStartOfLine.js 7.2 KiB

il y a 3 ans
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. "use strict";
  2. /**
  3. * Copyright (c) Facebook, Inc. and its affiliates.
  4. *
  5. * This source code is licensed under the MIT license found in the
  6. * LICENSE file in the root directory of this source tree.
  7. *
  8. * @format
  9. *
  10. * @emails oncall+draft_js
  11. */
  12. var UnicodeUtils = require("fbjs/lib/UnicodeUtils");
  13. var getCorrectDocumentFromNode = require("./getCorrectDocumentFromNode");
  14. var getRangeClientRects = require("./getRangeClientRects");
  15. var invariant = require("fbjs/lib/invariant");
  16. /**
  17. * Return the computed line height, in pixels, for the provided element.
  18. */
  19. function getLineHeightPx(element) {
  20. var computed = getComputedStyle(element);
  21. var correctDocument = getCorrectDocumentFromNode(element);
  22. var div = correctDocument.createElement('div');
  23. div.style.fontFamily = computed.fontFamily;
  24. div.style.fontSize = computed.fontSize;
  25. div.style.fontStyle = computed.fontStyle;
  26. div.style.fontWeight = computed.fontWeight;
  27. div.style.lineHeight = computed.lineHeight;
  28. div.style.position = 'absolute';
  29. div.textContent = 'M';
  30. var documentBody = correctDocument.body;
  31. !documentBody ? process.env.NODE_ENV !== "production" ? invariant(false, 'Missing document.body') : invariant(false) : void 0; // forced layout here
  32. documentBody.appendChild(div);
  33. var rect = div.getBoundingClientRect();
  34. documentBody.removeChild(div);
  35. return rect.height;
  36. }
  37. /**
  38. * Return whether every ClientRect in the provided list lies on the same line.
  39. *
  40. * We assume that the rects on the same line all contain the baseline, so the
  41. * lowest top line needs to be above the highest bottom line (i.e., if you were
  42. * to project the rects onto the y-axis, their intersection would be nonempty).
  43. *
  44. * In addition, we require that no two boxes are lineHeight (or more) apart at
  45. * either top or bottom, which helps protect against false positives for fonts
  46. * with extremely large glyph heights (e.g., with a font size of 17px, Zapfino
  47. * produces rects of height 58px!).
  48. */
  49. function areRectsOnOneLine(rects, lineHeight) {
  50. var minTop = Infinity;
  51. var minBottom = Infinity;
  52. var maxTop = -Infinity;
  53. var maxBottom = -Infinity;
  54. for (var ii = 0; ii < rects.length; ii++) {
  55. var rect = rects[ii];
  56. if (rect.width === 0 || rect.width === 1) {
  57. // When a range starts or ends a soft wrap, many browsers (Chrome, IE,
  58. // Safari) include an empty rect on the previous or next line. When the
  59. // text lies in a container whose position is not integral (e.g., from
  60. // margin: auto), Safari makes these empty rects have width 1 (instead of
  61. // 0). Having one-pixel-wide characters seems unlikely (and most browsers
  62. // report widths in subpixel precision anyway) so it's relatively safe to
  63. // skip over them.
  64. continue;
  65. }
  66. minTop = Math.min(minTop, rect.top);
  67. minBottom = Math.min(minBottom, rect.bottom);
  68. maxTop = Math.max(maxTop, rect.top);
  69. maxBottom = Math.max(maxBottom, rect.bottom);
  70. }
  71. return maxTop <= minBottom && maxTop - minTop < lineHeight && maxBottom - minBottom < lineHeight;
  72. }
  73. /**
  74. * Return the length of a node, as used by Range offsets.
  75. */
  76. function getNodeLength(node) {
  77. // http://www.w3.org/TR/dom/#concept-node-length
  78. switch (node.nodeType) {
  79. case Node.DOCUMENT_TYPE_NODE:
  80. return 0;
  81. case Node.TEXT_NODE:
  82. case Node.PROCESSING_INSTRUCTION_NODE:
  83. case Node.COMMENT_NODE:
  84. return node.length;
  85. default:
  86. return node.childNodes.length;
  87. }
  88. }
  89. /**
  90. * Given a collapsed range, move the start position backwards as far as
  91. * possible while the range still spans only a single line.
  92. */
  93. function expandRangeToStartOfLine(range) {
  94. !range.collapsed ? process.env.NODE_ENV !== "production" ? invariant(false, 'expandRangeToStartOfLine: Provided range is not collapsed.') : invariant(false) : void 0;
  95. range = range.cloneRange();
  96. var containingElement = range.startContainer;
  97. if (containingElement.nodeType !== 1) {
  98. containingElement = containingElement.parentNode;
  99. }
  100. var lineHeight = getLineHeightPx(containingElement); // Imagine our text looks like:
  101. // <div><span>once upon a time, there was a <em>boy
  102. // who lived</em> </span><q><strong>under^ the
  103. // stairs</strong> in a small closet.</q></div>
  104. // where the caret represents the cursor. First, we crawl up the tree until
  105. // the range spans multiple lines (setting the start point to before
  106. // "<strong>", then before "<div>"), then at each level we do a search to
  107. // find the latest point which is still on a previous line. We'll find that
  108. // the break point is inside the span, then inside the <em>, then in its text
  109. // node child, the actual break point before "who".
  110. var bestContainer = range.endContainer;
  111. var bestOffset = range.endOffset;
  112. range.setStart(range.startContainer, 0);
  113. while (areRectsOnOneLine(getRangeClientRects(range), lineHeight)) {
  114. bestContainer = range.startContainer;
  115. bestOffset = range.startOffset;
  116. !bestContainer.parentNode ? process.env.NODE_ENV !== "production" ? invariant(false, 'Found unexpected detached subtree when traversing.') : invariant(false) : void 0;
  117. range.setStartBefore(bestContainer);
  118. if (bestContainer.nodeType === 1 && getComputedStyle(bestContainer).display !== 'inline') {
  119. // The start of the line is never in a different block-level container.
  120. break;
  121. }
  122. } // In the above example, range now spans from "<div>" to "under",
  123. // bestContainer is <div>, and bestOffset is 1 (index of <q> inside <div>)].
  124. // Picking out which child to recurse into here is a special case since we
  125. // don't want to check past <q> -- once we find that the final range starts
  126. // in <span>, we can look at all of its children (and all of their children)
  127. // to find the break point.
  128. // At all times, (bestContainer, bestOffset) is the latest single-line start
  129. // point that we know of.
  130. var currentContainer = bestContainer;
  131. var maxIndexToConsider = bestOffset - 1;
  132. do {
  133. var nodeValue = currentContainer.nodeValue;
  134. var ii = maxIndexToConsider;
  135. for (; ii >= 0; ii--) {
  136. if (nodeValue != null && ii > 0 && UnicodeUtils.isSurrogatePair(nodeValue, ii - 1)) {
  137. // We're in the middle of a surrogate pair -- skip over so we never
  138. // return a range with an endpoint in the middle of a code point.
  139. continue;
  140. }
  141. range.setStart(currentContainer, ii);
  142. if (areRectsOnOneLine(getRangeClientRects(range), lineHeight)) {
  143. bestContainer = currentContainer;
  144. bestOffset = ii;
  145. } else {
  146. break;
  147. }
  148. }
  149. if (ii === -1 || currentContainer.childNodes.length === 0) {
  150. // If ii === -1, then (bestContainer, bestOffset), which is equal to
  151. // (currentContainer, 0), was a single-line start point but a start
  152. // point before currentContainer wasn't, so the line break seems to
  153. // have occurred immediately after currentContainer's start tag
  154. //
  155. // If currentContainer.childNodes.length === 0, we're already at a
  156. // terminal node (e.g., text node) and should return our current best.
  157. break;
  158. }
  159. currentContainer = currentContainer.childNodes[ii];
  160. maxIndexToConsider = getNodeLength(currentContainer);
  161. } while (true);
  162. range.setStart(bestContainer, bestOffset);
  163. return range;
  164. }
  165. module.exports = expandRangeToStartOfLine;