position.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module utils/dom/position
  7. */
  8. import global from './global';
  9. import Rect from './rect';
  10. import getPositionedAncestor from './getpositionedancestor';
  11. import getBorderWidths from './getborderwidths';
  12. /**
  13. * Calculates the `position: absolute` coordinates of a given element so it can be positioned with respect to the
  14. * target in the visually most efficient way, taking various restrictions like viewport or limiter geometry
  15. * into consideration.
  16. *
  17. * // The element which is to be positioned.
  18. * const element = document.body.querySelector( '#toolbar' );
  19. *
  20. * // A target to which the element is positioned relatively.
  21. * const target = document.body.querySelector( '#container' );
  22. *
  23. * // Finding the optimal coordinates for the positioning.
  24. * const { left, top, name } = getOptimalPosition( {
  25. * element: element,
  26. * target: target,
  27. *
  28. * // The algorithm will chose among these positions to meet the requirements such
  29. * // as "limiter" element or "fitInViewport", set below. The positions are considered
  30. * // in the order of the array.
  31. * positions: [
  32. * //
  33. * // [ Target ]
  34. * // +-----------------+
  35. * // | Element |
  36. * // +-----------------+
  37. * //
  38. * targetRect => ( {
  39. * top: targetRect.bottom,
  40. * left: targetRect.left,
  41. * name: 'mySouthEastPosition'
  42. * } ),
  43. *
  44. * //
  45. * // +-----------------+
  46. * // | Element |
  47. * // +-----------------+
  48. * // [ Target ]
  49. * //
  50. * ( targetRect, elementRect ) => ( {
  51. * top: targetRect.top - elementRect.height,
  52. * left: targetRect.left,
  53. * name: 'myNorthEastPosition'
  54. * } )
  55. * ],
  56. *
  57. * // Find a position such guarantees the element remains within visible boundaries of <body>.
  58. * limiter: document.body,
  59. *
  60. * // Find a position such guarantees the element remains within visible boundaries of the browser viewport.
  61. * fitInViewport: true
  62. * } );
  63. *
  64. * // The best position which fits into document.body and the viewport. May be useful
  65. * // to set proper class on the `element`.
  66. * console.log( name ); -> "myNorthEastPosition"
  67. *
  68. * // Using the absolute coordinates which has been found to position the element
  69. * // as in the diagram depicting the "myNorthEastPosition" position.
  70. * element.style.top = top;
  71. * element.style.left = left;
  72. *
  73. * @param {module:utils/dom/position~Options} options Positioning options object.
  74. * @returns {module:utils/dom/position~Position}
  75. */
  76. export function getOptimalPosition( { element, target, positions, limiter, fitInViewport } ) {
  77. // If the {@link module:utils/dom/position~Options#target} is a function, use what it returns.
  78. // https://github.com/ckeditor/ckeditor5-utils/issues/157
  79. if ( typeof target == 'function' ) {
  80. target = target();
  81. }
  82. const positionedElementAncestor = getPositionedAncestor( element.parentElement );
  83. const elementRect = new Rect( element );
  84. const targetRect = new Rect( target );
  85. let bestPosition;
  86. let name;
  87. // If there are no limits, just grab the very first position and be done with that drama.
  88. if ( !limiter && !fitInViewport ) {
  89. [ name, bestPosition ] = getPosition( positions[ 0 ], targetRect, elementRect );
  90. } else {
  91. const limiterRect = limiter && new Rect( limiter ).getVisible();
  92. const viewportRect = fitInViewport && Rect.getViewportRect();
  93. [ name, bestPosition ] =
  94. getBestPosition( positions, targetRect, elementRect, limiterRect, viewportRect ) ||
  95. // If there's no best position found, i.e. when all intersections have no area because
  96. // rects have no width or height, then just use the first available position.
  97. getPosition( positions[ 0 ], targetRect, elementRect );
  98. }
  99. let { left, top } = getAbsoluteRectCoordinates( bestPosition );
  100. if ( positionedElementAncestor ) {
  101. const ancestorPosition = getAbsoluteRectCoordinates( new Rect( positionedElementAncestor ) );
  102. const ancestorBorderWidths = getBorderWidths( positionedElementAncestor );
  103. // (https://github.com/ckeditor/ckeditor5-ui-default/issues/126)
  104. // If there's some positioned ancestor of the panel, then its `Rect` must be taken into
  105. // consideration. `Rect` is always relative to the viewport while `position: absolute` works
  106. // with respect to that positioned ancestor.
  107. left -= ancestorPosition.left;
  108. top -= ancestorPosition.top;
  109. // (https://github.com/ckeditor/ckeditor5-utils/issues/139)
  110. // If there's some positioned ancestor of the panel, not only its position must be taken into
  111. // consideration (see above) but also its internal scrolls. Scroll have an impact here because `Rect`
  112. // is relative to the viewport (it doesn't care about scrolling), while `position: absolute`
  113. // must compensate that scrolling.
  114. left += positionedElementAncestor.scrollLeft;
  115. top += positionedElementAncestor.scrollTop;
  116. // (https://github.com/ckeditor/ckeditor5-utils/issues/139)
  117. // If there's some positioned ancestor of the panel, then its `Rect` includes its CSS `borderWidth`
  118. // while `position: absolute` positioning does not consider it.
  119. // E.g. `{ position: absolute, top: 0, left: 0 }` means upper left corner of the element,
  120. // not upper-left corner of its border.
  121. left -= ancestorBorderWidths.left;
  122. top -= ancestorBorderWidths.top;
  123. }
  124. return { left, top, name };
  125. }
  126. // For given position function, returns a corresponding `Rect` instance.
  127. //
  128. // @private
  129. // @param {Function} position A function returning {@link module:utils/dom/position~Position}.
  130. // @param {utils/dom/rect~Rect} targetRect A rect of the target.
  131. // @param {utils/dom/rect~Rect} elementRect A rect of positioned element.
  132. // @returns {Array} An array containing position name and its Rect.
  133. function getPosition( position, targetRect, elementRect ) {
  134. const { left, top, name } = position( targetRect, elementRect );
  135. return [ name, elementRect.clone().moveTo( left, top ) ];
  136. }
  137. // For a given array of positioning functions, returns such that provides the best
  138. // fit of the `elementRect` into the `limiterRect` and `viewportRect`.
  139. //
  140. // @private
  141. // @param {module:utils/dom/position~Options#positions} positions Functions returning
  142. // {@link module:utils/dom/position~Position} to be checked, in the order of preference.
  143. // @param {utils/dom/rect~Rect} targetRect A rect of the {@link module:utils/dom/position~Options#target}.
  144. // @param {utils/dom/rect~Rect} elementRect A rect of positioned {@link module:utils/dom/position~Options#element}.
  145. // @param {utils/dom/rect~Rect} limiterRect A rect of the {@link module:utils/dom/position~Options#limiter}.
  146. // @param {utils/dom/rect~Rect} viewportRect A rect of the viewport.
  147. // @returns {Array} An array containing the name of the position and it's rect.
  148. function getBestPosition( positions, targetRect, elementRect, limiterRect, viewportRect ) {
  149. let maxLimiterIntersectArea = 0;
  150. let maxViewportIntersectArea = 0;
  151. let bestPositionRect;
  152. let bestPositionName;
  153. // This is when element is fully visible.
  154. const elementRectArea = elementRect.getArea();
  155. positions.some( position => {
  156. const [ positionName, positionRect ] = getPosition( position, targetRect, elementRect );
  157. let limiterIntersectArea;
  158. let viewportIntersectArea;
  159. if ( limiterRect ) {
  160. if ( viewportRect ) {
  161. // Consider only the part of the limiter which is visible in the viewport. So the limiter is getting limited.
  162. const limiterViewportIntersectRect = limiterRect.getIntersection( viewportRect );
  163. if ( limiterViewportIntersectRect ) {
  164. // If the limiter is within the viewport, then check the intersection between that part of the
  165. // limiter and actual position.
  166. limiterIntersectArea = limiterViewportIntersectRect.getIntersectionArea( positionRect );
  167. } else {
  168. limiterIntersectArea = 0;
  169. }
  170. } else {
  171. limiterIntersectArea = limiterRect.getIntersectionArea( positionRect );
  172. }
  173. }
  174. if ( viewportRect ) {
  175. viewportIntersectArea = viewportRect.getIntersectionArea( positionRect );
  176. }
  177. // The only criterion: intersection with the viewport.
  178. if ( viewportRect && !limiterRect ) {
  179. if ( viewportIntersectArea > maxViewportIntersectArea ) {
  180. setBestPosition();
  181. }
  182. }
  183. // The only criterion: intersection with the limiter.
  184. else if ( !viewportRect && limiterRect ) {
  185. if ( limiterIntersectArea > maxLimiterIntersectArea ) {
  186. setBestPosition();
  187. }
  188. }
  189. // Two criteria: intersection with the viewport and the limiter visible in the viewport.
  190. else {
  191. if ( viewportIntersectArea > maxViewportIntersectArea && limiterIntersectArea >= maxLimiterIntersectArea ) {
  192. setBestPosition();
  193. } else if ( viewportIntersectArea >= maxViewportIntersectArea && limiterIntersectArea > maxLimiterIntersectArea ) {
  194. setBestPosition();
  195. }
  196. }
  197. function setBestPosition() {
  198. maxViewportIntersectArea = viewportIntersectArea;
  199. maxLimiterIntersectArea = limiterIntersectArea;
  200. bestPositionRect = positionRect;
  201. bestPositionName = positionName;
  202. }
  203. // If a such position is found that element is fully container by the limiter then, obviously,
  204. // there will be no better one, so finishing.
  205. return limiterIntersectArea === elementRectArea;
  206. } );
  207. return bestPositionRect ? [ bestPositionName, bestPositionRect ] : null;
  208. }
  209. // DOMRect (also Rect) works in a scroll–independent geometry but `position: absolute` doesn't.
  210. // This function converts Rect to `position: absolute` coordinates.
  211. //
  212. // @private
  213. // @param {utils/dom/rect~Rect} rect A rect to be converted.
  214. // @returns {Object} Object containing `left` and `top` properties, in absolute coordinates.
  215. function getAbsoluteRectCoordinates( { left, top } ) {
  216. const { scrollX, scrollY } = global.window;
  217. return {
  218. left: left + scrollX,
  219. top: top + scrollY,
  220. };
  221. }
  222. /**
  223. * The `getOptimalPosition` helper options.
  224. *
  225. * @interface module:utils/dom/position~Options
  226. */
  227. /**
  228. * Element that is to be positioned.
  229. *
  230. * @member {HTMLElement} #element
  231. */
  232. /**
  233. * Target with respect to which the `element` is to be positioned.
  234. *
  235. * @member {HTMLElement|Range|ClientRect|Function} #target
  236. */
  237. /**
  238. * An array of functions which return {@link module:utils/dom/position~Position} relative
  239. * to the `target`, in the order of preference.
  240. *
  241. * @member {Array.<Function>} #positions
  242. */
  243. /**
  244. * When set, the algorithm will chose position which fits the most in the
  245. * limiter's bounding rect.
  246. *
  247. * @member {HTMLElement|Range|ClientRect} #limiter
  248. */
  249. /**
  250. * When set, the algorithm will chose such a position which fits `element`
  251. * the most inside visible viewport.
  252. *
  253. * @member {Boolean} #fitInViewport
  254. */
  255. /**
  256. * An object describing a position in `position: absolute` coordinate
  257. * system, along with position name.
  258. *
  259. * @typedef {Object} module:utils/dom/position~Position
  260. *
  261. * @property {Number} top Top position offset.
  262. * @property {Number} left Left position offset.
  263. * @property {String} name Name of the position.
  264. */