ResizeObserver.es.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  1. /**
  2. * A collection of shims that provide minimal functionality of the ES6 collections.
  3. *
  4. * These implementations are not meant to be used outside of the ResizeObserver
  5. * modules as they cover only a limited range of use cases.
  6. */
  7. /* eslint-disable require-jsdoc, valid-jsdoc */
  8. var MapShim = (function () {
  9. if (typeof Map !== 'undefined') {
  10. return Map;
  11. }
  12. /**
  13. * Returns index in provided array that matches the specified key.
  14. *
  15. * @param {Array<Array>} arr
  16. * @param {*} key
  17. * @returns {number}
  18. */
  19. function getIndex(arr, key) {
  20. var result = -1;
  21. arr.some(function (entry, index) {
  22. if (entry[0] === key) {
  23. result = index;
  24. return true;
  25. }
  26. return false;
  27. });
  28. return result;
  29. }
  30. return /** @class */ (function () {
  31. function class_1() {
  32. this.__entries__ = [];
  33. }
  34. Object.defineProperty(class_1.prototype, "size", {
  35. /**
  36. * @returns {boolean}
  37. */
  38. get: function () {
  39. return this.__entries__.length;
  40. },
  41. enumerable: true,
  42. configurable: true
  43. });
  44. /**
  45. * @param {*} key
  46. * @returns {*}
  47. */
  48. class_1.prototype.get = function (key) {
  49. var index = getIndex(this.__entries__, key);
  50. var entry = this.__entries__[index];
  51. return entry && entry[1];
  52. };
  53. /**
  54. * @param {*} key
  55. * @param {*} value
  56. * @returns {void}
  57. */
  58. class_1.prototype.set = function (key, value) {
  59. var index = getIndex(this.__entries__, key);
  60. if (~index) {
  61. this.__entries__[index][1] = value;
  62. }
  63. else {
  64. this.__entries__.push([key, value]);
  65. }
  66. };
  67. /**
  68. * @param {*} key
  69. * @returns {void}
  70. */
  71. class_1.prototype.delete = function (key) {
  72. var entries = this.__entries__;
  73. var index = getIndex(entries, key);
  74. if (~index) {
  75. entries.splice(index, 1);
  76. }
  77. };
  78. /**
  79. * @param {*} key
  80. * @returns {void}
  81. */
  82. class_1.prototype.has = function (key) {
  83. return !!~getIndex(this.__entries__, key);
  84. };
  85. /**
  86. * @returns {void}
  87. */
  88. class_1.prototype.clear = function () {
  89. this.__entries__.splice(0);
  90. };
  91. /**
  92. * @param {Function} callback
  93. * @param {*} [ctx=null]
  94. * @returns {void}
  95. */
  96. class_1.prototype.forEach = function (callback, ctx) {
  97. if (ctx === void 0) { ctx = null; }
  98. for (var _i = 0, _a = this.__entries__; _i < _a.length; _i++) {
  99. var entry = _a[_i];
  100. callback.call(ctx, entry[1], entry[0]);
  101. }
  102. };
  103. return class_1;
  104. }());
  105. })();
  106. /**
  107. * Detects whether window and document objects are available in current environment.
  108. */
  109. var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && window.document === document;
  110. // Returns global object of a current environment.
  111. var global$1 = (function () {
  112. if (typeof global !== 'undefined' && global.Math === Math) {
  113. return global;
  114. }
  115. if (typeof self !== 'undefined' && self.Math === Math) {
  116. return self;
  117. }
  118. if (typeof window !== 'undefined' && window.Math === Math) {
  119. return window;
  120. }
  121. // eslint-disable-next-line no-new-func
  122. return Function('return this')();
  123. })();
  124. /**
  125. * A shim for the requestAnimationFrame which falls back to the setTimeout if
  126. * first one is not supported.
  127. *
  128. * @returns {number} Requests' identifier.
  129. */
  130. var requestAnimationFrame$1 = (function () {
  131. if (typeof requestAnimationFrame === 'function') {
  132. // It's required to use a bounded function because IE sometimes throws
  133. // an "Invalid calling object" error if rAF is invoked without the global
  134. // object on the left hand side.
  135. return requestAnimationFrame.bind(global$1);
  136. }
  137. return function (callback) { return setTimeout(function () { return callback(Date.now()); }, 1000 / 60); };
  138. })();
  139. // Defines minimum timeout before adding a trailing call.
  140. var trailingTimeout = 2;
  141. /**
  142. * Creates a wrapper function which ensures that provided callback will be
  143. * invoked only once during the specified delay period.
  144. *
  145. * @param {Function} callback - Function to be invoked after the delay period.
  146. * @param {number} delay - Delay after which to invoke callback.
  147. * @returns {Function}
  148. */
  149. function throttle (callback, delay) {
  150. var leadingCall = false, trailingCall = false, lastCallTime = 0;
  151. /**
  152. * Invokes the original callback function and schedules new invocation if
  153. * the "proxy" was called during current request.
  154. *
  155. * @returns {void}
  156. */
  157. function resolvePending() {
  158. if (leadingCall) {
  159. leadingCall = false;
  160. callback();
  161. }
  162. if (trailingCall) {
  163. proxy();
  164. }
  165. }
  166. /**
  167. * Callback invoked after the specified delay. It will further postpone
  168. * invocation of the original function delegating it to the
  169. * requestAnimationFrame.
  170. *
  171. * @returns {void}
  172. */
  173. function timeoutCallback() {
  174. requestAnimationFrame$1(resolvePending);
  175. }
  176. /**
  177. * Schedules invocation of the original function.
  178. *
  179. * @returns {void}
  180. */
  181. function proxy() {
  182. var timeStamp = Date.now();
  183. if (leadingCall) {
  184. // Reject immediately following calls.
  185. if (timeStamp - lastCallTime < trailingTimeout) {
  186. return;
  187. }
  188. // Schedule new call to be in invoked when the pending one is resolved.
  189. // This is important for "transitions" which never actually start
  190. // immediately so there is a chance that we might miss one if change
  191. // happens amids the pending invocation.
  192. trailingCall = true;
  193. }
  194. else {
  195. leadingCall = true;
  196. trailingCall = false;
  197. setTimeout(timeoutCallback, delay);
  198. }
  199. lastCallTime = timeStamp;
  200. }
  201. return proxy;
  202. }
  203. // Minimum delay before invoking the update of observers.
  204. var REFRESH_DELAY = 20;
  205. // A list of substrings of CSS properties used to find transition events that
  206. // might affect dimensions of observed elements.
  207. var transitionKeys = ['top', 'right', 'bottom', 'left', 'width', 'height', 'size', 'weight'];
  208. // Check if MutationObserver is available.
  209. var mutationObserverSupported = typeof MutationObserver !== 'undefined';
  210. /**
  211. * Singleton controller class which handles updates of ResizeObserver instances.
  212. */
  213. var ResizeObserverController = /** @class */ (function () {
  214. /**
  215. * Creates a new instance of ResizeObserverController.
  216. *
  217. * @private
  218. */
  219. function ResizeObserverController() {
  220. /**
  221. * Indicates whether DOM listeners have been added.
  222. *
  223. * @private {boolean}
  224. */
  225. this.connected_ = false;
  226. /**
  227. * Tells that controller has subscribed for Mutation Events.
  228. *
  229. * @private {boolean}
  230. */
  231. this.mutationEventsAdded_ = false;
  232. /**
  233. * Keeps reference to the instance of MutationObserver.
  234. *
  235. * @private {MutationObserver}
  236. */
  237. this.mutationsObserver_ = null;
  238. /**
  239. * A list of connected observers.
  240. *
  241. * @private {Array<ResizeObserverSPI>}
  242. */
  243. this.observers_ = [];
  244. this.onTransitionEnd_ = this.onTransitionEnd_.bind(this);
  245. this.refresh = throttle(this.refresh.bind(this), REFRESH_DELAY);
  246. }
  247. /**
  248. * Adds observer to observers list.
  249. *
  250. * @param {ResizeObserverSPI} observer - Observer to be added.
  251. * @returns {void}
  252. */
  253. ResizeObserverController.prototype.addObserver = function (observer) {
  254. if (!~this.observers_.indexOf(observer)) {
  255. this.observers_.push(observer);
  256. }
  257. // Add listeners if they haven't been added yet.
  258. if (!this.connected_) {
  259. this.connect_();
  260. }
  261. };
  262. /**
  263. * Removes observer from observers list.
  264. *
  265. * @param {ResizeObserverSPI} observer - Observer to be removed.
  266. * @returns {void}
  267. */
  268. ResizeObserverController.prototype.removeObserver = function (observer) {
  269. var observers = this.observers_;
  270. var index = observers.indexOf(observer);
  271. // Remove observer if it's present in registry.
  272. if (~index) {
  273. observers.splice(index, 1);
  274. }
  275. // Remove listeners if controller has no connected observers.
  276. if (!observers.length && this.connected_) {
  277. this.disconnect_();
  278. }
  279. };
  280. /**
  281. * Invokes the update of observers. It will continue running updates insofar
  282. * it detects changes.
  283. *
  284. * @returns {void}
  285. */
  286. ResizeObserverController.prototype.refresh = function () {
  287. var changesDetected = this.updateObservers_();
  288. // Continue running updates if changes have been detected as there might
  289. // be future ones caused by CSS transitions.
  290. if (changesDetected) {
  291. this.refresh();
  292. }
  293. };
  294. /**
  295. * Updates every observer from observers list and notifies them of queued
  296. * entries.
  297. *
  298. * @private
  299. * @returns {boolean} Returns "true" if any observer has detected changes in
  300. * dimensions of it's elements.
  301. */
  302. ResizeObserverController.prototype.updateObservers_ = function () {
  303. // Collect observers that have active observations.
  304. var activeObservers = this.observers_.filter(function (observer) {
  305. return observer.gatherActive(), observer.hasActive();
  306. });
  307. // Deliver notifications in a separate cycle in order to avoid any
  308. // collisions between observers, e.g. when multiple instances of
  309. // ResizeObserver are tracking the same element and the callback of one
  310. // of them changes content dimensions of the observed target. Sometimes
  311. // this may result in notifications being blocked for the rest of observers.
  312. activeObservers.forEach(function (observer) { return observer.broadcastActive(); });
  313. return activeObservers.length > 0;
  314. };
  315. /**
  316. * Initializes DOM listeners.
  317. *
  318. * @private
  319. * @returns {void}
  320. */
  321. ResizeObserverController.prototype.connect_ = function () {
  322. // Do nothing if running in a non-browser environment or if listeners
  323. // have been already added.
  324. if (!isBrowser || this.connected_) {
  325. return;
  326. }
  327. // Subscription to the "Transitionend" event is used as a workaround for
  328. // delayed transitions. This way it's possible to capture at least the
  329. // final state of an element.
  330. document.addEventListener('transitionend', this.onTransitionEnd_);
  331. window.addEventListener('resize', this.refresh);
  332. if (mutationObserverSupported) {
  333. this.mutationsObserver_ = new MutationObserver(this.refresh);
  334. this.mutationsObserver_.observe(document, {
  335. attributes: true,
  336. childList: true,
  337. characterData: true,
  338. subtree: true
  339. });
  340. }
  341. else {
  342. document.addEventListener('DOMSubtreeModified', this.refresh);
  343. this.mutationEventsAdded_ = true;
  344. }
  345. this.connected_ = true;
  346. };
  347. /**
  348. * Removes DOM listeners.
  349. *
  350. * @private
  351. * @returns {void}
  352. */
  353. ResizeObserverController.prototype.disconnect_ = function () {
  354. // Do nothing if running in a non-browser environment or if listeners
  355. // have been already removed.
  356. if (!isBrowser || !this.connected_) {
  357. return;
  358. }
  359. document.removeEventListener('transitionend', this.onTransitionEnd_);
  360. window.removeEventListener('resize', this.refresh);
  361. if (this.mutationsObserver_) {
  362. this.mutationsObserver_.disconnect();
  363. }
  364. if (this.mutationEventsAdded_) {
  365. document.removeEventListener('DOMSubtreeModified', this.refresh);
  366. }
  367. this.mutationsObserver_ = null;
  368. this.mutationEventsAdded_ = false;
  369. this.connected_ = false;
  370. };
  371. /**
  372. * "Transitionend" event handler.
  373. *
  374. * @private
  375. * @param {TransitionEvent} event
  376. * @returns {void}
  377. */
  378. ResizeObserverController.prototype.onTransitionEnd_ = function (_a) {
  379. var _b = _a.propertyName, propertyName = _b === void 0 ? '' : _b;
  380. // Detect whether transition may affect dimensions of an element.
  381. var isReflowProperty = transitionKeys.some(function (key) {
  382. return !!~propertyName.indexOf(key);
  383. });
  384. if (isReflowProperty) {
  385. this.refresh();
  386. }
  387. };
  388. /**
  389. * Returns instance of the ResizeObserverController.
  390. *
  391. * @returns {ResizeObserverController}
  392. */
  393. ResizeObserverController.getInstance = function () {
  394. if (!this.instance_) {
  395. this.instance_ = new ResizeObserverController();
  396. }
  397. return this.instance_;
  398. };
  399. /**
  400. * Holds reference to the controller's instance.
  401. *
  402. * @private {ResizeObserverController}
  403. */
  404. ResizeObserverController.instance_ = null;
  405. return ResizeObserverController;
  406. }());
  407. /**
  408. * Defines non-writable/enumerable properties of the provided target object.
  409. *
  410. * @param {Object} target - Object for which to define properties.
  411. * @param {Object} props - Properties to be defined.
  412. * @returns {Object} Target object.
  413. */
  414. var defineConfigurable = (function (target, props) {
  415. for (var _i = 0, _a = Object.keys(props); _i < _a.length; _i++) {
  416. var key = _a[_i];
  417. Object.defineProperty(target, key, {
  418. value: props[key],
  419. enumerable: false,
  420. writable: false,
  421. configurable: true
  422. });
  423. }
  424. return target;
  425. });
  426. /**
  427. * Returns the global object associated with provided element.
  428. *
  429. * @param {Object} target
  430. * @returns {Object}
  431. */
  432. var getWindowOf = (function (target) {
  433. // Assume that the element is an instance of Node, which means that it
  434. // has the "ownerDocument" property from which we can retrieve a
  435. // corresponding global object.
  436. var ownerGlobal = target && target.ownerDocument && target.ownerDocument.defaultView;
  437. // Return the local global object if it's not possible extract one from
  438. // provided element.
  439. return ownerGlobal || global$1;
  440. });
  441. // Placeholder of an empty content rectangle.
  442. var emptyRect = createRectInit(0, 0, 0, 0);
  443. /**
  444. * Converts provided string to a number.
  445. *
  446. * @param {number|string} value
  447. * @returns {number}
  448. */
  449. function toFloat(value) {
  450. return parseFloat(value) || 0;
  451. }
  452. /**
  453. * Extracts borders size from provided styles.
  454. *
  455. * @param {CSSStyleDeclaration} styles
  456. * @param {...string} positions - Borders positions (top, right, ...)
  457. * @returns {number}
  458. */
  459. function getBordersSize(styles) {
  460. var positions = [];
  461. for (var _i = 1; _i < arguments.length; _i++) {
  462. positions[_i - 1] = arguments[_i];
  463. }
  464. return positions.reduce(function (size, position) {
  465. var value = styles['border-' + position + '-width'];
  466. return size + toFloat(value);
  467. }, 0);
  468. }
  469. /**
  470. * Extracts paddings sizes from provided styles.
  471. *
  472. * @param {CSSStyleDeclaration} styles
  473. * @returns {Object} Paddings box.
  474. */
  475. function getPaddings(styles) {
  476. var positions = ['top', 'right', 'bottom', 'left'];
  477. var paddings = {};
  478. for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) {
  479. var position = positions_1[_i];
  480. var value = styles['padding-' + position];
  481. paddings[position] = toFloat(value);
  482. }
  483. return paddings;
  484. }
  485. /**
  486. * Calculates content rectangle of provided SVG element.
  487. *
  488. * @param {SVGGraphicsElement} target - Element content rectangle of which needs
  489. * to be calculated.
  490. * @returns {DOMRectInit}
  491. */
  492. function getSVGContentRect(target) {
  493. var bbox = target.getBBox();
  494. return createRectInit(0, 0, bbox.width, bbox.height);
  495. }
  496. /**
  497. * Calculates content rectangle of provided HTMLElement.
  498. *
  499. * @param {HTMLElement} target - Element for which to calculate the content rectangle.
  500. * @returns {DOMRectInit}
  501. */
  502. function getHTMLElementContentRect(target) {
  503. // Client width & height properties can't be
  504. // used exclusively as they provide rounded values.
  505. var clientWidth = target.clientWidth, clientHeight = target.clientHeight;
  506. // By this condition we can catch all non-replaced inline, hidden and
  507. // detached elements. Though elements with width & height properties less
  508. // than 0.5 will be discarded as well.
  509. //
  510. // Without it we would need to implement separate methods for each of
  511. // those cases and it's not possible to perform a precise and performance
  512. // effective test for hidden elements. E.g. even jQuery's ':visible' filter
  513. // gives wrong results for elements with width & height less than 0.5.
  514. if (!clientWidth && !clientHeight) {
  515. return emptyRect;
  516. }
  517. var styles = getWindowOf(target).getComputedStyle(target);
  518. var paddings = getPaddings(styles);
  519. var horizPad = paddings.left + paddings.right;
  520. var vertPad = paddings.top + paddings.bottom;
  521. // Computed styles of width & height are being used because they are the
  522. // only dimensions available to JS that contain non-rounded values. It could
  523. // be possible to utilize the getBoundingClientRect if only it's data wasn't
  524. // affected by CSS transformations let alone paddings, borders and scroll bars.
  525. var width = toFloat(styles.width), height = toFloat(styles.height);
  526. // Width & height include paddings and borders when the 'border-box' box
  527. // model is applied (except for IE).
  528. if (styles.boxSizing === 'border-box') {
  529. // Following conditions are required to handle Internet Explorer which
  530. // doesn't include paddings and borders to computed CSS dimensions.
  531. //
  532. // We can say that if CSS dimensions + paddings are equal to the "client"
  533. // properties then it's either IE, and thus we don't need to subtract
  534. // anything, or an element merely doesn't have paddings/borders styles.
  535. if (Math.round(width + horizPad) !== clientWidth) {
  536. width -= getBordersSize(styles, 'left', 'right') + horizPad;
  537. }
  538. if (Math.round(height + vertPad) !== clientHeight) {
  539. height -= getBordersSize(styles, 'top', 'bottom') + vertPad;
  540. }
  541. }
  542. // Following steps can't be applied to the document's root element as its
  543. // client[Width/Height] properties represent viewport area of the window.
  544. // Besides, it's as well not necessary as the <html> itself neither has
  545. // rendered scroll bars nor it can be clipped.
  546. if (!isDocumentElement(target)) {
  547. // In some browsers (only in Firefox, actually) CSS width & height
  548. // include scroll bars size which can be removed at this step as scroll
  549. // bars are the only difference between rounded dimensions + paddings
  550. // and "client" properties, though that is not always true in Chrome.
  551. var vertScrollbar = Math.round(width + horizPad) - clientWidth;
  552. var horizScrollbar = Math.round(height + vertPad) - clientHeight;
  553. // Chrome has a rather weird rounding of "client" properties.
  554. // E.g. for an element with content width of 314.2px it sometimes gives
  555. // the client width of 315px and for the width of 314.7px it may give
  556. // 314px. And it doesn't happen all the time. So just ignore this delta
  557. // as a non-relevant.
  558. if (Math.abs(vertScrollbar) !== 1) {
  559. width -= vertScrollbar;
  560. }
  561. if (Math.abs(horizScrollbar) !== 1) {
  562. height -= horizScrollbar;
  563. }
  564. }
  565. return createRectInit(paddings.left, paddings.top, width, height);
  566. }
  567. /**
  568. * Checks whether provided element is an instance of the SVGGraphicsElement.
  569. *
  570. * @param {Element} target - Element to be checked.
  571. * @returns {boolean}
  572. */
  573. var isSVGGraphicsElement = (function () {
  574. // Some browsers, namely IE and Edge, don't have the SVGGraphicsElement
  575. // interface.
  576. if (typeof SVGGraphicsElement !== 'undefined') {
  577. return function (target) { return target instanceof getWindowOf(target).SVGGraphicsElement; };
  578. }
  579. // If it's so, then check that element is at least an instance of the
  580. // SVGElement and that it has the "getBBox" method.
  581. // eslint-disable-next-line no-extra-parens
  582. return function (target) { return (target instanceof getWindowOf(target).SVGElement &&
  583. typeof target.getBBox === 'function'); };
  584. })();
  585. /**
  586. * Checks whether provided element is a document element (<html>).
  587. *
  588. * @param {Element} target - Element to be checked.
  589. * @returns {boolean}
  590. */
  591. function isDocumentElement(target) {
  592. return target === getWindowOf(target).document.documentElement;
  593. }
  594. /**
  595. * Calculates an appropriate content rectangle for provided html or svg element.
  596. *
  597. * @param {Element} target - Element content rectangle of which needs to be calculated.
  598. * @returns {DOMRectInit}
  599. */
  600. function getContentRect(target) {
  601. if (!isBrowser) {
  602. return emptyRect;
  603. }
  604. if (isSVGGraphicsElement(target)) {
  605. return getSVGContentRect(target);
  606. }
  607. return getHTMLElementContentRect(target);
  608. }
  609. /**
  610. * Creates rectangle with an interface of the DOMRectReadOnly.
  611. * Spec: https://drafts.fxtf.org/geometry/#domrectreadonly
  612. *
  613. * @param {DOMRectInit} rectInit - Object with rectangle's x/y coordinates and dimensions.
  614. * @returns {DOMRectReadOnly}
  615. */
  616. function createReadOnlyRect(_a) {
  617. var x = _a.x, y = _a.y, width = _a.width, height = _a.height;
  618. // If DOMRectReadOnly is available use it as a prototype for the rectangle.
  619. var Constr = typeof DOMRectReadOnly !== 'undefined' ? DOMRectReadOnly : Object;
  620. var rect = Object.create(Constr.prototype);
  621. // Rectangle's properties are not writable and non-enumerable.
  622. defineConfigurable(rect, {
  623. x: x, y: y, width: width, height: height,
  624. top: y,
  625. right: x + width,
  626. bottom: height + y,
  627. left: x
  628. });
  629. return rect;
  630. }
  631. /**
  632. * Creates DOMRectInit object based on the provided dimensions and the x/y coordinates.
  633. * Spec: https://drafts.fxtf.org/geometry/#dictdef-domrectinit
  634. *
  635. * @param {number} x - X coordinate.
  636. * @param {number} y - Y coordinate.
  637. * @param {number} width - Rectangle's width.
  638. * @param {number} height - Rectangle's height.
  639. * @returns {DOMRectInit}
  640. */
  641. function createRectInit(x, y, width, height) {
  642. return { x: x, y: y, width: width, height: height };
  643. }
  644. /**
  645. * Class that is responsible for computations of the content rectangle of
  646. * provided DOM element and for keeping track of it's changes.
  647. */
  648. var ResizeObservation = /** @class */ (function () {
  649. /**
  650. * Creates an instance of ResizeObservation.
  651. *
  652. * @param {Element} target - Element to be observed.
  653. */
  654. function ResizeObservation(target) {
  655. /**
  656. * Broadcasted width of content rectangle.
  657. *
  658. * @type {number}
  659. */
  660. this.broadcastWidth = 0;
  661. /**
  662. * Broadcasted height of content rectangle.
  663. *
  664. * @type {number}
  665. */
  666. this.broadcastHeight = 0;
  667. /**
  668. * Reference to the last observed content rectangle.
  669. *
  670. * @private {DOMRectInit}
  671. */
  672. this.contentRect_ = createRectInit(0, 0, 0, 0);
  673. this.target = target;
  674. }
  675. /**
  676. * Updates content rectangle and tells whether it's width or height properties
  677. * have changed since the last broadcast.
  678. *
  679. * @returns {boolean}
  680. */
  681. ResizeObservation.prototype.isActive = function () {
  682. var rect = getContentRect(this.target);
  683. this.contentRect_ = rect;
  684. return (rect.width !== this.broadcastWidth ||
  685. rect.height !== this.broadcastHeight);
  686. };
  687. /**
  688. * Updates 'broadcastWidth' and 'broadcastHeight' properties with a data
  689. * from the corresponding properties of the last observed content rectangle.
  690. *
  691. * @returns {DOMRectInit} Last observed content rectangle.
  692. */
  693. ResizeObservation.prototype.broadcastRect = function () {
  694. var rect = this.contentRect_;
  695. this.broadcastWidth = rect.width;
  696. this.broadcastHeight = rect.height;
  697. return rect;
  698. };
  699. return ResizeObservation;
  700. }());
  701. var ResizeObserverEntry = /** @class */ (function () {
  702. /**
  703. * Creates an instance of ResizeObserverEntry.
  704. *
  705. * @param {Element} target - Element that is being observed.
  706. * @param {DOMRectInit} rectInit - Data of the element's content rectangle.
  707. */
  708. function ResizeObserverEntry(target, rectInit) {
  709. var contentRect = createReadOnlyRect(rectInit);
  710. // According to the specification following properties are not writable
  711. // and are also not enumerable in the native implementation.
  712. //
  713. // Property accessors are not being used as they'd require to define a
  714. // private WeakMap storage which may cause memory leaks in browsers that
  715. // don't support this type of collections.
  716. defineConfigurable(this, { target: target, contentRect: contentRect });
  717. }
  718. return ResizeObserverEntry;
  719. }());
  720. var ResizeObserverSPI = /** @class */ (function () {
  721. /**
  722. * Creates a new instance of ResizeObserver.
  723. *
  724. * @param {ResizeObserverCallback} callback - Callback function that is invoked
  725. * when one of the observed elements changes it's content dimensions.
  726. * @param {ResizeObserverController} controller - Controller instance which
  727. * is responsible for the updates of observer.
  728. * @param {ResizeObserver} callbackCtx - Reference to the public
  729. * ResizeObserver instance which will be passed to callback function.
  730. */
  731. function ResizeObserverSPI(callback, controller, callbackCtx) {
  732. /**
  733. * Collection of resize observations that have detected changes in dimensions
  734. * of elements.
  735. *
  736. * @private {Array<ResizeObservation>}
  737. */
  738. this.activeObservations_ = [];
  739. /**
  740. * Registry of the ResizeObservation instances.
  741. *
  742. * @private {Map<Element, ResizeObservation>}
  743. */
  744. this.observations_ = new MapShim();
  745. if (typeof callback !== 'function') {
  746. throw new TypeError('The callback provided as parameter 1 is not a function.');
  747. }
  748. this.callback_ = callback;
  749. this.controller_ = controller;
  750. this.callbackCtx_ = callbackCtx;
  751. }
  752. /**
  753. * Starts observing provided element.
  754. *
  755. * @param {Element} target - Element to be observed.
  756. * @returns {void}
  757. */
  758. ResizeObserverSPI.prototype.observe = function (target) {
  759. if (!arguments.length) {
  760. throw new TypeError('1 argument required, but only 0 present.');
  761. }
  762. // Do nothing if current environment doesn't have the Element interface.
  763. if (typeof Element === 'undefined' || !(Element instanceof Object)) {
  764. return;
  765. }
  766. if (!(target instanceof getWindowOf(target).Element)) {
  767. throw new TypeError('parameter 1 is not of type "Element".');
  768. }
  769. var observations = this.observations_;
  770. // Do nothing if element is already being observed.
  771. if (observations.has(target)) {
  772. return;
  773. }
  774. observations.set(target, new ResizeObservation(target));
  775. this.controller_.addObserver(this);
  776. // Force the update of observations.
  777. this.controller_.refresh();
  778. };
  779. /**
  780. * Stops observing provided element.
  781. *
  782. * @param {Element} target - Element to stop observing.
  783. * @returns {void}
  784. */
  785. ResizeObserverSPI.prototype.unobserve = function (target) {
  786. if (!arguments.length) {
  787. throw new TypeError('1 argument required, but only 0 present.');
  788. }
  789. // Do nothing if current environment doesn't have the Element interface.
  790. if (typeof Element === 'undefined' || !(Element instanceof Object)) {
  791. return;
  792. }
  793. if (!(target instanceof getWindowOf(target).Element)) {
  794. throw new TypeError('parameter 1 is not of type "Element".');
  795. }
  796. var observations = this.observations_;
  797. // Do nothing if element is not being observed.
  798. if (!observations.has(target)) {
  799. return;
  800. }
  801. observations.delete(target);
  802. if (!observations.size) {
  803. this.controller_.removeObserver(this);
  804. }
  805. };
  806. /**
  807. * Stops observing all elements.
  808. *
  809. * @returns {void}
  810. */
  811. ResizeObserverSPI.prototype.disconnect = function () {
  812. this.clearActive();
  813. this.observations_.clear();
  814. this.controller_.removeObserver(this);
  815. };
  816. /**
  817. * Collects observation instances the associated element of which has changed
  818. * it's content rectangle.
  819. *
  820. * @returns {void}
  821. */
  822. ResizeObserverSPI.prototype.gatherActive = function () {
  823. var _this = this;
  824. this.clearActive();
  825. this.observations_.forEach(function (observation) {
  826. if (observation.isActive()) {
  827. _this.activeObservations_.push(observation);
  828. }
  829. });
  830. };
  831. /**
  832. * Invokes initial callback function with a list of ResizeObserverEntry
  833. * instances collected from active resize observations.
  834. *
  835. * @returns {void}
  836. */
  837. ResizeObserverSPI.prototype.broadcastActive = function () {
  838. // Do nothing if observer doesn't have active observations.
  839. if (!this.hasActive()) {
  840. return;
  841. }
  842. var ctx = this.callbackCtx_;
  843. // Create ResizeObserverEntry instance for every active observation.
  844. var entries = this.activeObservations_.map(function (observation) {
  845. return new ResizeObserverEntry(observation.target, observation.broadcastRect());
  846. });
  847. this.callback_.call(ctx, entries, ctx);
  848. this.clearActive();
  849. };
  850. /**
  851. * Clears the collection of active observations.
  852. *
  853. * @returns {void}
  854. */
  855. ResizeObserverSPI.prototype.clearActive = function () {
  856. this.activeObservations_.splice(0);
  857. };
  858. /**
  859. * Tells whether observer has active observations.
  860. *
  861. * @returns {boolean}
  862. */
  863. ResizeObserverSPI.prototype.hasActive = function () {
  864. return this.activeObservations_.length > 0;
  865. };
  866. return ResizeObserverSPI;
  867. }());
  868. // Registry of internal observers. If WeakMap is not available use current shim
  869. // for the Map collection as it has all required methods and because WeakMap
  870. // can't be fully polyfilled anyway.
  871. var observers = typeof WeakMap !== 'undefined' ? new WeakMap() : new MapShim();
  872. /**
  873. * ResizeObserver API. Encapsulates the ResizeObserver SPI implementation
  874. * exposing only those methods and properties that are defined in the spec.
  875. */
  876. var ResizeObserver = /** @class */ (function () {
  877. /**
  878. * Creates a new instance of ResizeObserver.
  879. *
  880. * @param {ResizeObserverCallback} callback - Callback that is invoked when
  881. * dimensions of the observed elements change.
  882. */
  883. function ResizeObserver(callback) {
  884. if (!(this instanceof ResizeObserver)) {
  885. throw new TypeError('Cannot call a class as a function.');
  886. }
  887. if (!arguments.length) {
  888. throw new TypeError('1 argument required, but only 0 present.');
  889. }
  890. var controller = ResizeObserverController.getInstance();
  891. var observer = new ResizeObserverSPI(callback, controller, this);
  892. observers.set(this, observer);
  893. }
  894. return ResizeObserver;
  895. }());
  896. // Expose public methods of ResizeObserver.
  897. [
  898. 'observe',
  899. 'unobserve',
  900. 'disconnect'
  901. ].forEach(function (method) {
  902. ResizeObserver.prototype[method] = function () {
  903. var _a;
  904. return (_a = observers.get(this))[method].apply(_a, arguments);
  905. };
  906. });
  907. var index = (function () {
  908. // Export existing implementation if available.
  909. if (typeof global$1.ResizeObserver !== 'undefined') {
  910. return global$1.ResizeObserver;
  911. }
  912. return ResizeObserver;
  913. })();
  914. export default index;