8
0

position.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  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 );
  89. const elementRect = new Rect( element );
  90. const targetRect = new Rect( target );
  91. let bestPositionRect;
  92. let bestPositionName;
  93. // If there are no limits, just grab the very first position and be done with that drama.
  94. if ( !limiter && !fitInViewport ) {
  95. [ bestPositionName, bestPositionRect ] = getPositionNameAndRect( positions[ 0 ], targetRect, elementRect );
  96. } else {
  97. const limiterRect = limiter && new Rect( limiter ).getVisible();
  98. const viewportRect = fitInViewport && new Rect( global.window );
  99. const bestPosition = getBestPositionNameAndRect( positions, { targetRect, elementRect, limiterRect, viewportRect } );
  100. // If there's no best position found, i.e. when all intersections have no area because
  101. // rects have no width or height, then just use the first available position.
  102. [ bestPositionName, bestPositionRect ] = bestPosition || getPositionNameAndRect( positions[ 0 ], targetRect, elementRect );
  103. }
  104. let absoluteRectCoordinates = getAbsoluteRectCoordinates( bestPositionRect );
  105. if ( positionedElementAncestor ) {
  106. absoluteRectCoordinates = shiftRectCoordinatesDueToPositionedAncestor( absoluteRectCoordinates, positionedElementAncestor );
  107. }
  108. return {
  109. left: absoluteRectCoordinates.left,
  110. top: absoluteRectCoordinates.top,
  111. name: bestPositionName
  112. };
  113. }
  114. // For given position function, returns a corresponding `Rect` instance.
  115. //
  116. // @private
  117. // @param {Function} position A function returning {@link module:utils/dom/position~Position}.
  118. // @param {utils/dom/rect~Rect} targetRect A rect of the target.
  119. // @param {utils/dom/rect~Rect} elementRect A rect of positioned element.
  120. // @returns {Array} An array containing position name and its Rect.
  121. function getPositionNameAndRect( position, targetRect, elementRect ) {
  122. const { left, top, name } = position( targetRect, elementRect );
  123. return [ name, elementRect.clone().moveTo( left, top ) ];
  124. }
  125. // For a given array of positioning functions, returns such that provides the best
  126. // fit of the `elementRect` into the `limiterRect` and `viewportRect`.
  127. //
  128. // @private
  129. //
  130. // @param {Object} options
  131. // @param {module:utils/dom/position~Options#positions} positions Functions returning {@link module:utils/dom/position~Position}
  132. // to be checked, in the order of preference.
  133. // @param {Object} options
  134. // @param {utils/dom/rect~Rect} options.targetRect A rect of the {@link module:utils/dom/position~Options#target}.
  135. // @param {utils/dom/rect~Rect} options.elementRect A rect of positioned {@link module:utils/dom/position~Options#element}.
  136. // @param {utils/dom/rect~Rect} options.limiterRect A rect of the {@link module:utils/dom/position~Options#limiter}.
  137. // @param {utils/dom/rect~Rect} options.viewportRect A rect of the viewport.
  138. //
  139. // @returns {Array} An array containing the name of the position and it's rect.
  140. function getBestPositionNameAndRect( positions, options ) {
  141. const { elementRect, viewportRect } = options;
  142. // This is when element is fully visible.
  143. const elementRectArea = elementRect.getArea();
  144. // Let's calculate intersection areas for positions. It will end early if best match is found.
  145. const processedPositions = processPositionsToAreas( positions, options );
  146. // First let's check all positions that fully fit in the viewport.
  147. if ( viewportRect ) {
  148. const processedPositionsInViewport = processedPositions.filter( ( { viewportIntersectArea } ) => {
  149. return viewportIntersectArea === elementRectArea;
  150. } );
  151. // Try to find best position from those which fit completely in viewport.
  152. const bestPositionData = getBestOfProcessedPositions( processedPositionsInViewport, elementRectArea );
  153. if ( bestPositionData ) {
  154. return bestPositionData;
  155. }
  156. }
  157. // Either there is no viewportRect or there is no position that fits completely in the viewport.
  158. return getBestOfProcessedPositions( processedPositions, elementRectArea );
  159. }
  160. // For a given array of positioning functions, calculates intersection areas for them.
  161. //
  162. // Note: If some position fully fits into the `limiterRect`, it will be returned early, without further consideration
  163. // of other positions.
  164. //
  165. // @private
  166. //
  167. // @param {module:utils/dom/position~Options#positions} positions Functions returning {@link module:utils/dom/position~Position}
  168. // to be checked, in the order of preference.
  169. // @param {Object} options
  170. // @param {utils/dom/rect~Rect} options.targetRect A rect of the {@link module:utils/dom/position~Options#target}.
  171. // @param {utils/dom/rect~Rect} options.elementRect A rect of positioned {@link module:utils/dom/position~Options#element}.
  172. // @param {utils/dom/rect~Rect} options.limiterRect A rect of the {@link module:utils/dom/position~Options#limiter}.
  173. // @param {utils/dom/rect~Rect} options.viewportRect A rect of the viewport.
  174. //
  175. // @returns {Array.<Object>} Array of positions with calculated intersection areas. Each item is an object containing:
  176. // * {String} positionName Name of position.
  177. // * {utils/dom/rect~Rect} positionRect Rect of position.
  178. // * {Number} limiterIntersectArea Area of intersection of the position with limiter part that is in the viewport.
  179. // * {Number} viewportIntersectArea Area of intersection of the position with viewport.
  180. function processPositionsToAreas( positions, { targetRect, elementRect, limiterRect, viewportRect } ) {
  181. const processedPositions = [];
  182. // This is when element is fully visible.
  183. const elementRectArea = elementRect.getArea();
  184. for ( const position of positions ) {
  185. const [ positionName, positionRect ] = getPositionNameAndRect( position, targetRect, elementRect );
  186. let limiterIntersectArea = 0;
  187. let viewportIntersectArea = 0;
  188. if ( limiterRect ) {
  189. if ( viewportRect ) {
  190. // Consider only the part of the limiter which is visible in the viewport. So the limiter is getting limited.
  191. const limiterViewportIntersectRect = limiterRect.getIntersection( viewportRect );
  192. if ( limiterViewportIntersectRect ) {
  193. // If the limiter is within the viewport, then check the intersection between that part of the
  194. // limiter and actual position.
  195. limiterIntersectArea = limiterViewportIntersectRect.getIntersectionArea( positionRect );
  196. }
  197. } else {
  198. limiterIntersectArea = limiterRect.getIntersectionArea( positionRect );
  199. }
  200. }
  201. if ( viewportRect ) {
  202. viewportIntersectArea = viewportRect.getIntersectionArea( positionRect );
  203. }
  204. const processedPosition = {
  205. positionName,
  206. positionRect,
  207. limiterIntersectArea,
  208. viewportIntersectArea
  209. };
  210. // If a such position is found that element is fully contained by the limiter then, obviously,
  211. // there will be no better one, so finishing.
  212. if ( limiterIntersectArea === elementRectArea ) {
  213. return [ processedPosition ];
  214. }
  215. processedPositions.push( processedPosition );
  216. }
  217. return processedPositions;
  218. }
  219. // For a given array of processed position data (with calculated Rects for positions and intersection areas)
  220. // returns such that provides the best fit of the `elementRect` into the `limiterRect` and `viewportRect` at the same time.
  221. //
  222. // **Note**: It will return early if some position fully fits into the `limiterRect`.
  223. //
  224. // @private
  225. // @param {Array.<Object>} Array of positions with calculated intersection areas (in order of preference).
  226. // Each item is an object containing:
  227. //
  228. // * {String} positionName Name of position.
  229. // * {utils/dom/rect~Rect} positionRect Rect of position.
  230. // * {Number} limiterIntersectArea Area of intersection of the position with limiter part that is in the viewport.
  231. // * {Number} viewportIntersectArea Area of intersection of the position with viewport.
  232. //
  233. // @param {Number} elementRectArea Area of positioned {@link module:utils/dom/position~Options#element}.
  234. // @returns {Array|null} An array containing the name of the position and it's rect, or null if not found.
  235. function getBestOfProcessedPositions( processedPositions, elementRectArea ) {
  236. let maxFitFactor = 0;
  237. let bestPositionRect;
  238. let bestPositionName;
  239. for ( const { positionName, positionRect, limiterIntersectArea, viewportIntersectArea } of processedPositions ) {
  240. // If a such position is found that element is fully container by the limiter then, obviously,
  241. // there will be no better one, so finishing.
  242. if ( limiterIntersectArea === elementRectArea ) {
  243. return [ positionName, positionRect ];
  244. }
  245. // To maximize both viewport and limiter intersection areas we use distance on viewportIntersectArea
  246. // and limiterIntersectArea plane (without sqrt because we are looking for max value).
  247. const fitFactor = viewportIntersectArea ** 2 + limiterIntersectArea ** 2;
  248. if ( fitFactor > maxFitFactor ) {
  249. maxFitFactor = fitFactor;
  250. bestPositionRect = positionRect;
  251. bestPositionName = positionName;
  252. }
  253. }
  254. return bestPositionRect ? [ bestPositionName, bestPositionRect ] : null;
  255. }
  256. // For a given absolute Rect coordinates object and a positioned element ancestor, it returns an object with
  257. // new Rect coordinates that make up for the position and the scroll of the ancestor.
  258. //
  259. // This is necessary because while Rects (and DOMRects) are relative to the browser's viewport, their coordinates
  260. // are used in real–life to position elements with `position: absolute`, which are scoped by any positioned
  261. // (and scrollable) ancestors.
  262. //
  263. // @private
  264. //
  265. // @param {Object} absoluteRectCoordinates An object with absolute rect coordinates.
  266. // @param {Object} absoluteRectCoordinates.top
  267. // @param {Object} absoluteRectCoordinates.left
  268. // @param {HTMLElement} positionedElementAncestor An ancestor element that should be considered.
  269. //
  270. // @returns {Object} An object corresponding to `absoluteRectCoordinates` input but with values shifted
  271. // to make up for the positioned element ancestor.
  272. function shiftRectCoordinatesDueToPositionedAncestor( { left, top }, positionedElementAncestor ) {
  273. const ancestorPosition = getAbsoluteRectCoordinates( new Rect( positionedElementAncestor ) );
  274. const ancestorBorderWidths = getBorderWidths( positionedElementAncestor );
  275. // (https://github.com/ckeditor/ckeditor5-ui-default/issues/126)
  276. // If there's some positioned ancestor of the panel, then its `Rect` must be taken into
  277. // consideration. `Rect` is always relative to the viewport while `position: absolute` works
  278. // with respect to that positioned ancestor.
  279. left -= ancestorPosition.left;
  280. top -= ancestorPosition.top;
  281. // (https://github.com/ckeditor/ckeditor5-utils/issues/139)
  282. // If there's some positioned ancestor of the panel, not only its position must be taken into
  283. // consideration (see above) but also its internal scrolls. Scroll have an impact here because `Rect`
  284. // is relative to the viewport (it doesn't care about scrolling), while `position: absolute`
  285. // must compensate that scrolling.
  286. left += positionedElementAncestor.scrollLeft;
  287. top += positionedElementAncestor.scrollTop;
  288. // (https://github.com/ckeditor/ckeditor5-utils/issues/139)
  289. // If there's some positioned ancestor of the panel, then its `Rect` includes its CSS `borderWidth`
  290. // while `position: absolute` positioning does not consider it.
  291. // E.g. `{ position: absolute, top: 0, left: 0 }` means upper left corner of the element,
  292. // not upper-left corner of its border.
  293. left -= ancestorBorderWidths.left;
  294. top -= ancestorBorderWidths.top;
  295. return { left, top };
  296. }
  297. // DOMRect (also Rect) works in a scroll–independent geometry but `position: absolute` doesn't.
  298. // This function converts Rect to `position: absolute` coordinates.
  299. //
  300. // @private
  301. // @param {utils/dom/rect~Rect} rect A rect to be converted.
  302. // @returns {Object} Object containing `left` and `top` properties, in absolute coordinates.
  303. function getAbsoluteRectCoordinates( { left, top } ) {
  304. const { scrollX, scrollY } = global.window;
  305. return {
  306. left: left + scrollX,
  307. top: top + scrollY
  308. };
  309. }
  310. /**
  311. * The `getOptimalPosition` helper options.
  312. *
  313. * @interface module:utils/dom/position~Options
  314. */
  315. /**
  316. * Element that is to be positioned.
  317. *
  318. * @member {HTMLElement} #element
  319. */
  320. /**
  321. * Target with respect to which the `element` is to be positioned.
  322. *
  323. * @member {HTMLElement|Range|ClientRect|Rect|Function} #target
  324. */
  325. /**
  326. * An array of functions which return {@link module:utils/dom/position~Position} relative
  327. * to the `target`, in the order of preference.
  328. *
  329. * @member {Array.<Function>} #positions
  330. */
  331. /**
  332. * When set, the algorithm will chose position which fits the most in the
  333. * limiter's bounding rect.
  334. *
  335. * @member {HTMLElement|Range|ClientRect|Rect|Function} #limiter
  336. */
  337. /**
  338. * When set, the algorithm will chose such a position which fits `element`
  339. * the most inside visible viewport.
  340. *
  341. * @member {Boolean} #fitInViewport
  342. */
  343. /**
  344. * An object describing a position in `position: absolute` coordinate
  345. * system, along with position name.
  346. *
  347. * @typedef {Object} module:utils/dom/position~Position
  348. *
  349. * @property {Number} top Top position offset.
  350. * @property {Number} left Left position offset.
  351. * @property {String} name Name of the position.
  352. */