8
0

rect.js 11 KB

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