8
0

rect.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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. const rangeRects = Rect.getDomRangeRects( source );
  75. copyRectProperties( this, Rect.getBoundingRect( rangeRects ) );
  76. } else {
  77. copyRectProperties( this, source.getBoundingClientRect() );
  78. }
  79. } else if ( isWindow( source ) ) {
  80. const { innerWidth, innerHeight } = source;
  81. copyRectProperties( this, {
  82. top: 0,
  83. right: innerWidth,
  84. bottom: innerHeight,
  85. left: 0,
  86. width: innerWidth,
  87. height: innerHeight
  88. } );
  89. } else {
  90. copyRectProperties( this, source );
  91. }
  92. /**
  93. * The "top" value of the rect.
  94. *
  95. * @readonly
  96. * @member {Number} #top
  97. */
  98. /**
  99. * The "right" value of the rect.
  100. *
  101. * @readonly
  102. * @member {Number} #right
  103. */
  104. /**
  105. * The "bottom" value of the rect.
  106. *
  107. * @readonly
  108. * @member {Number} #bottom
  109. */
  110. /**
  111. * The "left" value of the rect.
  112. *
  113. * @readonly
  114. * @member {Number} #left
  115. */
  116. /**
  117. * The "width" value of the rect.
  118. *
  119. * @readonly
  120. * @member {Number} #width
  121. */
  122. /**
  123. * The "height" value of the rect.
  124. *
  125. * @readonly
  126. * @member {Number} #height
  127. */
  128. }
  129. /**
  130. * Returns a clone of the rect.
  131. *
  132. * @returns {module:utils/dom/rect~Rect} A cloned rect.
  133. */
  134. clone() {
  135. return new Rect( this );
  136. }
  137. /**
  138. * Moves the rect so that its upper–left corner lands in desired `[ x, y ]` location.
  139. *
  140. * @param {Number} x Desired horizontal location.
  141. * @param {Number} y Desired vertical location.
  142. * @returns {module:utils/dom/rect~Rect} A rect which has been moved.
  143. */
  144. moveTo( x, y ) {
  145. this.top = y;
  146. this.right = x + this.width;
  147. this.bottom = y + this.height;
  148. this.left = x;
  149. return this;
  150. }
  151. /**
  152. * Moves the rect in–place by a dedicated offset.
  153. *
  154. * @param {Number} x A horizontal offset.
  155. * @param {Number} y A vertical offset
  156. * @returns {module:utils/dom/rect~Rect} A rect which has been moved.
  157. */
  158. moveBy( x, y ) {
  159. this.top += y;
  160. this.right += x;
  161. this.left += x;
  162. this.bottom += y;
  163. return this;
  164. }
  165. /**
  166. * Returns a new rect a a result of intersection with another rect.
  167. *
  168. * @param {module:utils/dom/rect~Rect} anotherRect
  169. * @returns {module:utils/dom/rect~Rect}
  170. */
  171. getIntersection( anotherRect ) {
  172. const rect = {
  173. top: Math.max( this.top, anotherRect.top ),
  174. right: Math.min( this.right, anotherRect.right ),
  175. bottom: Math.min( this.bottom, anotherRect.bottom ),
  176. left: Math.max( this.left, anotherRect.left )
  177. };
  178. rect.width = rect.right - rect.left;
  179. rect.height = rect.bottom - rect.top;
  180. if ( rect.width < 0 || rect.height < 0 ) {
  181. return null;
  182. } else {
  183. return new Rect( rect );
  184. }
  185. }
  186. /**
  187. * Returns the area of intersection with another rect.
  188. *
  189. * @param {module:utils/dom/rect~Rect} anotherRect [description]
  190. * @returns {Number} Area of intersection.
  191. */
  192. getIntersectionArea( anotherRect ) {
  193. const rect = this.getIntersection( anotherRect );
  194. if ( rect ) {
  195. return rect.getArea();
  196. } else {
  197. return 0;
  198. }
  199. }
  200. /**
  201. * Returns the area of the rect.
  202. *
  203. * @returns {Number}
  204. */
  205. getArea() {
  206. return this.width * this.height;
  207. }
  208. /**
  209. * Returns a new rect, a part of the original rect, which is actually visible to the user,
  210. * e.g. an original rect cropped by parent element rects which have `overflow` set in CSS
  211. * other than `"visible"`.
  212. *
  213. * If there's no such visible rect, which is when the rect is limited by one or many of
  214. * the ancestors, `null` is returned.
  215. *
  216. * @returns {module:utils/dom/rect~Rect|null} A visible rect instance or `null`, if there's none.
  217. */
  218. getVisible() {
  219. const source = this._source;
  220. let visibleRect = this.clone();
  221. // There's no ancestor to crop <body> with the overflow.
  222. if ( !isBody( source ) ) {
  223. let parent = source.parentNode || source.commonAncestorContainer;
  224. // Check the ancestors all the way up to the <body>.
  225. while ( parent && !isBody( parent ) ) {
  226. const parentRect = new Rect( parent );
  227. const intersectionRect = visibleRect.getIntersection( parentRect );
  228. if ( intersectionRect ) {
  229. if ( intersectionRect.getArea() < visibleRect.getArea() ) {
  230. // Reduce the visible rect to the intersection.
  231. visibleRect = intersectionRect;
  232. }
  233. } else {
  234. // There's no intersection, the rect is completely invisible.
  235. return null;
  236. }
  237. parent = parent.parentNode;
  238. }
  239. }
  240. return visibleRect;
  241. }
  242. /**
  243. * Checks if all property values ({@link #top}, {@link #left}, {@link #right},
  244. * {@link #bottom}, {@link #width} and {@link #height}) are the equal in both rect
  245. * instances.
  246. *
  247. * @param {module:utils/dom/rect~Rect} rect A rect instance to compare with.
  248. * @returns {Boolean} `true` when Rects are equal. `false` otherwise.
  249. */
  250. isEqual( anotherRect ) {
  251. for ( const prop of rectProperties ) {
  252. if ( this[ prop ] !== anotherRect[ prop ] ) {
  253. return false;
  254. }
  255. }
  256. return true;
  257. }
  258. /**
  259. * Checks whether a rect fully contains another rect instance.
  260. *
  261. * @param {module:utils/dom/rect~Rect} anotherRect
  262. * @returns {Boolean} `true` if contains, `false` otherwise.
  263. */
  264. contains( anotherRect ) {
  265. const intersectRect = this.getIntersection( anotherRect );
  266. return !!( intersectRect && intersectRect.isEqual( anotherRect ) );
  267. }
  268. /**
  269. * Excludes scrollbars and CSS borders from the rect.
  270. *
  271. * * Borders are removed when {@link #_source} is an HTML element.
  272. * * Scrollbars are excluded from HTML elements and the `window`.
  273. *
  274. * @returns {module:utils/dom/rect~Rect} A rect which has been updated.
  275. */
  276. excludeScrollbarsAndBorders() {
  277. const source = this._source;
  278. let scrollBarWidth, scrollBarHeight, direction;
  279. if ( isWindow( source ) ) {
  280. scrollBarWidth = source.innerWidth - source.document.documentElement.clientWidth;
  281. scrollBarHeight = source.innerHeight - source.document.documentElement.clientHeight;
  282. direction = source.getComputedStyle( source.document.documentElement ).direction;
  283. } else {
  284. const borderWidths = getBorderWidths( this._source );
  285. scrollBarWidth = source.offsetWidth - source.clientWidth - borderWidths.left - borderWidths.right;
  286. scrollBarHeight = source.offsetHeight - source.clientHeight - borderWidths.top - borderWidths.bottom;
  287. direction = source.ownerDocument.defaultView.getComputedStyle( source ).direction;
  288. this.left += borderWidths.left;
  289. this.top += borderWidths.top;
  290. this.right -= borderWidths.right;
  291. this.bottom -= borderWidths.bottom;
  292. this.width = this.right - this.left;
  293. this.height = this.bottom - this.top;
  294. }
  295. this.width -= scrollBarWidth;
  296. if ( direction === 'ltr' ) {
  297. this.right -= scrollBarWidth;
  298. } else {
  299. this.left += scrollBarWidth;
  300. }
  301. this.height -= scrollBarHeight;
  302. this.bottom -= scrollBarHeight;
  303. return this;
  304. }
  305. /**
  306. * Returns an array of rects of the given native DOM Range.
  307. *
  308. * @param {Range} range A native DOM range.
  309. * @returns {Array.<module:utils/dom/rect~Rect>} DOM Range rects.
  310. */
  311. static getDomRangeRects( range ) {
  312. const rects = [];
  313. // Safari does not iterate over ClientRectList using for...of loop.
  314. const clientRects = Array.from( range.getClientRects() );
  315. if ( clientRects.length ) {
  316. for ( const rect of clientRects ) {
  317. rects.push( new Rect( rect ) );
  318. }
  319. }
  320. // If there's no client rects for the Range, use parent container's bounding rect
  321. // instead and adjust rect's width to simulate the actual geometry of such range.
  322. // https://github.com/ckeditor/ckeditor5-utils/issues/153
  323. // https://github.com/ckeditor/ckeditor5-ui/issues/317
  324. else {
  325. let startContainer = range.startContainer;
  326. if ( isText( startContainer ) ) {
  327. startContainer = startContainer.parentNode;
  328. }
  329. const rect = new Rect( startContainer.getBoundingClientRect() );
  330. rect.right = rect.left;
  331. rect.width = 0;
  332. rects.push( rect );
  333. }
  334. return rects;
  335. }
  336. /**
  337. * Returns a bounding rectangle that contains all the given `rects`.
  338. *
  339. * @param {Iterable.<module:utils/dom/rect~Rect>} rects A list of rectangles that should be contained in the result rectangle.
  340. * @returns {module:utils/dom/rect~Rect|null} Bounding rectangle or `null` if no `rects` were given.
  341. */
  342. static getBoundingRect( rects ) {
  343. const boundingRectData = {
  344. left: Number.POSITIVE_INFINITY,
  345. top: Number.POSITIVE_INFINITY,
  346. right: Number.NEGATIVE_INFINITY,
  347. bottom: Number.NEGATIVE_INFINITY
  348. };
  349. let rectangleCount = 0;
  350. for ( const rect of rects ) {
  351. rectangleCount++;
  352. boundingRectData.left = Math.min( boundingRectData.left, rect.left );
  353. boundingRectData.top = Math.min( boundingRectData.top, rect.top );
  354. boundingRectData.right = Math.max( boundingRectData.right, rect.right );
  355. boundingRectData.bottom = Math.max( boundingRectData.bottom, rect.bottom );
  356. }
  357. if ( rectangleCount == 0 ) {
  358. return null;
  359. }
  360. boundingRectData.width = boundingRectData.right - boundingRectData.left;
  361. boundingRectData.height = boundingRectData.bottom - boundingRectData.top;
  362. return new Rect( boundingRectData );
  363. }
  364. }
  365. // Acquires all the rect properties from the passed source.
  366. //
  367. // @private
  368. // @param {module:utils/dom/rect~Rect} rect
  369. // @param {ClientRect|module:utils/dom/rect~Rect|Object} source
  370. function copyRectProperties( rect, source ) {
  371. for ( const p of rectProperties ) {
  372. rect[ p ] = source[ p ];
  373. }
  374. }
  375. // Checks if provided object is a <body> HTML element.
  376. //
  377. // @private
  378. // @param {HTMLElement|Range} elementOrRange
  379. // @returns {Boolean}
  380. function isBody( elementOrRange ) {
  381. if ( !isElement( elementOrRange ) ) {
  382. return false;
  383. }
  384. return elementOrRange === elementOrRange.ownerDocument.body;
  385. }