rect.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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/rect
  7. */
  8. import isRange from './isrange';
  9. import isWindow from './iswindow';
  10. import getBorderWidths from './getborderwidths';
  11. import isText from './istext';
  12. import { isElement } from 'lodash-es';
  13. const rectProperties = [ 'top', 'right', 'bottom', 'left', 'width', 'height' ];
  14. /**
  15. * A helper class representing a `ClientRect` object, e.g. value returned by
  16. * the native `object.getBoundingClientRect()` method. Provides a set of methods
  17. * to manipulate the rect and compare it against other rect instances.
  18. */
  19. export default class Rect {
  20. /**
  21. * Creates an instance of rect.
  22. *
  23. * // Rect of an HTMLElement.
  24. * const rectA = new Rect( document.body );
  25. *
  26. * // Rect of a DOM Range.
  27. * const rectB = new Rect( document.getSelection().getRangeAt( 0 ) );
  28. *
  29. * // Rect of a window (web browser viewport).
  30. * const rectC = new Rect( window );
  31. *
  32. * // Rect out of an object.
  33. * const rectD = new Rect( { top: 0, right: 10, bottom: 10, left: 0, width: 10, height: 10 } );
  34. *
  35. * // Rect out of another Rect instance.
  36. * const rectE = new Rect( rectD );
  37. *
  38. * // Rect out of a ClientRect.
  39. * const rectF = new Rect( document.body.getClientRects().item( 0 ) );
  40. *
  41. * **Note**: By default a rect of an HTML element includes its CSS borders and scrollbars (if any)
  42. * ant the rect of a `window` includes scrollbars too. Use {@link #excludeScrollbarsAndBorders}
  43. * to get the inner part of the rect.
  44. *
  45. * @param {HTMLElement|Range|Window|ClientRect|module:utils/dom/rect~Rect|Object} source A source object to create the rect.
  46. */
  47. constructor( source ) {
  48. const isSourceRange = isRange( source );
  49. /**
  50. * The object this rect is for.
  51. *
  52. * @protected
  53. * @readonly
  54. * @member {HTMLElement|Range|ClientRect|module:utils/dom/rect~Rect|Object} #_source
  55. */
  56. Object.defineProperty( this, '_source', {
  57. // If the source is a Rect instance, copy it's #_source.
  58. value: source._source || source,
  59. writable: true,
  60. enumerable: false
  61. } );
  62. if ( isElement( source ) || isSourceRange ) {
  63. // The `Rect` class depends on `getBoundingClientRect` and `getClientRects` DOM methods. If the source
  64. // of a rect in an HTML element or a DOM range but it does not belong to any rendered DOM tree, these methods
  65. // will fail to obtain the geometry and the rect instance makes little sense to the features using it.
  66. // To get rid of this warning make sure the source passed to the constructor is a descendant of `window.document.body`.
  67. // @if CK_DEBUG // const sourceNode = isSourceRange ? source.startContainer : source;
  68. // @if CK_DEBUG // if ( !sourceNode.ownerDocument || !sourceNode.ownerDocument.body.contains( sourceNode ) ) {
  69. // @if CK_DEBUG // console.warn(
  70. // @if CK_DEBUG // 'rect-source-not-in-dom: The source of this rect does not belong to any rendered DOM tree.',
  71. // @if CK_DEBUG // { source } );
  72. // @if CK_DEBUG // }
  73. if ( isSourceRange ) {
  74. copyRectProperties( this, Rect.getDomRangeRects( source )[ 0 ] );
  75. } else {
  76. copyRectProperties( this, source.getBoundingClientRect() );
  77. }
  78. } else if ( isWindow( source ) ) {
  79. const { innerWidth, innerHeight } = source;
  80. copyRectProperties( this, {
  81. top: 0,
  82. right: innerWidth,
  83. bottom: innerHeight,
  84. left: 0,
  85. width: innerWidth,
  86. height: innerHeight
  87. } );
  88. } else {
  89. copyRectProperties( this, source );
  90. }
  91. /**
  92. * The "top" value of the rect.
  93. *
  94. * @readonly
  95. * @member {Number} #top
  96. */
  97. /**
  98. * The "right" value of the rect.
  99. *
  100. * @readonly
  101. * @member {Number} #right
  102. */
  103. /**
  104. * The "bottom" value of the rect.
  105. *
  106. * @readonly
  107. * @member {Number} #bottom
  108. */
  109. /**
  110. * The "left" value of the rect.
  111. *
  112. * @readonly
  113. * @member {Number} #left
  114. */
  115. /**
  116. * The "width" value of the rect.
  117. *
  118. * @readonly
  119. * @member {Number} #width
  120. */
  121. /**
  122. * The "height" value of the rect.
  123. *
  124. * @readonly
  125. * @member {Number} #height
  126. */
  127. }
  128. /**
  129. * Returns a clone of the rect.
  130. *
  131. * @returns {module:utils/dom/rect~Rect} A cloned rect.
  132. */
  133. clone() {
  134. return new Rect( this );
  135. }
  136. /**
  137. * Moves the rect so that its upper–left corner lands in desired `[ x, y ]` location.
  138. *
  139. * @param {Number} x Desired horizontal location.
  140. * @param {Number} y Desired vertical location.
  141. * @returns {module:utils/dom/rect~Rect} A rect which has been moved.
  142. */
  143. moveTo( x, y ) {
  144. this.top = y;
  145. this.right = x + this.width;
  146. this.bottom = y + this.height;
  147. this.left = x;
  148. return this;
  149. }
  150. /**
  151. * Moves the rect in–place by a dedicated offset.
  152. *
  153. * @param {Number} x A horizontal offset.
  154. * @param {Number} y A vertical offset
  155. * @returns {module:utils/dom/rect~Rect} A rect which has been moved.
  156. */
  157. moveBy( x, y ) {
  158. this.top += y;
  159. this.right += x;
  160. this.left += x;
  161. this.bottom += y;
  162. return this;
  163. }
  164. /**
  165. * Returns a new rect a a result of intersection with another rect.
  166. *
  167. * @param {module:utils/dom/rect~Rect} anotherRect
  168. * @returns {module:utils/dom/rect~Rect}
  169. */
  170. getIntersection( anotherRect ) {
  171. const rect = {
  172. top: Math.max( this.top, anotherRect.top ),
  173. right: Math.min( this.right, anotherRect.right ),
  174. bottom: Math.min( this.bottom, anotherRect.bottom ),
  175. left: Math.max( this.left, anotherRect.left )
  176. };
  177. rect.width = rect.right - rect.left;
  178. rect.height = rect.bottom - rect.top;
  179. if ( rect.width < 0 || rect.height < 0 ) {
  180. return null;
  181. } else {
  182. return new Rect( rect );
  183. }
  184. }
  185. /**
  186. * Returns the area of intersection with another rect.
  187. *
  188. * @param {module:utils/dom/rect~Rect} anotherRect [description]
  189. * @returns {Number} Area of intersection.
  190. */
  191. getIntersectionArea( anotherRect ) {
  192. const rect = this.getIntersection( anotherRect );
  193. if ( rect ) {
  194. return rect.getArea();
  195. } else {
  196. return 0;
  197. }
  198. }
  199. /**
  200. * Returns the area of the rect.
  201. *
  202. * @returns {Number}
  203. */
  204. getArea() {
  205. return this.width * this.height;
  206. }
  207. /**
  208. * Returns a new rect, a part of the original rect, which is actually visible to the user,
  209. * e.g. an original rect cropped by parent element rects which have `overflow` set in CSS
  210. * other than `"visible"`.
  211. *
  212. * If there's no such visible rect, which is when the rect is limited by one or many of
  213. * the ancestors, `null` is returned.
  214. *
  215. * @returns {module:utils/dom/rect~Rect|null} A visible rect instance or `null`, if there's none.
  216. */
  217. getVisible() {
  218. const source = this._source;
  219. let visibleRect = this.clone();
  220. // There's no ancestor to crop <body> with the overflow.
  221. if ( !isBody( source ) ) {
  222. let parent = source.parentNode || source.commonAncestorContainer;
  223. // Check the ancestors all the way up to the <body>.
  224. while ( parent && !isBody( parent ) ) {
  225. const parentRect = new Rect( parent );
  226. const intersectionRect = visibleRect.getIntersection( parentRect );
  227. if ( intersectionRect ) {
  228. if ( intersectionRect.getArea() < visibleRect.getArea() ) {
  229. // Reduce the visible rect to the intersection.
  230. visibleRect = intersectionRect;
  231. }
  232. } else {
  233. // There's no intersection, the rect is completely invisible.
  234. return null;
  235. }
  236. parent = parent.parentNode;
  237. }
  238. }
  239. return visibleRect;
  240. }
  241. /**
  242. * Checks if all property values ({@link #top}, {@link #left}, {@link #right},
  243. * {@link #bottom}, {@link #width} and {@link #height}) are the equal in both rect
  244. * instances.
  245. *
  246. * @param {module:utils/dom/rect~Rect} rect A rect instance to compare with.
  247. * @returns {Boolean} `true` when Rects are equal. `false` otherwise.
  248. */
  249. isEqual( anotherRect ) {
  250. for ( const prop of rectProperties ) {
  251. if ( this[ prop ] !== anotherRect[ prop ] ) {
  252. return false;
  253. }
  254. }
  255. return true;
  256. }
  257. /**
  258. * Checks whether a rect fully contains another rect instance.
  259. *
  260. * @param {module:utils/dom/rect~Rect} anotherRect
  261. * @returns {Boolean} `true` if contains, `false` otherwise.
  262. */
  263. contains( anotherRect ) {
  264. const intersectRect = this.getIntersection( anotherRect );
  265. return !!( intersectRect && intersectRect.isEqual( anotherRect ) );
  266. }
  267. /**
  268. * Excludes scrollbars and CSS borders from the rect.
  269. *
  270. * * Borders are removed when {@link #_source} is an HTML element.
  271. * * Scrollbars are excluded from HTML elements and the `window`.
  272. *
  273. * @returns {module:utils/dom/rect~Rect} A rect which has been updated.
  274. */
  275. excludeScrollbarsAndBorders() {
  276. const source = this._source;
  277. let scrollBarWidth, scrollBarHeight, direction;
  278. if ( isWindow( source ) ) {
  279. scrollBarWidth = source.innerWidth - source.document.documentElement.clientWidth;
  280. scrollBarHeight = source.innerHeight - source.document.documentElement.clientHeight;
  281. direction = source.getComputedStyle( source.document.documentElement ).direction;
  282. } else {
  283. const borderWidths = getBorderWidths( this._source );
  284. scrollBarWidth = source.offsetWidth - source.clientWidth - borderWidths.left - borderWidths.right;
  285. scrollBarHeight = source.offsetHeight - source.clientHeight - borderWidths.top - borderWidths.bottom;
  286. direction = source.ownerDocument.defaultView.getComputedStyle( source ).direction;
  287. this.left += borderWidths.left;
  288. this.top += borderWidths.top;
  289. this.right -= borderWidths.right;
  290. this.bottom -= borderWidths.bottom;
  291. this.width = this.right - this.left;
  292. this.height = this.bottom - this.top;
  293. }
  294. this.width -= scrollBarWidth;
  295. if ( direction === 'ltr' ) {
  296. this.right -= scrollBarWidth;
  297. } else {
  298. this.left += scrollBarWidth;
  299. }
  300. this.height -= scrollBarHeight;
  301. this.bottom -= scrollBarHeight;
  302. return this;
  303. }
  304. /**
  305. * Returns an array of rects of the given native DOM Range.
  306. *
  307. * @param {Range} range A native DOM range.
  308. * @returns {Array.<module:utils/dom/rect~Rect>} DOM Range rects.
  309. */
  310. static getDomRangeRects( range ) {
  311. const rects = [];
  312. // Safari does not iterate over ClientRectList using for...of loop.
  313. const clientRects = Array.from( range.getClientRects() );
  314. if ( clientRects.length ) {
  315. for ( const rect of clientRects ) {
  316. rects.push( new Rect( rect ) );
  317. }
  318. }
  319. // If there's no client rects for the Range, use parent container's bounding rect
  320. // instead and adjust rect's width to simulate the actual geometry of such range.
  321. // https://github.com/ckeditor/ckeditor5-utils/issues/153
  322. // https://github.com/ckeditor/ckeditor5-ui/issues/317
  323. else {
  324. let startContainer = range.startContainer;
  325. if ( isText( startContainer ) ) {
  326. startContainer = startContainer.parentNode;
  327. }
  328. const rect = new Rect( startContainer.getBoundingClientRect() );
  329. rect.right = rect.left;
  330. rect.width = 0;
  331. rects.push( rect );
  332. }
  333. return rects;
  334. }
  335. }
  336. // Acquires all the rect properties from the passed source.
  337. //
  338. // @private
  339. // @param {module:utils/dom/rect~Rect} rect
  340. // @param {ClientRect|module:utils/dom/rect~Rect|Object} source
  341. function copyRectProperties( rect, source ) {
  342. for ( const p of rectProperties ) {
  343. rect[ p ] = source[ p ];
  344. }
  345. }
  346. // Checks if provided object is a <body> HTML element.
  347. //
  348. // @private
  349. // @param {HTMLElement|Range} elementOrRange
  350. // @returns {Boolean}
  351. function isBody( elementOrRange ) {
  352. if ( !isElement( elementOrRange ) ) {
  353. return false;
  354. }
  355. return elementOrRange === elementOrRange.ownerDocument.body;
  356. }