8
0

position.js 11 KB

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