🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

use-element-fit

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

use-element-fit - npm Package Compare versions

Comparing version
0.1.0
to
0.2.0
+1107
dist/index.bundle.js
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
(global = global || self, factory(global.useElementFit = {}, global.react));
}(this, function (exports, react) { 'use strict';
var ScaleMode;
(function (ScaleMode) {
ScaleMode["CONTAIN"] = "contain";
ScaleMode["COVER"] = "cover";
ScaleMode["ALIGN_ONLY"] = "align-only";
})(ScaleMode || (ScaleMode = {}));
var ScaleMode$1 = ScaleMode;
/**
* A collection of shims that provide minimal functionality of the ES6 collections.
*
* These implementations are not meant to be used outside of the ResizeObserver
* modules as they cover only a limited range of use cases.
*/
/* eslint-disable require-jsdoc, valid-jsdoc */
var MapShim = (function () {
if (typeof Map !== 'undefined') {
return Map;
}
/**
* Returns index in provided array that matches the specified key.
*
* @param {Array<Array>} arr
* @param {*} key
* @returns {number}
*/
function getIndex(arr, key) {
var result = -1;
arr.some(function (entry, index) {
if (entry[0] === key) {
result = index;
return true;
}
return false;
});
return result;
}
return /** @class */ (function () {
function class_1() {
this.__entries__ = [];
}
Object.defineProperty(class_1.prototype, "size", {
/**
* @returns {boolean}
*/
get: function () {
return this.__entries__.length;
},
enumerable: true,
configurable: true
});
/**
* @param {*} key
* @returns {*}
*/
class_1.prototype.get = function (key) {
var index = getIndex(this.__entries__, key);
var entry = this.__entries__[index];
return entry && entry[1];
};
/**
* @param {*} key
* @param {*} value
* @returns {void}
*/
class_1.prototype.set = function (key, value) {
var index = getIndex(this.__entries__, key);
if (~index) {
this.__entries__[index][1] = value;
}
else {
this.__entries__.push([key, value]);
}
};
/**
* @param {*} key
* @returns {void}
*/
class_1.prototype.delete = function (key) {
var entries = this.__entries__;
var index = getIndex(entries, key);
if (~index) {
entries.splice(index, 1);
}
};
/**
* @param {*} key
* @returns {void}
*/
class_1.prototype.has = function (key) {
return !!~getIndex(this.__entries__, key);
};
/**
* @returns {void}
*/
class_1.prototype.clear = function () {
this.__entries__.splice(0);
};
/**
* @param {Function} callback
* @param {*} [ctx=null]
* @returns {void}
*/
class_1.prototype.forEach = function (callback, ctx) {
if (ctx === void 0) { ctx = null; }
for (var _i = 0, _a = this.__entries__; _i < _a.length; _i++) {
var entry = _a[_i];
callback.call(ctx, entry[1], entry[0]);
}
};
return class_1;
}());
})();
/**
* Detects whether window and document objects are available in current environment.
*/
var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && window.document === document;
// Returns global object of a current environment.
var global$1 = (function () {
if (typeof global !== 'undefined' && global.Math === Math) {
return global;
}
if (typeof self !== 'undefined' && self.Math === Math) {
return self;
}
if (typeof window !== 'undefined' && window.Math === Math) {
return window;
}
// eslint-disable-next-line no-new-func
return Function('return this')();
})();
/**
* A shim for the requestAnimationFrame which falls back to the setTimeout if
* first one is not supported.
*
* @returns {number} Requests' identifier.
*/
var requestAnimationFrame$1 = (function () {
if (typeof requestAnimationFrame === 'function') {
// It's required to use a bounded function because IE sometimes throws
// an "Invalid calling object" error if rAF is invoked without the global
// object on the left hand side.
return requestAnimationFrame.bind(global$1);
}
return function (callback) { return setTimeout(function () { return callback(Date.now()); }, 1000 / 60); };
})();
// Defines minimum timeout before adding a trailing call.
var trailingTimeout = 2;
/**
* Creates a wrapper function which ensures that provided callback will be
* invoked only once during the specified delay period.
*
* @param {Function} callback - Function to be invoked after the delay period.
* @param {number} delay - Delay after which to invoke callback.
* @returns {Function}
*/
function throttle (callback, delay) {
var leadingCall = false, trailingCall = false, lastCallTime = 0;
/**
* Invokes the original callback function and schedules new invocation if
* the "proxy" was called during current request.
*
* @returns {void}
*/
function resolvePending() {
if (leadingCall) {
leadingCall = false;
callback();
}
if (trailingCall) {
proxy();
}
}
/**
* Callback invoked after the specified delay. It will further postpone
* invocation of the original function delegating it to the
* requestAnimationFrame.
*
* @returns {void}
*/
function timeoutCallback() {
requestAnimationFrame$1(resolvePending);
}
/**
* Schedules invocation of the original function.
*
* @returns {void}
*/
function proxy() {
var timeStamp = Date.now();
if (leadingCall) {
// Reject immediately following calls.
if (timeStamp - lastCallTime < trailingTimeout) {
return;
}
// Schedule new call to be in invoked when the pending one is resolved.
// This is important for "transitions" which never actually start
// immediately so there is a chance that we might miss one if change
// happens amids the pending invocation.
trailingCall = true;
}
else {
leadingCall = true;
trailingCall = false;
setTimeout(timeoutCallback, delay);
}
lastCallTime = timeStamp;
}
return proxy;
}
// Minimum delay before invoking the update of observers.
var REFRESH_DELAY = 20;
// A list of substrings of CSS properties used to find transition events that
// might affect dimensions of observed elements.
var transitionKeys = ['top', 'right', 'bottom', 'left', 'width', 'height', 'size', 'weight'];
// Check if MutationObserver is available.
var mutationObserverSupported = typeof MutationObserver !== 'undefined';
/**
* Singleton controller class which handles updates of ResizeObserver instances.
*/
var ResizeObserverController = /** @class */ (function () {
/**
* Creates a new instance of ResizeObserverController.
*
* @private
*/
function ResizeObserverController() {
/**
* Indicates whether DOM listeners have been added.
*
* @private {boolean}
*/
this.connected_ = false;
/**
* Tells that controller has subscribed for Mutation Events.
*
* @private {boolean}
*/
this.mutationEventsAdded_ = false;
/**
* Keeps reference to the instance of MutationObserver.
*
* @private {MutationObserver}
*/
this.mutationsObserver_ = null;
/**
* A list of connected observers.
*
* @private {Array<ResizeObserverSPI>}
*/
this.observers_ = [];
this.onTransitionEnd_ = this.onTransitionEnd_.bind(this);
this.refresh = throttle(this.refresh.bind(this), REFRESH_DELAY);
}
/**
* Adds observer to observers list.
*
* @param {ResizeObserverSPI} observer - Observer to be added.
* @returns {void}
*/
ResizeObserverController.prototype.addObserver = function (observer) {
if (!~this.observers_.indexOf(observer)) {
this.observers_.push(observer);
}
// Add listeners if they haven't been added yet.
if (!this.connected_) {
this.connect_();
}
};
/**
* Removes observer from observers list.
*
* @param {ResizeObserverSPI} observer - Observer to be removed.
* @returns {void}
*/
ResizeObserverController.prototype.removeObserver = function (observer) {
var observers = this.observers_;
var index = observers.indexOf(observer);
// Remove observer if it's present in registry.
if (~index) {
observers.splice(index, 1);
}
// Remove listeners if controller has no connected observers.
if (!observers.length && this.connected_) {
this.disconnect_();
}
};
/**
* Invokes the update of observers. It will continue running updates insofar
* it detects changes.
*
* @returns {void}
*/
ResizeObserverController.prototype.refresh = function () {
var changesDetected = this.updateObservers_();
// Continue running updates if changes have been detected as there might
// be future ones caused by CSS transitions.
if (changesDetected) {
this.refresh();
}
};
/**
* Updates every observer from observers list and notifies them of queued
* entries.
*
* @private
* @returns {boolean} Returns "true" if any observer has detected changes in
* dimensions of it's elements.
*/
ResizeObserverController.prototype.updateObservers_ = function () {
// Collect observers that have active observations.
var activeObservers = this.observers_.filter(function (observer) {
return observer.gatherActive(), observer.hasActive();
});
// Deliver notifications in a separate cycle in order to avoid any
// collisions between observers, e.g. when multiple instances of
// ResizeObserver are tracking the same element and the callback of one
// of them changes content dimensions of the observed target. Sometimes
// this may result in notifications being blocked for the rest of observers.
activeObservers.forEach(function (observer) { return observer.broadcastActive(); });
return activeObservers.length > 0;
};
/**
* Initializes DOM listeners.
*
* @private
* @returns {void}
*/
ResizeObserverController.prototype.connect_ = function () {
// Do nothing if running in a non-browser environment or if listeners
// have been already added.
if (!isBrowser || this.connected_) {
return;
}
// Subscription to the "Transitionend" event is used as a workaround for
// delayed transitions. This way it's possible to capture at least the
// final state of an element.
document.addEventListener('transitionend', this.onTransitionEnd_);
window.addEventListener('resize', this.refresh);
if (mutationObserverSupported) {
this.mutationsObserver_ = new MutationObserver(this.refresh);
this.mutationsObserver_.observe(document, {
attributes: true,
childList: true,
characterData: true,
subtree: true
});
}
else {
document.addEventListener('DOMSubtreeModified', this.refresh);
this.mutationEventsAdded_ = true;
}
this.connected_ = true;
};
/**
* Removes DOM listeners.
*
* @private
* @returns {void}
*/
ResizeObserverController.prototype.disconnect_ = function () {
// Do nothing if running in a non-browser environment or if listeners
// have been already removed.
if (!isBrowser || !this.connected_) {
return;
}
document.removeEventListener('transitionend', this.onTransitionEnd_);
window.removeEventListener('resize', this.refresh);
if (this.mutationsObserver_) {
this.mutationsObserver_.disconnect();
}
if (this.mutationEventsAdded_) {
document.removeEventListener('DOMSubtreeModified', this.refresh);
}
this.mutationsObserver_ = null;
this.mutationEventsAdded_ = false;
this.connected_ = false;
};
/**
* "Transitionend" event handler.
*
* @private
* @param {TransitionEvent} event
* @returns {void}
*/
ResizeObserverController.prototype.onTransitionEnd_ = function (_a) {
var _b = _a.propertyName, propertyName = _b === void 0 ? '' : _b;
// Detect whether transition may affect dimensions of an element.
var isReflowProperty = transitionKeys.some(function (key) {
return !!~propertyName.indexOf(key);
});
if (isReflowProperty) {
this.refresh();
}
};
/**
* Returns instance of the ResizeObserverController.
*
* @returns {ResizeObserverController}
*/
ResizeObserverController.getInstance = function () {
if (!this.instance_) {
this.instance_ = new ResizeObserverController();
}
return this.instance_;
};
/**
* Holds reference to the controller's instance.
*
* @private {ResizeObserverController}
*/
ResizeObserverController.instance_ = null;
return ResizeObserverController;
}());
/**
* Defines non-writable/enumerable properties of the provided target object.
*
* @param {Object} target - Object for which to define properties.
* @param {Object} props - Properties to be defined.
* @returns {Object} Target object.
*/
var defineConfigurable = (function (target, props) {
for (var _i = 0, _a = Object.keys(props); _i < _a.length; _i++) {
var key = _a[_i];
Object.defineProperty(target, key, {
value: props[key],
enumerable: false,
writable: false,
configurable: true
});
}
return target;
});
/**
* Returns the global object associated with provided element.
*
* @param {Object} target
* @returns {Object}
*/
var getWindowOf = (function (target) {
// Assume that the element is an instance of Node, which means that it
// has the "ownerDocument" property from which we can retrieve a
// corresponding global object.
var ownerGlobal = target && target.ownerDocument && target.ownerDocument.defaultView;
// Return the local global object if it's not possible extract one from
// provided element.
return ownerGlobal || global$1;
});
// Placeholder of an empty content rectangle.
var emptyRect = createRectInit(0, 0, 0, 0);
/**
* Converts provided string to a number.
*
* @param {number|string} value
* @returns {number}
*/
function toFloat(value) {
return parseFloat(value) || 0;
}
/**
* Extracts borders size from provided styles.
*
* @param {CSSStyleDeclaration} styles
* @param {...string} positions - Borders positions (top, right, ...)
* @returns {number}
*/
function getBordersSize(styles) {
var positions = [];
for (var _i = 1; _i < arguments.length; _i++) {
positions[_i - 1] = arguments[_i];
}
return positions.reduce(function (size, position) {
var value = styles['border-' + position + '-width'];
return size + toFloat(value);
}, 0);
}
/**
* Extracts paddings sizes from provided styles.
*
* @param {CSSStyleDeclaration} styles
* @returns {Object} Paddings box.
*/
function getPaddings(styles) {
var positions = ['top', 'right', 'bottom', 'left'];
var paddings = {};
for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) {
var position = positions_1[_i];
var value = styles['padding-' + position];
paddings[position] = toFloat(value);
}
return paddings;
}
/**
* Calculates content rectangle of provided SVG element.
*
* @param {SVGGraphicsElement} target - Element content rectangle of which needs
* to be calculated.
* @returns {DOMRectInit}
*/
function getSVGContentRect(target) {
var bbox = target.getBBox();
return createRectInit(0, 0, bbox.width, bbox.height);
}
/**
* Calculates content rectangle of provided HTMLElement.
*
* @param {HTMLElement} target - Element for which to calculate the content rectangle.
* @returns {DOMRectInit}
*/
function getHTMLElementContentRect(target) {
// Client width & height properties can't be
// used exclusively as they provide rounded values.
var clientWidth = target.clientWidth, clientHeight = target.clientHeight;
// By this condition we can catch all non-replaced inline, hidden and
// detached elements. Though elements with width & height properties less
// than 0.5 will be discarded as well.
//
// Without it we would need to implement separate methods for each of
// those cases and it's not possible to perform a precise and performance
// effective test for hidden elements. E.g. even jQuery's ':visible' filter
// gives wrong results for elements with width & height less than 0.5.
if (!clientWidth && !clientHeight) {
return emptyRect;
}
var styles = getWindowOf(target).getComputedStyle(target);
var paddings = getPaddings(styles);
var horizPad = paddings.left + paddings.right;
var vertPad = paddings.top + paddings.bottom;
// Computed styles of width & height are being used because they are the
// only dimensions available to JS that contain non-rounded values. It could
// be possible to utilize the getBoundingClientRect if only it's data wasn't
// affected by CSS transformations let alone paddings, borders and scroll bars.
var width = toFloat(styles.width), height = toFloat(styles.height);
// Width & height include paddings and borders when the 'border-box' box
// model is applied (except for IE).
if (styles.boxSizing === 'border-box') {
// Following conditions are required to handle Internet Explorer which
// doesn't include paddings and borders to computed CSS dimensions.
//
// We can say that if CSS dimensions + paddings are equal to the "client"
// properties then it's either IE, and thus we don't need to subtract
// anything, or an element merely doesn't have paddings/borders styles.
if (Math.round(width + horizPad) !== clientWidth) {
width -= getBordersSize(styles, 'left', 'right') + horizPad;
}
if (Math.round(height + vertPad) !== clientHeight) {
height -= getBordersSize(styles, 'top', 'bottom') + vertPad;
}
}
// Following steps can't be applied to the document's root element as its
// client[Width/Height] properties represent viewport area of the window.
// Besides, it's as well not necessary as the <html> itself neither has
// rendered scroll bars nor it can be clipped.
if (!isDocumentElement(target)) {
// In some browsers (only in Firefox, actually) CSS width & height
// include scroll bars size which can be removed at this step as scroll
// bars are the only difference between rounded dimensions + paddings
// and "client" properties, though that is not always true in Chrome.
var vertScrollbar = Math.round(width + horizPad) - clientWidth;
var horizScrollbar = Math.round(height + vertPad) - clientHeight;
// Chrome has a rather weird rounding of "client" properties.
// E.g. for an element with content width of 314.2px it sometimes gives
// the client width of 315px and for the width of 314.7px it may give
// 314px. And it doesn't happen all the time. So just ignore this delta
// as a non-relevant.
if (Math.abs(vertScrollbar) !== 1) {
width -= vertScrollbar;
}
if (Math.abs(horizScrollbar) !== 1) {
height -= horizScrollbar;
}
}
return createRectInit(paddings.left, paddings.top, width, height);
}
/**
* Checks whether provided element is an instance of the SVGGraphicsElement.
*
* @param {Element} target - Element to be checked.
* @returns {boolean}
*/
var isSVGGraphicsElement = (function () {
// Some browsers, namely IE and Edge, don't have the SVGGraphicsElement
// interface.
if (typeof SVGGraphicsElement !== 'undefined') {
return function (target) { return target instanceof getWindowOf(target).SVGGraphicsElement; };
}
// If it's so, then check that element is at least an instance of the
// SVGElement and that it has the "getBBox" method.
// eslint-disable-next-line no-extra-parens
return function (target) { return (target instanceof getWindowOf(target).SVGElement &&
typeof target.getBBox === 'function'); };
})();
/**
* Checks whether provided element is a document element (<html>).
*
* @param {Element} target - Element to be checked.
* @returns {boolean}
*/
function isDocumentElement(target) {
return target === getWindowOf(target).document.documentElement;
}
/**
* Calculates an appropriate content rectangle for provided html or svg element.
*
* @param {Element} target - Element content rectangle of which needs to be calculated.
* @returns {DOMRectInit}
*/
function getContentRect(target) {
if (!isBrowser) {
return emptyRect;
}
if (isSVGGraphicsElement(target)) {
return getSVGContentRect(target);
}
return getHTMLElementContentRect(target);
}
/**
* Creates rectangle with an interface of the DOMRectReadOnly.
* Spec: https://drafts.fxtf.org/geometry/#domrectreadonly
*
* @param {DOMRectInit} rectInit - Object with rectangle's x/y coordinates and dimensions.
* @returns {DOMRectReadOnly}
*/
function createReadOnlyRect(_a) {
var x = _a.x, y = _a.y, width = _a.width, height = _a.height;
// If DOMRectReadOnly is available use it as a prototype for the rectangle.
var Constr = typeof DOMRectReadOnly !== 'undefined' ? DOMRectReadOnly : Object;
var rect = Object.create(Constr.prototype);
// Rectangle's properties are not writable and non-enumerable.
defineConfigurable(rect, {
x: x, y: y, width: width, height: height,
top: y,
right: x + width,
bottom: height + y,
left: x
});
return rect;
}
/**
* Creates DOMRectInit object based on the provided dimensions and the x/y coordinates.
* Spec: https://drafts.fxtf.org/geometry/#dictdef-domrectinit
*
* @param {number} x - X coordinate.
* @param {number} y - Y coordinate.
* @param {number} width - Rectangle's width.
* @param {number} height - Rectangle's height.
* @returns {DOMRectInit}
*/
function createRectInit(x, y, width, height) {
return { x: x, y: y, width: width, height: height };
}
/**
* Class that is responsible for computations of the content rectangle of
* provided DOM element and for keeping track of it's changes.
*/
var ResizeObservation = /** @class */ (function () {
/**
* Creates an instance of ResizeObservation.
*
* @param {Element} target - Element to be observed.
*/
function ResizeObservation(target) {
/**
* Broadcasted width of content rectangle.
*
* @type {number}
*/
this.broadcastWidth = 0;
/**
* Broadcasted height of content rectangle.
*
* @type {number}
*/
this.broadcastHeight = 0;
/**
* Reference to the last observed content rectangle.
*
* @private {DOMRectInit}
*/
this.contentRect_ = createRectInit(0, 0, 0, 0);
this.target = target;
}
/**
* Updates content rectangle and tells whether it's width or height properties
* have changed since the last broadcast.
*
* @returns {boolean}
*/
ResizeObservation.prototype.isActive = function () {
var rect = getContentRect(this.target);
this.contentRect_ = rect;
return (rect.width !== this.broadcastWidth ||
rect.height !== this.broadcastHeight);
};
/**
* Updates 'broadcastWidth' and 'broadcastHeight' properties with a data
* from the corresponding properties of the last observed content rectangle.
*
* @returns {DOMRectInit} Last observed content rectangle.
*/
ResizeObservation.prototype.broadcastRect = function () {
var rect = this.contentRect_;
this.broadcastWidth = rect.width;
this.broadcastHeight = rect.height;
return rect;
};
return ResizeObservation;
}());
var ResizeObserverEntry = /** @class */ (function () {
/**
* Creates an instance of ResizeObserverEntry.
*
* @param {Element} target - Element that is being observed.
* @param {DOMRectInit} rectInit - Data of the element's content rectangle.
*/
function ResizeObserverEntry(target, rectInit) {
var contentRect = createReadOnlyRect(rectInit);
// According to the specification following properties are not writable
// and are also not enumerable in the native implementation.
//
// Property accessors are not being used as they'd require to define a
// private WeakMap storage which may cause memory leaks in browsers that
// don't support this type of collections.
defineConfigurable(this, { target: target, contentRect: contentRect });
}
return ResizeObserverEntry;
}());
var ResizeObserverSPI = /** @class */ (function () {
/**
* Creates a new instance of ResizeObserver.
*
* @param {ResizeObserverCallback} callback - Callback function that is invoked
* when one of the observed elements changes it's content dimensions.
* @param {ResizeObserverController} controller - Controller instance which
* is responsible for the updates of observer.
* @param {ResizeObserver} callbackCtx - Reference to the public
* ResizeObserver instance which will be passed to callback function.
*/
function ResizeObserverSPI(callback, controller, callbackCtx) {
/**
* Collection of resize observations that have detected changes in dimensions
* of elements.
*
* @private {Array<ResizeObservation>}
*/
this.activeObservations_ = [];
/**
* Registry of the ResizeObservation instances.
*
* @private {Map<Element, ResizeObservation>}
*/
this.observations_ = new MapShim();
if (typeof callback !== 'function') {
throw new TypeError('The callback provided as parameter 1 is not a function.');
}
this.callback_ = callback;
this.controller_ = controller;
this.callbackCtx_ = callbackCtx;
}
/**
* Starts observing provided element.
*
* @param {Element} target - Element to be observed.
* @returns {void}
*/
ResizeObserverSPI.prototype.observe = function (target) {
if (!arguments.length) {
throw new TypeError('1 argument required, but only 0 present.');
}
// Do nothing if current environment doesn't have the Element interface.
if (typeof Element === 'undefined' || !(Element instanceof Object)) {
return;
}
if (!(target instanceof getWindowOf(target).Element)) {
throw new TypeError('parameter 1 is not of type "Element".');
}
var observations = this.observations_;
// Do nothing if element is already being observed.
if (observations.has(target)) {
return;
}
observations.set(target, new ResizeObservation(target));
this.controller_.addObserver(this);
// Force the update of observations.
this.controller_.refresh();
};
/**
* Stops observing provided element.
*
* @param {Element} target - Element to stop observing.
* @returns {void}
*/
ResizeObserverSPI.prototype.unobserve = function (target) {
if (!arguments.length) {
throw new TypeError('1 argument required, but only 0 present.');
}
// Do nothing if current environment doesn't have the Element interface.
if (typeof Element === 'undefined' || !(Element instanceof Object)) {
return;
}
if (!(target instanceof getWindowOf(target).Element)) {
throw new TypeError('parameter 1 is not of type "Element".');
}
var observations = this.observations_;
// Do nothing if element is not being observed.
if (!observations.has(target)) {
return;
}
observations.delete(target);
if (!observations.size) {
this.controller_.removeObserver(this);
}
};
/**
* Stops observing all elements.
*
* @returns {void}
*/
ResizeObserverSPI.prototype.disconnect = function () {
this.clearActive();
this.observations_.clear();
this.controller_.removeObserver(this);
};
/**
* Collects observation instances the associated element of which has changed
* it's content rectangle.
*
* @returns {void}
*/
ResizeObserverSPI.prototype.gatherActive = function () {
var _this = this;
this.clearActive();
this.observations_.forEach(function (observation) {
if (observation.isActive()) {
_this.activeObservations_.push(observation);
}
});
};
/**
* Invokes initial callback function with a list of ResizeObserverEntry
* instances collected from active resize observations.
*
* @returns {void}
*/
ResizeObserverSPI.prototype.broadcastActive = function () {
// Do nothing if observer doesn't have active observations.
if (!this.hasActive()) {
return;
}
var ctx = this.callbackCtx_;
// Create ResizeObserverEntry instance for every active observation.
var entries = this.activeObservations_.map(function (observation) {
return new ResizeObserverEntry(observation.target, observation.broadcastRect());
});
this.callback_.call(ctx, entries, ctx);
this.clearActive();
};
/**
* Clears the collection of active observations.
*
* @returns {void}
*/
ResizeObserverSPI.prototype.clearActive = function () {
this.activeObservations_.splice(0);
};
/**
* Tells whether observer has active observations.
*
* @returns {boolean}
*/
ResizeObserverSPI.prototype.hasActive = function () {
return this.activeObservations_.length > 0;
};
return ResizeObserverSPI;
}());
// Registry of internal observers. If WeakMap is not available use current shim
// for the Map collection as it has all required methods and because WeakMap
// can't be fully polyfilled anyway.
var observers = typeof WeakMap !== 'undefined' ? new WeakMap() : new MapShim();
/**
* ResizeObserver API. Encapsulates the ResizeObserver SPI implementation
* exposing only those methods and properties that are defined in the spec.
*/
var ResizeObserver = /** @class */ (function () {
/**
* Creates a new instance of ResizeObserver.
*
* @param {ResizeObserverCallback} callback - Callback that is invoked when
* dimensions of the observed elements change.
*/
function ResizeObserver(callback) {
if (!(this instanceof ResizeObserver)) {
throw new TypeError('Cannot call a class as a function.');
}
if (!arguments.length) {
throw new TypeError('1 argument required, but only 0 present.');
}
var controller = ResizeObserverController.getInstance();
var observer = new ResizeObserverSPI(callback, controller, this);
observers.set(this, observer);
}
return ResizeObserver;
}());
// Expose public methods of ResizeObserver.
[
'observe',
'unobserve',
'disconnect'
].forEach(function (method) {
ResizeObserver.prototype[method] = function () {
var _a;
return (_a = observers.get(this))[method].apply(_a, arguments);
};
});
var index = (function () {
// Export existing implementation if available.
if (typeof global$1.ResizeObserver !== 'undefined') {
return global$1.ResizeObserver;
}
return ResizeObserver;
})();
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
function index$1 () {
var ref = react.useRef();
var _useState = react.useState(1),
_useState2 = _slicedToArray(_useState, 2),
width = _useState2[0],
changeWidth = _useState2[1];
var _useState3 = react.useState(1),
_useState4 = _slicedToArray(_useState3, 2),
height = _useState4[0],
changeHeight = _useState4[1];
react.useEffect(function () {
var element = ref.current;
var resizeObserver = new index(function (entries) {
if (!Array.isArray(entries)) {
return;
} // Since we only observe the one element, we don't need to loop over the
// array
if (!entries.length) {
return;
}
var entry = entries[0];
changeWidth(entry.contentRect.width);
changeHeight(entry.contentRect.height);
});
resizeObserver.observe(element);
return function () {
return resizeObserver.unobserve(element);
};
}, []);
return [ref, width, height];
}
const resize = (elementWidth, elementHeight, containerWidth, containerHeight, scaleMode, alignmentX = 0.5, alignmentY = 0.5, maxWidth, maxHeight) => {
let targetWidth = 0;
let targetHeight = 0;
let boundRatioX = 0;
let boundRatioY = 0;
let scale = 1;
// get needed scale to fit in bounds with cover
if (scaleMode === ScaleMode$1.CONTAIN || scaleMode === ScaleMode$1.COVER) {
boundRatioX = containerWidth / elementWidth;
boundRatioY = containerHeight / elementHeight;
}
// get scale for bounds container
switch (scaleMode) {
case ScaleMode$1.CONTAIN:
scale = boundRatioX < boundRatioY ? boundRatioX : boundRatioY;
break;
case ScaleMode$1.COVER:
scale = boundRatioX > boundRatioY ? boundRatioX : boundRatioY;
break;
case ScaleMode$1.ALIGN_ONLY:
targetWidth = elementWidth;
targetHeight = elementHeight;
break;
}
if (scaleMode === ScaleMode$1.CONTAIN || scaleMode === ScaleMode$1.COVER) {
// get needed scale to fit in max with contain
if (maxWidth || maxHeight) {
let scaleMaxRatioX = scale;
let scaleMaxRatioY = scale;
if (maxWidth) {
scaleMaxRatioX = maxWidth / elementWidth;
}
if (maxHeight) {
scaleMaxRatioY = maxHeight / elementHeight;
}
const scaleMax = scaleMaxRatioX < scaleMaxRatioY ? scaleMaxRatioX : scaleMaxRatioY;
scale = Math.min(scale, scaleMax);
}
// do the actual scale
targetWidth = elementWidth * scale;
targetHeight = elementHeight * scale;
}
return {
width: Math.round(targetWidth),
height: Math.round(targetHeight),
x: Math.round((containerWidth - targetWidth) * alignmentX),
y: Math.round((containerHeight - targetHeight) * alignmentY),
};
};
const useElementFit = (width, height, scaleMode = ScaleMode$1.CONTAIN, alignmentX = 0.5, alignmentY = 0.5, maxWidth, maxHeight) => {
const [ref, containerWidth, containerHeight] = index$1();
const [fitWidth, setFitWidth] = react.useState(1);
const [fitHeight, setFitHeight] = react.useState(1);
const [fitX, setFitX] = react.useState(1);
const [fitY, setFitY] = react.useState(1);
react.useEffect(() => {
const { width: newWidth, height: newHeight, x, y } = resize(width, height, containerWidth, containerHeight, scaleMode, alignmentX, alignmentY, maxWidth, maxHeight);
setFitWidth(newWidth);
setFitHeight(newHeight);
setFitX(x);
setFitY(y);
}, [
containerWidth,
containerHeight,
width,
height,
containerWidth,
containerHeight,
scaleMode,
alignmentX,
alignmentY,
maxWidth,
maxHeight,
]);
return {
ref,
width: fitWidth,
height: fitHeight,
x: fitX,
y: fitY,
};
};
exports.ScaleMode = ScaleMode$1;
exports.useElementFit = useElementFit;
Object.defineProperty(exports, '__esModule', { value: true });
}));
//# sourceMappingURL=index.bundle.js.map

Sorry, the diff of this file is too big to display

!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],e):e((t=t||self).useElementFit={},t.react)}(this,function(t,e){"use strict";var n;!function(t){t.CONTAIN="contain",t.COVER="cover",t.ALIGN_ONLY="align-only"}(n||(n={}));var r=n,i=function(){if("undefined"!=typeof Map)return Map;function t(t,e){var n=-1;return t.some(function(t,r){return t[0]===e&&(n=r,!0)}),n}return function(){function e(){this.__entries__=[]}return Object.defineProperty(e.prototype,"size",{get:function(){return this.__entries__.length},enumerable:!0,configurable:!0}),e.prototype.get=function(e){var n=t(this.__entries__,e),r=this.__entries__[n];return r&&r[1]},e.prototype.set=function(e,n){var r=t(this.__entries__,e);~r?this.__entries__[r][1]=n:this.__entries__.push([e,n])},e.prototype.delete=function(e){var n=this.__entries__,r=t(n,e);~r&&n.splice(r,1)},e.prototype.has=function(e){return!!~t(this.__entries__,e)},e.prototype.clear=function(){this.__entries__.splice(0)},e.prototype.forEach=function(t,e){void 0===e&&(e=null);for(var n=0,r=this.__entries__;n<r.length;n++){var i=r[n];t.call(e,i[1],i[0])}},e}()}(),o="undefined"!=typeof window&&"undefined"!=typeof document&&window.document===document,s="undefined"!=typeof global&&global.Math===Math?global:"undefined"!=typeof self&&self.Math===Math?self:"undefined"!=typeof window&&window.Math===Math?window:Function("return this")(),a="function"==typeof requestAnimationFrame?requestAnimationFrame.bind(s):function(t){return setTimeout(function(){return t(Date.now())},1e3/60)},c=2;var u=20,h=["top","right","bottom","left","width","height","size","weight"],f="undefined"!=typeof MutationObserver,d=function(){function t(){this.connected_=!1,this.mutationEventsAdded_=!1,this.mutationsObserver_=null,this.observers_=[],this.onTransitionEnd_=this.onTransitionEnd_.bind(this),this.refresh=function(t,e){var n=!1,r=!1,i=0;function o(){n&&(n=!1,t()),r&&u()}function s(){a(o)}function u(){var t=Date.now();if(n){if(t-i<c)return;r=!0}else n=!0,r=!1,setTimeout(s,e);i=t}return u}(this.refresh.bind(this),u)}return t.prototype.addObserver=function(t){~this.observers_.indexOf(t)||this.observers_.push(t),this.connected_||this.connect_()},t.prototype.removeObserver=function(t){var e=this.observers_,n=e.indexOf(t);~n&&e.splice(n,1),!e.length&&this.connected_&&this.disconnect_()},t.prototype.refresh=function(){this.updateObservers_()&&this.refresh()},t.prototype.updateObservers_=function(){var t=this.observers_.filter(function(t){return t.gatherActive(),t.hasActive()});return t.forEach(function(t){return t.broadcastActive()}),t.length>0},t.prototype.connect_=function(){o&&!this.connected_&&(document.addEventListener("transitionend",this.onTransitionEnd_),window.addEventListener("resize",this.refresh),f?(this.mutationsObserver_=new MutationObserver(this.refresh),this.mutationsObserver_.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})):(document.addEventListener("DOMSubtreeModified",this.refresh),this.mutationEventsAdded_=!0),this.connected_=!0)},t.prototype.disconnect_=function(){o&&this.connected_&&(document.removeEventListener("transitionend",this.onTransitionEnd_),window.removeEventListener("resize",this.refresh),this.mutationsObserver_&&this.mutationsObserver_.disconnect(),this.mutationEventsAdded_&&document.removeEventListener("DOMSubtreeModified",this.refresh),this.mutationsObserver_=null,this.mutationEventsAdded_=!1,this.connected_=!1)},t.prototype.onTransitionEnd_=function(t){var e=t.propertyName,n=void 0===e?"":e;h.some(function(t){return!!~n.indexOf(t)})&&this.refresh()},t.getInstance=function(){return this.instance_||(this.instance_=new t),this.instance_},t.instance_=null,t}(),l=function(t,e){for(var n=0,r=Object.keys(e);n<r.length;n++){var i=r[n];Object.defineProperty(t,i,{value:e[i],enumerable:!1,writable:!1,configurable:!0})}return t},v=function(t){return t&&t.ownerDocument&&t.ownerDocument.defaultView||s},p=g(0,0,0,0);function _(t){return parseFloat(t)||0}function b(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];return e.reduce(function(e,n){return e+_(t["border-"+n+"-width"])},0)}function y(t){var e=t.clientWidth,n=t.clientHeight;if(!e&&!n)return p;var r=v(t).getComputedStyle(t),i=function(t){for(var e={},n=0,r=["top","right","bottom","left"];n<r.length;n++){var i=r[n],o=t["padding-"+i];e[i]=_(o)}return e}(r),o=i.left+i.right,s=i.top+i.bottom,a=_(r.width),c=_(r.height);if("border-box"===r.boxSizing&&(Math.round(a+o)!==e&&(a-=b(r,"left","right")+o),Math.round(c+s)!==n&&(c-=b(r,"top","bottom")+s)),!function(t){return t===v(t).document.documentElement}(t)){var u=Math.round(a+o)-e,h=Math.round(c+s)-n;1!==Math.abs(u)&&(a-=u),1!==Math.abs(h)&&(c-=h)}return g(i.left,i.top,a,c)}var m="undefined"!=typeof SVGGraphicsElement?function(t){return t instanceof v(t).SVGGraphicsElement}:function(t){return t instanceof v(t).SVGElement&&"function"==typeof t.getBBox};function w(t){return o?m(t)?function(t){var e=t.getBBox();return g(0,0,e.width,e.height)}(t):y(t):p}function g(t,e,n,r){return{x:t,y:e,width:n,height:r}}var O=function(){function t(t){this.broadcastWidth=0,this.broadcastHeight=0,this.contentRect_=g(0,0,0,0),this.target=t}return t.prototype.isActive=function(){var t=w(this.target);return this.contentRect_=t,t.width!==this.broadcastWidth||t.height!==this.broadcastHeight},t.prototype.broadcastRect=function(){var t=this.contentRect_;return this.broadcastWidth=t.width,this.broadcastHeight=t.height,t},t}(),E=function(){return function(t,e){var n,r,i,o,s,a,c,u=(r=(n=e).x,i=n.y,o=n.width,s=n.height,a="undefined"!=typeof DOMRectReadOnly?DOMRectReadOnly:Object,c=Object.create(a.prototype),l(c,{x:r,y:i,width:o,height:s,top:i,right:r+o,bottom:s+i,left:r}),c);l(this,{target:t,contentRect:u})}}(),M=function(){function t(t,e,n){if(this.activeObservations_=[],this.observations_=new i,"function"!=typeof t)throw new TypeError("The callback provided as parameter 1 is not a function.");this.callback_=t,this.controller_=e,this.callbackCtx_=n}return t.prototype.observe=function(t){if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");if("undefined"!=typeof Element&&Element instanceof Object){if(!(t instanceof v(t).Element))throw new TypeError('parameter 1 is not of type "Element".');var e=this.observations_;e.has(t)||(e.set(t,new O(t)),this.controller_.addObserver(this),this.controller_.refresh())}},t.prototype.unobserve=function(t){if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");if("undefined"!=typeof Element&&Element instanceof Object){if(!(t instanceof v(t).Element))throw new TypeError('parameter 1 is not of type "Element".');var e=this.observations_;e.has(t)&&(e.delete(t),e.size||this.controller_.removeObserver(this))}},t.prototype.disconnect=function(){this.clearActive(),this.observations_.clear(),this.controller_.removeObserver(this)},t.prototype.gatherActive=function(){var t=this;this.clearActive(),this.observations_.forEach(function(e){e.isActive()&&t.activeObservations_.push(e)})},t.prototype.broadcastActive=function(){if(this.hasActive()){var t=this.callbackCtx_,e=this.activeObservations_.map(function(t){return new E(t.target,t.broadcastRect())});this.callback_.call(t,e,t),this.clearActive()}},t.prototype.clearActive=function(){this.activeObservations_.splice(0)},t.prototype.hasActive=function(){return this.activeObservations_.length>0},t}(),A="undefined"!=typeof WeakMap?new WeakMap:new i,T=function(){return function t(e){if(!(this instanceof t))throw new TypeError("Cannot call a class as a function.");if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");var n=d.getInstance(),r=new M(e,n,this);A.set(this,r)}}();["observe","unobserve","disconnect"].forEach(function(t){T.prototype[t]=function(){var e;return(e=A.get(this))[t].apply(e,arguments)}});var x=void 0!==s.ResizeObserver?s.ResizeObserver:T;function R(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=[],r=!0,i=!1,o=void 0;try{for(var s,a=t[Symbol.iterator]();!(r=(s=a.next()).done)&&(n.push(s.value),!e||n.length!==e);r=!0);}catch(t){i=!0,o=t}finally{try{r||null==a.return||a.return()}finally{if(i)throw o}}return n}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}t.ScaleMode=r,t.useElementFit=(t,n,i=r.CONTAIN,o=.5,s=.5,a,c)=>{const[u,h,f]=function(){var t=e.useRef(),n=R(e.useState(1),2),r=n[0],i=n[1],o=R(e.useState(1),2),s=o[0],a=o[1];return e.useEffect(function(){var e=t.current,n=new x(function(t){if(Array.isArray(t)&&t.length){var e=t[0];i(e.contentRect.width),a(e.contentRect.height)}});return n.observe(e),function(){return n.unobserve(e)}},[]),[t,r,s]}(),[d,l]=e.useState(1),[v,p]=e.useState(1),[_,b]=e.useState(1),[y,m]=e.useState(1);return e.useEffect(()=>{const{width:e,height:u,x:d,y:v}=((t,e,n,i,o,s=.5,a=.5,c,u)=>{let h=0,f=0,d=0,l=0,v=1;switch(o!==r.CONTAIN&&o!==r.COVER||(d=n/t,l=i/e),o){case r.CONTAIN:v=d<l?d:l;break;case r.COVER:v=d>l?d:l;break;case r.ALIGN_ONLY:h=t,f=e}if(o===r.CONTAIN||o===r.COVER){if(c||u){let n=v,r=v;c&&(n=c/t),u&&(r=u/e);const i=n<r?n:r;v=Math.min(v,i)}h=t*v,f=e*v}return{width:Math.round(h),height:Math.round(f),x:Math.round((n-h)*s),y:Math.round((i-f)*a)}})(t,n,h,f,i,o,s,a,c);l(e),p(u),b(d),m(v)},[h,f,t,n,h,f,i,o,s,a,c]),{ref:u,width:d,height:v,x:_,y:y}},Object.defineProperty(t,"__esModule",{value:!0})});
//# sourceMappingURL=index.bundle.min.js.map
{"version":3,"file":"index.bundle.min.js","sources":["../src/ScaleMode.ts","../node_modules/resize-observer-polyfill/dist/ResizeObserver.es.js","../node_modules/use-resize-observer/dist/bundle.esm.js","../src/useElementFit.ts"],"sourcesContent":["enum ScaleMode {\n CONTAIN = 'contain',\n COVER = 'cover',\n ALIGN_ONLY = 'align-only',\n}\n\nexport default ScaleMode;\n","/**\r\n * A collection of shims that provide minimal functionality of the ES6 collections.\r\n *\r\n * These implementations are not meant to be used outside of the ResizeObserver\r\n * modules as they cover only a limited range of use cases.\r\n */\r\n/* eslint-disable require-jsdoc, valid-jsdoc */\r\nvar MapShim = (function () {\r\n if (typeof Map !== 'undefined') {\r\n return Map;\r\n }\r\n /**\r\n * Returns index in provided array that matches the specified key.\r\n *\r\n * @param {Array<Array>} arr\r\n * @param {*} key\r\n * @returns {number}\r\n */\r\n function getIndex(arr, key) {\r\n var result = -1;\r\n arr.some(function (entry, index) {\r\n if (entry[0] === key) {\r\n result = index;\r\n return true;\r\n }\r\n return false;\r\n });\r\n return result;\r\n }\r\n return /** @class */ (function () {\r\n function class_1() {\r\n this.__entries__ = [];\r\n }\r\n Object.defineProperty(class_1.prototype, \"size\", {\r\n /**\r\n * @returns {boolean}\r\n */\r\n get: function () {\r\n return this.__entries__.length;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * @param {*} key\r\n * @returns {*}\r\n */\r\n class_1.prototype.get = function (key) {\r\n var index = getIndex(this.__entries__, key);\r\n var entry = this.__entries__[index];\r\n return entry && entry[1];\r\n };\r\n /**\r\n * @param {*} key\r\n * @param {*} value\r\n * @returns {void}\r\n */\r\n class_1.prototype.set = function (key, value) {\r\n var index = getIndex(this.__entries__, key);\r\n if (~index) {\r\n this.__entries__[index][1] = value;\r\n }\r\n else {\r\n this.__entries__.push([key, value]);\r\n }\r\n };\r\n /**\r\n * @param {*} key\r\n * @returns {void}\r\n */\r\n class_1.prototype.delete = function (key) {\r\n var entries = this.__entries__;\r\n var index = getIndex(entries, key);\r\n if (~index) {\r\n entries.splice(index, 1);\r\n }\r\n };\r\n /**\r\n * @param {*} key\r\n * @returns {void}\r\n */\r\n class_1.prototype.has = function (key) {\r\n return !!~getIndex(this.__entries__, key);\r\n };\r\n /**\r\n * @returns {void}\r\n */\r\n class_1.prototype.clear = function () {\r\n this.__entries__.splice(0);\r\n };\r\n /**\r\n * @param {Function} callback\r\n * @param {*} [ctx=null]\r\n * @returns {void}\r\n */\r\n class_1.prototype.forEach = function (callback, ctx) {\r\n if (ctx === void 0) { ctx = null; }\r\n for (var _i = 0, _a = this.__entries__; _i < _a.length; _i++) {\r\n var entry = _a[_i];\r\n callback.call(ctx, entry[1], entry[0]);\r\n }\r\n };\r\n return class_1;\r\n }());\r\n})();\n\n/**\r\n * Detects whether window and document objects are available in current environment.\r\n */\r\nvar isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && window.document === document;\n\n// Returns global object of a current environment.\r\nvar global$1 = (function () {\r\n if (typeof global !== 'undefined' && global.Math === Math) {\r\n return global;\r\n }\r\n if (typeof self !== 'undefined' && self.Math === Math) {\r\n return self;\r\n }\r\n if (typeof window !== 'undefined' && window.Math === Math) {\r\n return window;\r\n }\r\n // eslint-disable-next-line no-new-func\r\n return Function('return this')();\r\n})();\n\n/**\r\n * A shim for the requestAnimationFrame which falls back to the setTimeout if\r\n * first one is not supported.\r\n *\r\n * @returns {number} Requests' identifier.\r\n */\r\nvar requestAnimationFrame$1 = (function () {\r\n if (typeof requestAnimationFrame === 'function') {\r\n // It's required to use a bounded function because IE sometimes throws\r\n // an \"Invalid calling object\" error if rAF is invoked without the global\r\n // object on the left hand side.\r\n return requestAnimationFrame.bind(global$1);\r\n }\r\n return function (callback) { return setTimeout(function () { return callback(Date.now()); }, 1000 / 60); };\r\n})();\n\n// Defines minimum timeout before adding a trailing call.\r\nvar trailingTimeout = 2;\r\n/**\r\n * Creates a wrapper function which ensures that provided callback will be\r\n * invoked only once during the specified delay period.\r\n *\r\n * @param {Function} callback - Function to be invoked after the delay period.\r\n * @param {number} delay - Delay after which to invoke callback.\r\n * @returns {Function}\r\n */\r\nfunction throttle (callback, delay) {\r\n var leadingCall = false, trailingCall = false, lastCallTime = 0;\r\n /**\r\n * Invokes the original callback function and schedules new invocation if\r\n * the \"proxy\" was called during current request.\r\n *\r\n * @returns {void}\r\n */\r\n function resolvePending() {\r\n if (leadingCall) {\r\n leadingCall = false;\r\n callback();\r\n }\r\n if (trailingCall) {\r\n proxy();\r\n }\r\n }\r\n /**\r\n * Callback invoked after the specified delay. It will further postpone\r\n * invocation of the original function delegating it to the\r\n * requestAnimationFrame.\r\n *\r\n * @returns {void}\r\n */\r\n function timeoutCallback() {\r\n requestAnimationFrame$1(resolvePending);\r\n }\r\n /**\r\n * Schedules invocation of the original function.\r\n *\r\n * @returns {void}\r\n */\r\n function proxy() {\r\n var timeStamp = Date.now();\r\n if (leadingCall) {\r\n // Reject immediately following calls.\r\n if (timeStamp - lastCallTime < trailingTimeout) {\r\n return;\r\n }\r\n // Schedule new call to be in invoked when the pending one is resolved.\r\n // This is important for \"transitions\" which never actually start\r\n // immediately so there is a chance that we might miss one if change\r\n // happens amids the pending invocation.\r\n trailingCall = true;\r\n }\r\n else {\r\n leadingCall = true;\r\n trailingCall = false;\r\n setTimeout(timeoutCallback, delay);\r\n }\r\n lastCallTime = timeStamp;\r\n }\r\n return proxy;\r\n}\n\n// Minimum delay before invoking the update of observers.\r\nvar REFRESH_DELAY = 20;\r\n// A list of substrings of CSS properties used to find transition events that\r\n// might affect dimensions of observed elements.\r\nvar transitionKeys = ['top', 'right', 'bottom', 'left', 'width', 'height', 'size', 'weight'];\r\n// Check if MutationObserver is available.\r\nvar mutationObserverSupported = typeof MutationObserver !== 'undefined';\r\n/**\r\n * Singleton controller class which handles updates of ResizeObserver instances.\r\n */\r\nvar ResizeObserverController = /** @class */ (function () {\r\n /**\r\n * Creates a new instance of ResizeObserverController.\r\n *\r\n * @private\r\n */\r\n function ResizeObserverController() {\r\n /**\r\n * Indicates whether DOM listeners have been added.\r\n *\r\n * @private {boolean}\r\n */\r\n this.connected_ = false;\r\n /**\r\n * Tells that controller has subscribed for Mutation Events.\r\n *\r\n * @private {boolean}\r\n */\r\n this.mutationEventsAdded_ = false;\r\n /**\r\n * Keeps reference to the instance of MutationObserver.\r\n *\r\n * @private {MutationObserver}\r\n */\r\n this.mutationsObserver_ = null;\r\n /**\r\n * A list of connected observers.\r\n *\r\n * @private {Array<ResizeObserverSPI>}\r\n */\r\n this.observers_ = [];\r\n this.onTransitionEnd_ = this.onTransitionEnd_.bind(this);\r\n this.refresh = throttle(this.refresh.bind(this), REFRESH_DELAY);\r\n }\r\n /**\r\n * Adds observer to observers list.\r\n *\r\n * @param {ResizeObserverSPI} observer - Observer to be added.\r\n * @returns {void}\r\n */\r\n ResizeObserverController.prototype.addObserver = function (observer) {\r\n if (!~this.observers_.indexOf(observer)) {\r\n this.observers_.push(observer);\r\n }\r\n // Add listeners if they haven't been added yet.\r\n if (!this.connected_) {\r\n this.connect_();\r\n }\r\n };\r\n /**\r\n * Removes observer from observers list.\r\n *\r\n * @param {ResizeObserverSPI} observer - Observer to be removed.\r\n * @returns {void}\r\n */\r\n ResizeObserverController.prototype.removeObserver = function (observer) {\r\n var observers = this.observers_;\r\n var index = observers.indexOf(observer);\r\n // Remove observer if it's present in registry.\r\n if (~index) {\r\n observers.splice(index, 1);\r\n }\r\n // Remove listeners if controller has no connected observers.\r\n if (!observers.length && this.connected_) {\r\n this.disconnect_();\r\n }\r\n };\r\n /**\r\n * Invokes the update of observers. It will continue running updates insofar\r\n * it detects changes.\r\n *\r\n * @returns {void}\r\n */\r\n ResizeObserverController.prototype.refresh = function () {\r\n var changesDetected = this.updateObservers_();\r\n // Continue running updates if changes have been detected as there might\r\n // be future ones caused by CSS transitions.\r\n if (changesDetected) {\r\n this.refresh();\r\n }\r\n };\r\n /**\r\n * Updates every observer from observers list and notifies them of queued\r\n * entries.\r\n *\r\n * @private\r\n * @returns {boolean} Returns \"true\" if any observer has detected changes in\r\n * dimensions of it's elements.\r\n */\r\n ResizeObserverController.prototype.updateObservers_ = function () {\r\n // Collect observers that have active observations.\r\n var activeObservers = this.observers_.filter(function (observer) {\r\n return observer.gatherActive(), observer.hasActive();\r\n });\r\n // Deliver notifications in a separate cycle in order to avoid any\r\n // collisions between observers, e.g. when multiple instances of\r\n // ResizeObserver are tracking the same element and the callback of one\r\n // of them changes content dimensions of the observed target. Sometimes\r\n // this may result in notifications being blocked for the rest of observers.\r\n activeObservers.forEach(function (observer) { return observer.broadcastActive(); });\r\n return activeObservers.length > 0;\r\n };\r\n /**\r\n * Initializes DOM listeners.\r\n *\r\n * @private\r\n * @returns {void}\r\n */\r\n ResizeObserverController.prototype.connect_ = function () {\r\n // Do nothing if running in a non-browser environment or if listeners\r\n // have been already added.\r\n if (!isBrowser || this.connected_) {\r\n return;\r\n }\r\n // Subscription to the \"Transitionend\" event is used as a workaround for\r\n // delayed transitions. This way it's possible to capture at least the\r\n // final state of an element.\r\n document.addEventListener('transitionend', this.onTransitionEnd_);\r\n window.addEventListener('resize', this.refresh);\r\n if (mutationObserverSupported) {\r\n this.mutationsObserver_ = new MutationObserver(this.refresh);\r\n this.mutationsObserver_.observe(document, {\r\n attributes: true,\r\n childList: true,\r\n characterData: true,\r\n subtree: true\r\n });\r\n }\r\n else {\r\n document.addEventListener('DOMSubtreeModified', this.refresh);\r\n this.mutationEventsAdded_ = true;\r\n }\r\n this.connected_ = true;\r\n };\r\n /**\r\n * Removes DOM listeners.\r\n *\r\n * @private\r\n * @returns {void}\r\n */\r\n ResizeObserverController.prototype.disconnect_ = function () {\r\n // Do nothing if running in a non-browser environment or if listeners\r\n // have been already removed.\r\n if (!isBrowser || !this.connected_) {\r\n return;\r\n }\r\n document.removeEventListener('transitionend', this.onTransitionEnd_);\r\n window.removeEventListener('resize', this.refresh);\r\n if (this.mutationsObserver_) {\r\n this.mutationsObserver_.disconnect();\r\n }\r\n if (this.mutationEventsAdded_) {\r\n document.removeEventListener('DOMSubtreeModified', this.refresh);\r\n }\r\n this.mutationsObserver_ = null;\r\n this.mutationEventsAdded_ = false;\r\n this.connected_ = false;\r\n };\r\n /**\r\n * \"Transitionend\" event handler.\r\n *\r\n * @private\r\n * @param {TransitionEvent} event\r\n * @returns {void}\r\n */\r\n ResizeObserverController.prototype.onTransitionEnd_ = function (_a) {\r\n var _b = _a.propertyName, propertyName = _b === void 0 ? '' : _b;\r\n // Detect whether transition may affect dimensions of an element.\r\n var isReflowProperty = transitionKeys.some(function (key) {\r\n return !!~propertyName.indexOf(key);\r\n });\r\n if (isReflowProperty) {\r\n this.refresh();\r\n }\r\n };\r\n /**\r\n * Returns instance of the ResizeObserverController.\r\n *\r\n * @returns {ResizeObserverController}\r\n */\r\n ResizeObserverController.getInstance = function () {\r\n if (!this.instance_) {\r\n this.instance_ = new ResizeObserverController();\r\n }\r\n return this.instance_;\r\n };\r\n /**\r\n * Holds reference to the controller's instance.\r\n *\r\n * @private {ResizeObserverController}\r\n */\r\n ResizeObserverController.instance_ = null;\r\n return ResizeObserverController;\r\n}());\n\n/**\r\n * Defines non-writable/enumerable properties of the provided target object.\r\n *\r\n * @param {Object} target - Object for which to define properties.\r\n * @param {Object} props - Properties to be defined.\r\n * @returns {Object} Target object.\r\n */\r\nvar defineConfigurable = (function (target, props) {\r\n for (var _i = 0, _a = Object.keys(props); _i < _a.length; _i++) {\r\n var key = _a[_i];\r\n Object.defineProperty(target, key, {\r\n value: props[key],\r\n enumerable: false,\r\n writable: false,\r\n configurable: true\r\n });\r\n }\r\n return target;\r\n});\n\n/**\r\n * Returns the global object associated with provided element.\r\n *\r\n * @param {Object} target\r\n * @returns {Object}\r\n */\r\nvar getWindowOf = (function (target) {\r\n // Assume that the element is an instance of Node, which means that it\r\n // has the \"ownerDocument\" property from which we can retrieve a\r\n // corresponding global object.\r\n var ownerGlobal = target && target.ownerDocument && target.ownerDocument.defaultView;\r\n // Return the local global object if it's not possible extract one from\r\n // provided element.\r\n return ownerGlobal || global$1;\r\n});\n\n// Placeholder of an empty content rectangle.\r\nvar emptyRect = createRectInit(0, 0, 0, 0);\r\n/**\r\n * Converts provided string to a number.\r\n *\r\n * @param {number|string} value\r\n * @returns {number}\r\n */\r\nfunction toFloat(value) {\r\n return parseFloat(value) || 0;\r\n}\r\n/**\r\n * Extracts borders size from provided styles.\r\n *\r\n * @param {CSSStyleDeclaration} styles\r\n * @param {...string} positions - Borders positions (top, right, ...)\r\n * @returns {number}\r\n */\r\nfunction getBordersSize(styles) {\r\n var positions = [];\r\n for (var _i = 1; _i < arguments.length; _i++) {\r\n positions[_i - 1] = arguments[_i];\r\n }\r\n return positions.reduce(function (size, position) {\r\n var value = styles['border-' + position + '-width'];\r\n return size + toFloat(value);\r\n }, 0);\r\n}\r\n/**\r\n * Extracts paddings sizes from provided styles.\r\n *\r\n * @param {CSSStyleDeclaration} styles\r\n * @returns {Object} Paddings box.\r\n */\r\nfunction getPaddings(styles) {\r\n var positions = ['top', 'right', 'bottom', 'left'];\r\n var paddings = {};\r\n for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) {\r\n var position = positions_1[_i];\r\n var value = styles['padding-' + position];\r\n paddings[position] = toFloat(value);\r\n }\r\n return paddings;\r\n}\r\n/**\r\n * Calculates content rectangle of provided SVG element.\r\n *\r\n * @param {SVGGraphicsElement} target - Element content rectangle of which needs\r\n * to be calculated.\r\n * @returns {DOMRectInit}\r\n */\r\nfunction getSVGContentRect(target) {\r\n var bbox = target.getBBox();\r\n return createRectInit(0, 0, bbox.width, bbox.height);\r\n}\r\n/**\r\n * Calculates content rectangle of provided HTMLElement.\r\n *\r\n * @param {HTMLElement} target - Element for which to calculate the content rectangle.\r\n * @returns {DOMRectInit}\r\n */\r\nfunction getHTMLElementContentRect(target) {\r\n // Client width & height properties can't be\r\n // used exclusively as they provide rounded values.\r\n var clientWidth = target.clientWidth, clientHeight = target.clientHeight;\r\n // By this condition we can catch all non-replaced inline, hidden and\r\n // detached elements. Though elements with width & height properties less\r\n // than 0.5 will be discarded as well.\r\n //\r\n // Without it we would need to implement separate methods for each of\r\n // those cases and it's not possible to perform a precise and performance\r\n // effective test for hidden elements. E.g. even jQuery's ':visible' filter\r\n // gives wrong results for elements with width & height less than 0.5.\r\n if (!clientWidth && !clientHeight) {\r\n return emptyRect;\r\n }\r\n var styles = getWindowOf(target).getComputedStyle(target);\r\n var paddings = getPaddings(styles);\r\n var horizPad = paddings.left + paddings.right;\r\n var vertPad = paddings.top + paddings.bottom;\r\n // Computed styles of width & height are being used because they are the\r\n // only dimensions available to JS that contain non-rounded values. It could\r\n // be possible to utilize the getBoundingClientRect if only it's data wasn't\r\n // affected by CSS transformations let alone paddings, borders and scroll bars.\r\n var width = toFloat(styles.width), height = toFloat(styles.height);\r\n // Width & height include paddings and borders when the 'border-box' box\r\n // model is applied (except for IE).\r\n if (styles.boxSizing === 'border-box') {\r\n // Following conditions are required to handle Internet Explorer which\r\n // doesn't include paddings and borders to computed CSS dimensions.\r\n //\r\n // We can say that if CSS dimensions + paddings are equal to the \"client\"\r\n // properties then it's either IE, and thus we don't need to subtract\r\n // anything, or an element merely doesn't have paddings/borders styles.\r\n if (Math.round(width + horizPad) !== clientWidth) {\r\n width -= getBordersSize(styles, 'left', 'right') + horizPad;\r\n }\r\n if (Math.round(height + vertPad) !== clientHeight) {\r\n height -= getBordersSize(styles, 'top', 'bottom') + vertPad;\r\n }\r\n }\r\n // Following steps can't be applied to the document's root element as its\r\n // client[Width/Height] properties represent viewport area of the window.\r\n // Besides, it's as well not necessary as the <html> itself neither has\r\n // rendered scroll bars nor it can be clipped.\r\n if (!isDocumentElement(target)) {\r\n // In some browsers (only in Firefox, actually) CSS width & height\r\n // include scroll bars size which can be removed at this step as scroll\r\n // bars are the only difference between rounded dimensions + paddings\r\n // and \"client\" properties, though that is not always true in Chrome.\r\n var vertScrollbar = Math.round(width + horizPad) - clientWidth;\r\n var horizScrollbar = Math.round(height + vertPad) - clientHeight;\r\n // Chrome has a rather weird rounding of \"client\" properties.\r\n // E.g. for an element with content width of 314.2px it sometimes gives\r\n // the client width of 315px and for the width of 314.7px it may give\r\n // 314px. And it doesn't happen all the time. So just ignore this delta\r\n // as a non-relevant.\r\n if (Math.abs(vertScrollbar) !== 1) {\r\n width -= vertScrollbar;\r\n }\r\n if (Math.abs(horizScrollbar) !== 1) {\r\n height -= horizScrollbar;\r\n }\r\n }\r\n return createRectInit(paddings.left, paddings.top, width, height);\r\n}\r\n/**\r\n * Checks whether provided element is an instance of the SVGGraphicsElement.\r\n *\r\n * @param {Element} target - Element to be checked.\r\n * @returns {boolean}\r\n */\r\nvar isSVGGraphicsElement = (function () {\r\n // Some browsers, namely IE and Edge, don't have the SVGGraphicsElement\r\n // interface.\r\n if (typeof SVGGraphicsElement !== 'undefined') {\r\n return function (target) { return target instanceof getWindowOf(target).SVGGraphicsElement; };\r\n }\r\n // If it's so, then check that element is at least an instance of the\r\n // SVGElement and that it has the \"getBBox\" method.\r\n // eslint-disable-next-line no-extra-parens\r\n return function (target) { return (target instanceof getWindowOf(target).SVGElement &&\r\n typeof target.getBBox === 'function'); };\r\n})();\r\n/**\r\n * Checks whether provided element is a document element (<html>).\r\n *\r\n * @param {Element} target - Element to be checked.\r\n * @returns {boolean}\r\n */\r\nfunction isDocumentElement(target) {\r\n return target === getWindowOf(target).document.documentElement;\r\n}\r\n/**\r\n * Calculates an appropriate content rectangle for provided html or svg element.\r\n *\r\n * @param {Element} target - Element content rectangle of which needs to be calculated.\r\n * @returns {DOMRectInit}\r\n */\r\nfunction getContentRect(target) {\r\n if (!isBrowser) {\r\n return emptyRect;\r\n }\r\n if (isSVGGraphicsElement(target)) {\r\n return getSVGContentRect(target);\r\n }\r\n return getHTMLElementContentRect(target);\r\n}\r\n/**\r\n * Creates rectangle with an interface of the DOMRectReadOnly.\r\n * Spec: https://drafts.fxtf.org/geometry/#domrectreadonly\r\n *\r\n * @param {DOMRectInit} rectInit - Object with rectangle's x/y coordinates and dimensions.\r\n * @returns {DOMRectReadOnly}\r\n */\r\nfunction createReadOnlyRect(_a) {\r\n var x = _a.x, y = _a.y, width = _a.width, height = _a.height;\r\n // If DOMRectReadOnly is available use it as a prototype for the rectangle.\r\n var Constr = typeof DOMRectReadOnly !== 'undefined' ? DOMRectReadOnly : Object;\r\n var rect = Object.create(Constr.prototype);\r\n // Rectangle's properties are not writable and non-enumerable.\r\n defineConfigurable(rect, {\r\n x: x, y: y, width: width, height: height,\r\n top: y,\r\n right: x + width,\r\n bottom: height + y,\r\n left: x\r\n });\r\n return rect;\r\n}\r\n/**\r\n * Creates DOMRectInit object based on the provided dimensions and the x/y coordinates.\r\n * Spec: https://drafts.fxtf.org/geometry/#dictdef-domrectinit\r\n *\r\n * @param {number} x - X coordinate.\r\n * @param {number} y - Y coordinate.\r\n * @param {number} width - Rectangle's width.\r\n * @param {number} height - Rectangle's height.\r\n * @returns {DOMRectInit}\r\n */\r\nfunction createRectInit(x, y, width, height) {\r\n return { x: x, y: y, width: width, height: height };\r\n}\n\n/**\r\n * Class that is responsible for computations of the content rectangle of\r\n * provided DOM element and for keeping track of it's changes.\r\n */\r\nvar ResizeObservation = /** @class */ (function () {\r\n /**\r\n * Creates an instance of ResizeObservation.\r\n *\r\n * @param {Element} target - Element to be observed.\r\n */\r\n function ResizeObservation(target) {\r\n /**\r\n * Broadcasted width of content rectangle.\r\n *\r\n * @type {number}\r\n */\r\n this.broadcastWidth = 0;\r\n /**\r\n * Broadcasted height of content rectangle.\r\n *\r\n * @type {number}\r\n */\r\n this.broadcastHeight = 0;\r\n /**\r\n * Reference to the last observed content rectangle.\r\n *\r\n * @private {DOMRectInit}\r\n */\r\n this.contentRect_ = createRectInit(0, 0, 0, 0);\r\n this.target = target;\r\n }\r\n /**\r\n * Updates content rectangle and tells whether it's width or height properties\r\n * have changed since the last broadcast.\r\n *\r\n * @returns {boolean}\r\n */\r\n ResizeObservation.prototype.isActive = function () {\r\n var rect = getContentRect(this.target);\r\n this.contentRect_ = rect;\r\n return (rect.width !== this.broadcastWidth ||\r\n rect.height !== this.broadcastHeight);\r\n };\r\n /**\r\n * Updates 'broadcastWidth' and 'broadcastHeight' properties with a data\r\n * from the corresponding properties of the last observed content rectangle.\r\n *\r\n * @returns {DOMRectInit} Last observed content rectangle.\r\n */\r\n ResizeObservation.prototype.broadcastRect = function () {\r\n var rect = this.contentRect_;\r\n this.broadcastWidth = rect.width;\r\n this.broadcastHeight = rect.height;\r\n return rect;\r\n };\r\n return ResizeObservation;\r\n}());\n\nvar ResizeObserverEntry = /** @class */ (function () {\r\n /**\r\n * Creates an instance of ResizeObserverEntry.\r\n *\r\n * @param {Element} target - Element that is being observed.\r\n * @param {DOMRectInit} rectInit - Data of the element's content rectangle.\r\n */\r\n function ResizeObserverEntry(target, rectInit) {\r\n var contentRect = createReadOnlyRect(rectInit);\r\n // According to the specification following properties are not writable\r\n // and are also not enumerable in the native implementation.\r\n //\r\n // Property accessors are not being used as they'd require to define a\r\n // private WeakMap storage which may cause memory leaks in browsers that\r\n // don't support this type of collections.\r\n defineConfigurable(this, { target: target, contentRect: contentRect });\r\n }\r\n return ResizeObserverEntry;\r\n}());\n\nvar ResizeObserverSPI = /** @class */ (function () {\r\n /**\r\n * Creates a new instance of ResizeObserver.\r\n *\r\n * @param {ResizeObserverCallback} callback - Callback function that is invoked\r\n * when one of the observed elements changes it's content dimensions.\r\n * @param {ResizeObserverController} controller - Controller instance which\r\n * is responsible for the updates of observer.\r\n * @param {ResizeObserver} callbackCtx - Reference to the public\r\n * ResizeObserver instance which will be passed to callback function.\r\n */\r\n function ResizeObserverSPI(callback, controller, callbackCtx) {\r\n /**\r\n * Collection of resize observations that have detected changes in dimensions\r\n * of elements.\r\n *\r\n * @private {Array<ResizeObservation>}\r\n */\r\n this.activeObservations_ = [];\r\n /**\r\n * Registry of the ResizeObservation instances.\r\n *\r\n * @private {Map<Element, ResizeObservation>}\r\n */\r\n this.observations_ = new MapShim();\r\n if (typeof callback !== 'function') {\r\n throw new TypeError('The callback provided as parameter 1 is not a function.');\r\n }\r\n this.callback_ = callback;\r\n this.controller_ = controller;\r\n this.callbackCtx_ = callbackCtx;\r\n }\r\n /**\r\n * Starts observing provided element.\r\n *\r\n * @param {Element} target - Element to be observed.\r\n * @returns {void}\r\n */\r\n ResizeObserverSPI.prototype.observe = function (target) {\r\n if (!arguments.length) {\r\n throw new TypeError('1 argument required, but only 0 present.');\r\n }\r\n // Do nothing if current environment doesn't have the Element interface.\r\n if (typeof Element === 'undefined' || !(Element instanceof Object)) {\r\n return;\r\n }\r\n if (!(target instanceof getWindowOf(target).Element)) {\r\n throw new TypeError('parameter 1 is not of type \"Element\".');\r\n }\r\n var observations = this.observations_;\r\n // Do nothing if element is already being observed.\r\n if (observations.has(target)) {\r\n return;\r\n }\r\n observations.set(target, new ResizeObservation(target));\r\n this.controller_.addObserver(this);\r\n // Force the update of observations.\r\n this.controller_.refresh();\r\n };\r\n /**\r\n * Stops observing provided element.\r\n *\r\n * @param {Element} target - Element to stop observing.\r\n * @returns {void}\r\n */\r\n ResizeObserverSPI.prototype.unobserve = function (target) {\r\n if (!arguments.length) {\r\n throw new TypeError('1 argument required, but only 0 present.');\r\n }\r\n // Do nothing if current environment doesn't have the Element interface.\r\n if (typeof Element === 'undefined' || !(Element instanceof Object)) {\r\n return;\r\n }\r\n if (!(target instanceof getWindowOf(target).Element)) {\r\n throw new TypeError('parameter 1 is not of type \"Element\".');\r\n }\r\n var observations = this.observations_;\r\n // Do nothing if element is not being observed.\r\n if (!observations.has(target)) {\r\n return;\r\n }\r\n observations.delete(target);\r\n if (!observations.size) {\r\n this.controller_.removeObserver(this);\r\n }\r\n };\r\n /**\r\n * Stops observing all elements.\r\n *\r\n * @returns {void}\r\n */\r\n ResizeObserverSPI.prototype.disconnect = function () {\r\n this.clearActive();\r\n this.observations_.clear();\r\n this.controller_.removeObserver(this);\r\n };\r\n /**\r\n * Collects observation instances the associated element of which has changed\r\n * it's content rectangle.\r\n *\r\n * @returns {void}\r\n */\r\n ResizeObserverSPI.prototype.gatherActive = function () {\r\n var _this = this;\r\n this.clearActive();\r\n this.observations_.forEach(function (observation) {\r\n if (observation.isActive()) {\r\n _this.activeObservations_.push(observation);\r\n }\r\n });\r\n };\r\n /**\r\n * Invokes initial callback function with a list of ResizeObserverEntry\r\n * instances collected from active resize observations.\r\n *\r\n * @returns {void}\r\n */\r\n ResizeObserverSPI.prototype.broadcastActive = function () {\r\n // Do nothing if observer doesn't have active observations.\r\n if (!this.hasActive()) {\r\n return;\r\n }\r\n var ctx = this.callbackCtx_;\r\n // Create ResizeObserverEntry instance for every active observation.\r\n var entries = this.activeObservations_.map(function (observation) {\r\n return new ResizeObserverEntry(observation.target, observation.broadcastRect());\r\n });\r\n this.callback_.call(ctx, entries, ctx);\r\n this.clearActive();\r\n };\r\n /**\r\n * Clears the collection of active observations.\r\n *\r\n * @returns {void}\r\n */\r\n ResizeObserverSPI.prototype.clearActive = function () {\r\n this.activeObservations_.splice(0);\r\n };\r\n /**\r\n * Tells whether observer has active observations.\r\n *\r\n * @returns {boolean}\r\n */\r\n ResizeObserverSPI.prototype.hasActive = function () {\r\n return this.activeObservations_.length > 0;\r\n };\r\n return ResizeObserverSPI;\r\n}());\n\n// Registry of internal observers. If WeakMap is not available use current shim\r\n// for the Map collection as it has all required methods and because WeakMap\r\n// can't be fully polyfilled anyway.\r\nvar observers = typeof WeakMap !== 'undefined' ? new WeakMap() : new MapShim();\r\n/**\r\n * ResizeObserver API. Encapsulates the ResizeObserver SPI implementation\r\n * exposing only those methods and properties that are defined in the spec.\r\n */\r\nvar ResizeObserver = /** @class */ (function () {\r\n /**\r\n * Creates a new instance of ResizeObserver.\r\n *\r\n * @param {ResizeObserverCallback} callback - Callback that is invoked when\r\n * dimensions of the observed elements change.\r\n */\r\n function ResizeObserver(callback) {\r\n if (!(this instanceof ResizeObserver)) {\r\n throw new TypeError('Cannot call a class as a function.');\r\n }\r\n if (!arguments.length) {\r\n throw new TypeError('1 argument required, but only 0 present.');\r\n }\r\n var controller = ResizeObserverController.getInstance();\r\n var observer = new ResizeObserverSPI(callback, controller, this);\r\n observers.set(this, observer);\r\n }\r\n return ResizeObserver;\r\n}());\r\n// Expose public methods of ResizeObserver.\r\n[\r\n 'observe',\r\n 'unobserve',\r\n 'disconnect'\r\n].forEach(function (method) {\r\n ResizeObserver.prototype[method] = function () {\r\n var _a;\r\n return (_a = observers.get(this))[method].apply(_a, arguments);\r\n };\r\n});\n\nvar index = (function () {\r\n // Export existing implementation if available.\r\n if (typeof global$1.ResizeObserver !== 'undefined') {\r\n return global$1.ResizeObserver;\r\n }\r\n return ResizeObserver;\r\n})();\n\nexport default index;\n","import { useEffect, useState, useRef } from 'react';\nimport ResizeObserver from 'resize-observer-polyfill';\n\nfunction _slicedToArray(arr, i) {\n return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();\n}\n\nfunction _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}\n\nfunction _iterableToArrayLimit(arr, i) {\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}\n\nfunction _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n}\n\nfunction index () {\n var ref = useRef();\n\n var _useState = useState(1),\n _useState2 = _slicedToArray(_useState, 2),\n width = _useState2[0],\n changeWidth = _useState2[1];\n\n var _useState3 = useState(1),\n _useState4 = _slicedToArray(_useState3, 2),\n height = _useState4[0],\n changeHeight = _useState4[1];\n\n useEffect(function () {\n var element = ref.current;\n var resizeObserver = new ResizeObserver(function (entries) {\n if (!Array.isArray(entries)) {\n return;\n } // Since we only observe the one element, we don't need to loop over the\n // array\n\n\n if (!entries.length) {\n return;\n }\n\n var entry = entries[0];\n changeWidth(entry.contentRect.width);\n changeHeight(entry.contentRect.height);\n });\n resizeObserver.observe(element);\n return function () {\n return resizeObserver.unobserve(element);\n };\n }, []);\n return [ref, width, height];\n}\n\nexport default index;\n","import { useEffect, useState } from 'react';\nimport useResizeObserver from 'use-resize-observer';\nimport ScaleMode from './ScaleMode';\n\nconst resize = (\n elementWidth: number,\n elementHeight: number,\n containerWidth: number,\n containerHeight: number,\n scaleMode: ScaleMode,\n alignmentX: number = 0.5,\n alignmentY: number = 0.5,\n maxWidth?: number | undefined,\n maxHeight?: number | undefined,\n) => {\n let targetWidth: number = 0;\n let targetHeight: number = 0;\n let boundRatioX: number = 0;\n let boundRatioY: number = 0;\n let scale = 1;\n\n // get needed scale to fit in bounds with cover\n if (scaleMode === ScaleMode.CONTAIN || scaleMode === ScaleMode.COVER) {\n boundRatioX = containerWidth / elementWidth;\n boundRatioY = containerHeight / elementHeight;\n }\n\n // get scale for bounds container\n switch (scaleMode) {\n case ScaleMode.CONTAIN:\n scale = boundRatioX < boundRatioY ? boundRatioX : boundRatioY;\n break;\n case ScaleMode.COVER:\n scale = boundRatioX > boundRatioY ? boundRatioX : boundRatioY;\n break;\n case ScaleMode.ALIGN_ONLY:\n targetWidth = elementWidth;\n targetHeight = elementHeight;\n break;\n }\n\n if (scaleMode === ScaleMode.CONTAIN || scaleMode === ScaleMode.COVER) {\n // get needed scale to fit in max with contain\n if (maxWidth || maxHeight) {\n let scaleMaxRatioX = scale;\n let scaleMaxRatioY = scale;\n\n if (maxWidth) {\n scaleMaxRatioX = maxWidth / elementWidth;\n }\n\n if (maxHeight) {\n scaleMaxRatioY = maxHeight / elementHeight;\n }\n\n const scaleMax = scaleMaxRatioX < scaleMaxRatioY ? scaleMaxRatioX : scaleMaxRatioY;\n\n scale = Math.min(scale, scaleMax);\n }\n\n // do the actual scale\n targetWidth = elementWidth * scale;\n targetHeight = elementHeight * scale;\n }\n\n return {\n width: Math.round(targetWidth),\n height: Math.round(targetHeight),\n x: Math.round((containerWidth - targetWidth) * alignmentX),\n y: Math.round((containerHeight - targetHeight) * alignmentY),\n };\n};\n\nconst useElementFit = (\n width: number,\n height: number,\n scaleMode: ScaleMode = ScaleMode.CONTAIN,\n alignmentX: number = 0.5,\n alignmentY: number = 0.5,\n maxWidth?: number | undefined,\n maxHeight?: number | undefined,\n): {\n ref: React.RefObject<HTMLElement>;\n width: number;\n x: number;\n y: number;\n height: number;\n} => {\n const [ref, containerWidth, containerHeight] = useResizeObserver();\n\n const [fitWidth, setFitWidth] = useState(1);\n const [fitHeight, setFitHeight] = useState(1);\n\n const [fitX, setFitX] = useState(1);\n const [fitY, setFitY] = useState(1);\n\n useEffect(() => {\n const { width: newWidth, height: newHeight, x, y } = resize(\n width,\n height,\n containerWidth,\n containerHeight,\n scaleMode,\n alignmentX,\n alignmentY,\n maxWidth,\n maxHeight,\n );\n\n setFitWidth(newWidth);\n setFitHeight(newHeight);\n setFitX(x);\n setFitY(y);\n }, [\n containerWidth,\n containerHeight,\n width,\n height,\n containerWidth,\n containerHeight,\n scaleMode,\n alignmentX,\n alignmentY,\n maxWidth,\n maxHeight,\n ]);\n\n return {\n ref,\n width: fitWidth,\n height: fitHeight,\n x: fitX,\n y: fitY,\n };\n};\n\nexport default useElementFit;\n"],"names":["ScaleMode","MapShim","Map","getIndex","arr","key","result","some","entry","index","class_1","this","__entries__","Object","defineProperty","prototype","get","length","enumerable","configurable","set","value","push","delete","entries","splice","has","clear","forEach","callback","ctx","_i","_a","call","isBrowser","window","document","global$1","global","Math","self","Function","requestAnimationFrame$1","requestAnimationFrame","bind","setTimeout","Date","now","trailingTimeout","REFRESH_DELAY","transitionKeys","mutationObserverSupported","MutationObserver","ResizeObserverController","connected_","mutationEventsAdded_","mutationsObserver_","observers_","onTransitionEnd_","refresh","delay","leadingCall","trailingCall","lastCallTime","resolvePending","proxy","timeoutCallback","timeStamp","throttle","addObserver","observer","indexOf","connect_","removeObserver","observers","disconnect_","updateObservers_","activeObservers","filter","gatherActive","hasActive","broadcastActive","addEventListener","observe","attributes","childList","characterData","subtree","removeEventListener","disconnect","_b","propertyName","getInstance","instance_","defineConfigurable","target","props","keys","writable","getWindowOf","ownerDocument","defaultView","emptyRect","createRectInit","toFloat","parseFloat","getBordersSize","styles","positions","arguments","reduce","size","position","getHTMLElementContentRect","clientWidth","clientHeight","getComputedStyle","paddings","positions_1","getPaddings","horizPad","left","right","vertPad","top","bottom","width","height","boxSizing","round","documentElement","isDocumentElement","vertScrollbar","horizScrollbar","abs","isSVGGraphicsElement","SVGGraphicsElement","SVGElement","getBBox","getContentRect","bbox","getSVGContentRect","x","y","ResizeObservation","broadcastWidth","broadcastHeight","contentRect_","isActive","rect","broadcastRect","ResizeObserverEntry","rectInit","Constr","contentRect","DOMRectReadOnly","create","ResizeObserverSPI","controller","callbackCtx","activeObservations_","observations_","TypeError","callback_","controller_","callbackCtx_","Element","observations","unobserve","clearActive","_this","observation","map","WeakMap","ResizeObserver","method","apply","_slicedToArray","i","Array","isArray","_arrayWithHoles","_arr","_n","_d","_e","undefined","_s","Symbol","iterator","next","done","err","_iterableToArrayLimit","_nonIterableRest","scaleMode","CONTAIN","alignmentX","alignmentY","maxWidth","maxHeight","ref","containerWidth","containerHeight","useRef","_useState2","useState","changeWidth","_useState4","changeHeight","useEffect","element","current","resizeObserver","useResizeObserver","fitWidth","setFitWidth","fitHeight","setFitHeight","fitX","setFitX","fitY","setFitY","newWidth","newHeight","elementWidth","elementHeight","targetWidth","targetHeight","boundRatioX","boundRatioY","scale","COVER","ALIGN_ONLY","scaleMaxRatioX","scaleMaxRatioY","scaleMax","min","resize"],"mappings":"6OAAA,IAAKA,GAAL,SAAKA,GACHA,oBACAA,gBACAA,0BAHF,CAAKA,IAAAA,aAMUA,ECCXC,EAAU,WACV,GAAmB,oBAARC,IACP,OAAOA,IASX,SAASC,EAASC,EAAKC,GACnB,IAAIC,GAAU,EAQd,OAPAF,EAAIG,KAAK,SAAUC,EAAOC,GACtB,OAAID,EAAM,KAAOH,IACbC,EAASG,GACF,KAIRH,EAEX,OAAsB,WAClB,SAASI,IACLC,KAAKC,YAAc,GAuEvB,OArEAC,OAAOC,eAAeJ,EAAQK,UAAW,OAAQ,CAI7CC,IAAK,WACD,OAAOL,KAAKC,YAAYK,QAE5BC,YAAY,EACZC,cAAc,IAMlBT,EAAQK,UAAUC,IAAM,SAAUX,GAC9B,IAAII,EAAQN,EAASQ,KAAKC,YAAaP,GACnCG,EAAQG,KAAKC,YAAYH,GAC7B,OAAOD,GAASA,EAAM,IAO1BE,EAAQK,UAAUK,IAAM,SAAUf,EAAKgB,GACnC,IAAIZ,EAAQN,EAASQ,KAAKC,YAAaP,IAClCI,EACDE,KAAKC,YAAYH,GAAO,GAAKY,EAG7BV,KAAKC,YAAYU,KAAK,CAACjB,EAAKgB,KAOpCX,EAAQK,UAAUQ,OAAS,SAAUlB,GACjC,IAAImB,EAAUb,KAAKC,YACfH,EAAQN,EAASqB,EAASnB,IACzBI,GACDe,EAAQC,OAAOhB,EAAO,IAO9BC,EAAQK,UAAUW,IAAM,SAAUrB,GAC9B,SAAUF,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2D,EACAC,EACA7E,EACAC,EACA2E,EACAC,EACAR,EACAE,EACAC,EACAC,EACAC,IAGK,CACLC,IAAAA,EACA3E,MAAOyF,EACPxF,OAAQ0F,EACR3E,EAAG6E,EACH5E,EAAG8E"}
+1
-1

@@ -1,1 +0,1 @@

{"version":3,"file":"index.js","sources":["../src/ScaleMode.ts","../src/useElementFit.ts"],"sourcesContent":["enum ScaleMode {\n CONTAIN = 'contain',\n COVER = 'cover',\n ALIGN_ONLY = 'align-only',\n}\n\nexport default ScaleMode;\n","import { RefObject, useEffect, useState } from 'react';\nimport useResizeObserver from 'use-resize-observer';\nimport ScaleMode from './ScaleMode';\n\nconst resize = (\n elementWidth: number,\n elementHeight: number,\n containerWidth: number,\n containerHeight: number,\n scaleMode: ScaleMode,\n alignmentX: number = 0.5,\n alignmentY: number = 0.5,\n maxWidth?: number | undefined,\n maxHeight?: number | undefined,\n) => {\n let targetWidth: number = 0;\n let targetHeight: number = 0;\n let boundRatioX: number = 0;\n let boundRatioY: number = 0;\n let scale = 1;\n\n // get needed scale to fit in bounds with cover\n if (scaleMode === ScaleMode.CONTAIN || scaleMode === ScaleMode.COVER) {\n boundRatioX = containerWidth / elementWidth;\n boundRatioY = containerHeight / elementHeight;\n }\n\n // get scale for bounds container\n switch (scaleMode) {\n case ScaleMode.CONTAIN:\n scale = boundRatioX < boundRatioY ? boundRatioX : boundRatioY;\n break;\n case ScaleMode.COVER:\n scale = boundRatioX > boundRatioY ? boundRatioX : boundRatioY;\n break;\n case ScaleMode.ALIGN_ONLY:\n targetWidth = elementWidth;\n targetHeight = elementHeight;\n break;\n }\n\n if (scaleMode === ScaleMode.CONTAIN || scaleMode === ScaleMode.COVER) {\n // get needed scale to fit in max with contain\n if (maxWidth || maxHeight) {\n let scaleMaxRatioX = scale;\n let scaleMaxRatioY = scale;\n\n if (maxWidth) {\n scaleMaxRatioX = maxWidth / elementWidth;\n }\n\n if (maxHeight) {\n scaleMaxRatioY = maxHeight / elementHeight;\n }\n\n const scaleMax = scaleMaxRatioX < scaleMaxRatioY ? scaleMaxRatioX : scaleMaxRatioY;\n\n scale = Math.min(scale, scaleMax);\n }\n\n // do the actual scale\n targetWidth = elementWidth * scale;\n targetHeight = elementHeight * scale;\n }\n\n return {\n width: Math.round(targetWidth),\n height: Math.round(targetHeight),\n x: Math.round((containerWidth - targetWidth) * alignmentX),\n y: Math.round((containerHeight - targetHeight) * alignmentY),\n };\n};\n\nconst useElementFit = (\n width: number,\n height: number,\n scaleMode: ScaleMode = ScaleMode.CONTAIN,\n alignmentX: number = 0.5,\n alignmentY: number = 0.5,\n maxWidth?: number | undefined,\n maxHeight?: number | undefined,\n): {\n ref: React.RefObject<HTMLElement>;\n width: number;\n x: number;\n y: number;\n height: number;\n} => {\n const [ref, containerWidth, containerHeight] = useResizeObserver();\n\n const [fitWidth, setFitWidth] = useState(1);\n const [fitHeight, setFitHeight] = useState(1);\n\n const [fitX, setFitX] = useState(1);\n const [fitY, setFitY] = useState(1);\n\n useEffect(() => {\n const { width: newWidth, height: newHeight, x, y } = resize(\n width,\n height,\n containerWidth,\n containerHeight,\n scaleMode,\n alignmentX,\n alignmentY,\n maxWidth,\n maxHeight,\n );\n\n setFitWidth(newWidth);\n setFitHeight(newHeight);\n setFitX(x);\n setFitY(y);\n }, [\n containerWidth,\n containerHeight,\n width,\n height,\n containerWidth,\n containerHeight,\n scaleMode,\n alignmentX,\n alignmentY,\n maxWidth,\n maxHeight,\n ]);\n\n return {\n ref,\n width: fitWidth,\n height: fitHeight,\n x: fitX,\n y: fitY,\n };\n};\n\nexport default useElementFit;\n"],"names":["ScaleMode","useState","useEffect"],"mappings":";;;;;;;;EAAA,IAAK,SAIJ;EAJD,WAAK,SAAS;MACZ,gCAAmB,CAAA;MACnB,4BAAe,CAAA;MACf,sCAAyB,CAAA;EAC3B,CAAC,EAJI,SAAS,KAAT,SAAS,QAIb;AAED,oBAAe,SAAS,CAAC;;ECFzB,MAAM,MAAM,GAAG,CACb,YAAoB,EACpB,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EACf,SAAS,EACT,UAAU,EACV,UAAU,EACV,QAAQ,EACR,SAAS,CACV,CAAC;UAEF,WAAW,CAAC,QAAQ,CAAC,CAAC;UACtB,YAAY,CAAC,SAAS,CAAC,CAAC;UACxB,OAAO,CAAC,CAAC,CAAC,CAAC;UACX,OAAO,CAAC,CAAC,CAAC,CAAC;OACZ,EAAE;UACD,cAAc;UACd,eAAe;UACf,KAAK;UACL,MAAM;UACN,cAAc;UACd,eAAe;UACf,SAAS;UACT,UAAU;UACV,UAAU;UACV,QAAQ;UACR,SAAS;OACV,CAAC,CAAC;MAEH,OAAO;UACL,GAAG;UACH,KAAK,EAAE,QAAQ;UACf,MAAM,EAAE,SAAS;UACjB,CAAC,EAAE,IAAI;UACP,CAAC,EAAE,IAAI;OACR,CAAC;EACJ,CAAC,CAAC;;;;;;;;;;;;;"}
{"version":3,"file":"index.js","sources":["../src/ScaleMode.ts","../src/useElementFit.ts"],"sourcesContent":["enum ScaleMode {\n CONTAIN = 'contain',\n COVER = 'cover',\n ALIGN_ONLY = 'align-only',\n}\n\nexport default ScaleMode;\n","import { useEffect, useState } from 'react';\nimport useResizeObserver from 'use-resize-observer';\nimport ScaleMode from './ScaleMode';\n\nconst resize = (\n elementWidth: number,\n elementHeight: number,\n containerWidth: number,\n containerHeight: number,\n scaleMode: ScaleMode,\n alignmentX: number = 0.5,\n alignmentY: number = 0.5,\n maxWidth?: number | undefined,\n maxHeight?: number | undefined,\n) => {\n let targetWidth: number = 0;\n let targetHeight: number = 0;\n let boundRatioX: number = 0;\n let boundRatioY: number = 0;\n let scale = 1;\n\n // get needed scale to fit in bounds with cover\n if (scaleMode === ScaleMode.CONTAIN || scaleMode === ScaleMode.COVER) {\n boundRatioX = containerWidth / elementWidth;\n boundRatioY = containerHeight / elementHeight;\n }\n\n // get scale for bounds container\n switch (scaleMode) {\n case ScaleMode.CONTAIN:\n scale = boundRatioX < boundRatioY ? boundRatioX : boundRatioY;\n break;\n case ScaleMode.COVER:\n scale = boundRatioX > boundRatioY ? boundRatioX : boundRatioY;\n break;\n case ScaleMode.ALIGN_ONLY:\n targetWidth = elementWidth;\n targetHeight = elementHeight;\n break;\n }\n\n if (scaleMode === ScaleMode.CONTAIN || scaleMode === ScaleMode.COVER) {\n // get needed scale to fit in max with contain\n if (maxWidth || maxHeight) {\n let scaleMaxRatioX = scale;\n let scaleMaxRatioY = scale;\n\n if (maxWidth) {\n scaleMaxRatioX = maxWidth / elementWidth;\n }\n\n if (maxHeight) {\n scaleMaxRatioY = maxHeight / elementHeight;\n }\n\n const scaleMax = scaleMaxRatioX < scaleMaxRatioY ? scaleMaxRatioX : scaleMaxRatioY;\n\n scale = Math.min(scale, scaleMax);\n }\n\n // do the actual scale\n targetWidth = elementWidth * scale;\n targetHeight = elementHeight * scale;\n }\n\n return {\n width: Math.round(targetWidth),\n height: Math.round(targetHeight),\n x: Math.round((containerWidth - targetWidth) * alignmentX),\n y: Math.round((containerHeight - targetHeight) * alignmentY),\n };\n};\n\nconst useElementFit = (\n width: number,\n height: number,\n scaleMode: ScaleMode = ScaleMode.CONTAIN,\n alignmentX: number = 0.5,\n alignmentY: number = 0.5,\n maxWidth?: number | undefined,\n maxHeight?: number | undefined,\n): {\n ref: React.RefObject<HTMLElement>;\n width: number;\n x: number;\n y: number;\n height: number;\n} => {\n const [ref, containerWidth, containerHeight] = useResizeObserver();\n\n const [fitWidth, setFitWidth] = useState(1);\n const [fitHeight, setFitHeight] = useState(1);\n\n const [fitX, setFitX] = useState(1);\n const [fitY, setFitY] = useState(1);\n\n useEffect(() => {\n const { width: newWidth, height: newHeight, x, y } = resize(\n width,\n height,\n containerWidth,\n containerHeight,\n scaleMode,\n alignmentX,\n alignmentY,\n maxWidth,\n maxHeight,\n );\n\n setFitWidth(newWidth);\n setFitHeight(newHeight);\n setFitX(x);\n setFitY(y);\n }, [\n containerWidth,\n containerHeight,\n width,\n height,\n containerWidth,\n containerHeight,\n scaleMode,\n alignmentX,\n alignmentY,\n maxWidth,\n maxHeight,\n ]);\n\n return {\n ref,\n width: fitWidth,\n height: fitHeight,\n x: fitX,\n y: fitY,\n };\n};\n\nexport default useElementFit;\n"],"names":["ScaleMode","useState","useEffect"],"mappings":";;;;;;;;EAAA,IAAK,SAIJ;EAJD,WAAK,SAAS;MACZ,gCAAmB,CAAA;MACnB,4BAAe,CAAA;MACf,sCAAyB,CAAA;EAC3B,CAAC,EAJI,SAAS,KAAT,SAAS,QAIb;AAED,oBAAe,SAAS,CAAC;;ECFzB,MAAM,MAAM,GAAG,CACb,YAAoB,EACpB,aAAqB,EACrB,cAAsB,EACtB,eAAuB,EACvB,SAAoB,EACpB,aAAqB,GAAG,EACxB,aAAqB,GAAG,EACxB,QAA6B,EAC7B,SAA8B;MAE9B,IAAI,WAAW,GAAW,CAAC,CAAC;MAC5B,IAAI,YAAY,GAAW,CAAC,CAAC;MAC7B,IAAI,WAAW,GAAW,CAAC,CAAC;MAC5B,IAAI,WAAW,GAAW,CAAC,CAAC;MAC5B,IAAI,KAAK,GAAG,CAAC,CAAC;;MAGd,IAAI,SAAS,KAAKA,WAAS,CAAC,OAAO,IAAI,SAAS,KAAKA,WAAS,CAAC,KAAK,EAAE;UACpE,WAAW,GAAG,cAAc,GAAG,YAAY,CAAC;UAC5C,WAAW,GAAG,eAAe,GAAG,aAAa,CAAC;OAC/C;;MAGD,QAAQ,SAAS;UACf,KAAKA,WAAS,CAAC,OAAO;cACpB,KAAK,GAAG,WAAW,GAAG,WAAW,GAAG,WAAW,GAAG,WAAW,CAAC;cAC9D,MAAM;UACR,KAAKA,WAAS,CAAC,KAAK;cAClB,KAAK,GAAG,WAAW,GAAG,WAAW,GAAG,WAAW,GAAG,WAAW,CAAC;cAC9D,MAAM;UACR,KAAKA,WAAS,CAAC,UAAU;cACvB,WAAW,GAAG,YAAY,CAAC;cAC3B,YAAY,GAAG,aAAa,CAAC;cAC7B,MAAM;OACT;MAED,IAAI,SAAS,KAAKA,WAAS,CAAC,OAAO,IAAI,SAAS,KAAKA,WA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AC,CAAC;MAE9C,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,GAAGA,cAAQ,CAAC,CAAC,CAAC,CAAC;MACpC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,GAAGA,cAAQ,CAAC,CAAC,CAAC,CAAC;MAEpCC,eAAS,CAAC;UACR,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,MAAM,CACzD,KAAK,EACL,MAAM,EACN,cAAc,EACd,eAAe,EACf,SAAS,EACT,UAAU,EACV,UAAU,EACV,QAAQ,EACR,SAAS,CACV,CAAC;UAEF,WAAW,CAAC,QAAQ,CAAC,CAAC;UACtB,YAAY,CAAC,SAAS,CAAC,CAAC;UACxB,OAAO,CAAC,CAAC,CAAC,CAAC;UACX,OAAO,CAAC,CAAC,CAAC,CAAC;OACZ,EAAE;UACD,cAAc;UACd,eAAe;UACf,KAAK;UACL,MAAM;UACN,cAAc;UACd,eAAe;UACf,SAAS;UACT,UAAU;UACV,UAAU;UACV,QAAQ;UACR,SAAS;OACV,CAAC,CAAC;MAEH,OAAO;UACL,GAAG;UACH,KAAK,EAAE,QAAQ;UACf,MAAM,EAAE,SAAS;UACjB,CAAC,EAAE,IAAI;UACP,CAAC,EAAE,IAAI;OACR,CAAC;EACJ,CAAC,CAAC;;;;;;;;;;;;;"}

@@ -1,1 +0,1 @@

{"version":3,"file":"index.min.js","sources":["../src/ScaleMode.ts","../src/useElementFit.ts"],"sourcesContent":["enum ScaleMode {\n CONTAIN = 'contain',\n COVER = 'cover',\n ALIGN_ONLY = 'align-only',\n}\n\nexport default ScaleMode;\n","import { RefObject, useEffect, useState } from 'react';\nimport useResizeObserver from 'use-resize-observer';\nimport ScaleMode from './ScaleMode';\n\nconst resize = (\n elementWidth: number,\n elementHeight: number,\n containerWidth: number,\n containerHeight: number,\n scaleMode: ScaleMode,\n alignmentX: number = 0.5,\n alignmentY: number = 0.5,\n maxWidth?: number | undefined,\n maxHeight?: number | undefined,\n) => {\n let targetWidth: number = 0;\n let targetHeight: number = 0;\n let boundRatioX: number = 0;\n let boundRatioY: number = 0;\n let scale = 1;\n\n // get needed scale to fit in bounds with cover\n if (scaleMode === ScaleMode.CONTAIN || scaleMode === ScaleMode.COVER) {\n boundRatioX = containerWidth / elementWidth;\n boundRatioY = containerHeight / elementHeight;\n }\n\n // get scale for bounds container\n switch (scaleMode) {\n case ScaleMode.CONTAIN:\n scale = boundRatioX < boundRatioY ? boundRatioX : boundRatioY;\n break;\n case ScaleMode.COVER:\n scale = boundRatioX > boundRatioY ? boundRatioX : boundRatioY;\n break;\n case ScaleMode.ALIGN_ONLY:\n targetWidth = elementWidth;\n targetHeight = elementHeight;\n break;\n }\n\n if (scaleMode === ScaleMode.CONTAIN || scaleMode === ScaleMode.COVER) {\n // get needed scale to fit in max with contain\n if (maxWidth || maxHeight) {\n let scaleMaxRatioX = scale;\n let scaleMaxRatioY = scale;\n\n if (maxWidth) {\n scaleMaxRatioX = maxWidth / elementWidth;\n }\n\n if (maxHeight) {\n scaleMaxRatioY = maxHeight / elementHeight;\n }\n\n const scaleMax = scaleMaxRatioX < scaleMaxRatioY ? scaleMaxRatioX : scaleMaxRatioY;\n\n scale = Math.min(scale, scaleMax);\n }\n\n // do the actual scale\n targetWidth = elementWidth * scale;\n targetHeight = elementHeight * scale;\n }\n\n return {\n width: Math.round(targetWidth),\n height: Math.round(targetHeight),\n x: Math.round((containerWidth - targetWidth) * alignmentX),\n y: Math.round((containerHeight - targetHeight) * alignmentY),\n };\n};\n\nconst useElementFit = (\n width: number,\n height: number,\n scaleMode: ScaleMode = ScaleMode.CONTAIN,\n alignmentX: number = 0.5,\n alignmentY: number = 0.5,\n maxWidth?: number | undefined,\n maxHeight?: number | undefined,\n): {\n ref: React.RefObject<HTMLElement>;\n width: number;\n x: number;\n y: number;\n height: number;\n} => {\n const [ref, containerWidth, containerHeight] = useResizeObserver();\n\n const [fitWidth, setFitWidth] = useState(1);\n const [fitHeight, setFitHeight] = useState(1);\n\n const [fitX, setFitX] = useState(1);\n const [fitY, setFitY] = useState(1);\n\n useEffect(() => {\n const { width: newWidth, height: newHeight, x, y } = resize(\n width,\n height,\n containerWidth,\n containerHeight,\n scaleMode,\n alignmentX,\n alignmentY,\n maxWidth,\n maxHeight,\n );\n\n setFitWidth(newWidth);\n setFitHeight(newHeight);\n setFitX(x);\n setFitY(y);\n }, [\n containerWidth,\n containerHeight,\n width,\n height,\n containerWidth,\n containerHeight,\n scaleMode,\n alignmentX,\n alignmentY,\n maxWidth,\n maxHeight,\n ]);\n\n return {\n ref,\n width: fitWidth,\n height: fitHeight,\n x: fitX,\n y: fitY,\n };\n};\n\nexport default useElementFit;\n"],"names":["ScaleMode","width","height","scaleMode","CONTAIN","alignmentX","alignmentY","maxWidth","maxHeight","ref","containerWidth","containerHeight","useResizeObserver","fitWidth","setFitWidth","useState","fitHeight","setFitHeight","fitX","setFitX","fitY","setFitY","useEffect","newWidth","newHeight","x","y","elementWidth","elementHeight","targetWidth","targetHeight","boundRatioX","boundRatioY","scale","COVER","ALIGN_ONLY","scaleMaxRatioX","scaleMaxRatioY","scaleMax","Math","min","round","resize"],"mappings":"wTAAA,IAAKA,+CAAL,SAAKA,GACHA,oBACAA,gBACAA,0BAHF,CAAKA,IAAAA,aAMUA,gCCmEO,CACpBC,EACAC,EACAC,EAAuBH,EAAUI,QACjCC,EAAqB,GACrBC,EAAqB,GACrBC,EACAC,KAQA,MAAOC,EAAKC,EAAgBC,GAAmBC,KAExCC,EAAUC,GAAeC,WAAS,IAClCC,EAAWC,GAAgBF,WAAS,IAEpCG,EAAMC,GAAWJ,WAAS,IAC1BK,EAAMC,GAAWN,WAAS,GAiCjC,OA/BAO,YAAU,KACR,MAAQrB,MAAOsB,EAAUrB,OAAQsB,EAASC,EAAEA,EAACC,EAAEA,GA7FpC,EACbC,EACAC,EACAlB,EACAC,EACAR,EACAE,EAAqB,GACrBC,EAAqB,GACrBC,EACAC,KAEA,IAAIqB,EAAsB,EACtBC,EAAuB,EACvBC,EAAsB,EACtBC,EAAsB,EACtBC,EAAQ,EASZ,OANI9B,IAAcH,EAAUI,SAAWD,IAAcH,EAAUkC,QAC7DH,EAAcrB,EAAiBiB,EAC/BK,EAAcrB,EAAkBiB,GAI1BzB,GACN,KAAKH,EAAUI,QACb6B,EAAQF,EAAcC,EAAcD,EAAcC,EAClD,MACF,KAAKhC,EAAUkC,MACbD,EAAQF,EAAcC,EAAcD,EAAcC,EAClD,MACF,KAAKhC,EAAUmC,WACbN,EAAcF,EACdG,EAAeF,EAInB,GAAIzB,IAAcH,EAAUI,SAAWD,IAAcH,EAAUkC,MAAO,CAEpE,GAAI3B,GAAYC,EAAW,CACzB,IAAI4B,EAAiBH,EACjBI,EAAiBJ,EAEjB1B,IACF6B,EAAiB7B,EAAWoB,GAG1BnB,IACF6B,EAAiB7B,EAAYoB,GAG/B,MAAMU,EAAWF,EAAiBC,EAAiBD,EAAiBC,EAEpEJ,EAAQM,KAAKC,IAAIP,EAAOK,GAI1BT,EAAcF,EAAeM,EAC7BH,EAAeF,EAAgBK,EAGjC,MAAO,CACLhC,MAAOsC,KAAKE,MAAMZ,GAClB3B,OAAQqC,KAAKE,MAAMX,GACnBL,EAAGc,KAAKE,OAAO/B,EAAiBmB,GAAexB,GAC/CqB,EAAGa,KAAKE,OAAO9B,EAAkBmB,GAAgBxB,KA4BIoC,CACnDzC,EACAC,EACAQ,EACAC,EACAR,EACAE,EACAC,EACAC,EACAC,GAGFM,EAAYS,GACZN,EAAaO,GACbL,EAAQM,GACRJ,EAAQK,IACP,CACDhB,EACAC,EACAV,EACAC,EACAQ,EACAC,EACAR,EACAE,EACAC,EACAC,EACAC,IAGK,CACLC,IAAAA,EACAR,MAAOY,EACPX,OAAQc,EACRS,EAAGP,EACHQ,EAAGN"}
{"version":3,"file":"index.min.js","sources":["../src/ScaleMode.ts","../src/useElementFit.ts"],"sourcesContent":["enum ScaleMode {\n CONTAIN = 'contain',\n COVER = 'cover',\n ALIGN_ONLY = 'align-only',\n}\n\nexport default ScaleMode;\n","import { useEffect, useState } from 'react';\nimport useResizeObserver from 'use-resize-observer';\nimport ScaleMode from './ScaleMode';\n\nconst resize = (\n elementWidth: number,\n elementHeight: number,\n containerWidth: number,\n containerHeight: number,\n scaleMode: ScaleMode,\n alignmentX: number = 0.5,\n alignmentY: number = 0.5,\n maxWidth?: number | undefined,\n maxHeight?: number | undefined,\n) => {\n let targetWidth: number = 0;\n let targetHeight: number = 0;\n let boundRatioX: number = 0;\n let boundRatioY: number = 0;\n let scale = 1;\n\n // get needed scale to fit in bounds with cover\n if (scaleMode === ScaleMode.CONTAIN || scaleMode === ScaleMode.COVER) {\n boundRatioX = containerWidth / elementWidth;\n boundRatioY = containerHeight / elementHeight;\n }\n\n // get scale for bounds container\n switch (scaleMode) {\n case ScaleMode.CONTAIN:\n scale = boundRatioX < boundRatioY ? boundRatioX : boundRatioY;\n break;\n case ScaleMode.COVER:\n scale = boundRatioX > boundRatioY ? boundRatioX : boundRatioY;\n break;\n case ScaleMode.ALIGN_ONLY:\n targetWidth = elementWidth;\n targetHeight = elementHeight;\n break;\n }\n\n if (scaleMode === ScaleMode.CONTAIN || scaleMode === ScaleMode.COVER) {\n // get needed scale to fit in max with contain\n if (maxWidth || maxHeight) {\n let scaleMaxRatioX = scale;\n let scaleMaxRatioY = scale;\n\n if (maxWidth) {\n scaleMaxRatioX = maxWidth / elementWidth;\n }\n\n if (maxHeight) {\n scaleMaxRatioY = maxHeight / elementHeight;\n }\n\n const scaleMax = scaleMaxRatioX < scaleMaxRatioY ? scaleMaxRatioX : scaleMaxRatioY;\n\n scale = Math.min(scale, scaleMax);\n }\n\n // do the actual scale\n targetWidth = elementWidth * scale;\n targetHeight = elementHeight * scale;\n }\n\n return {\n width: Math.round(targetWidth),\n height: Math.round(targetHeight),\n x: Math.round((containerWidth - targetWidth) * alignmentX),\n y: Math.round((containerHeight - targetHeight) * alignmentY),\n };\n};\n\nconst useElementFit = (\n width: number,\n height: number,\n scaleMode: ScaleMode = ScaleMode.CONTAIN,\n alignmentX: number = 0.5,\n alignmentY: number = 0.5,\n maxWidth?: number | undefined,\n maxHeight?: number | undefined,\n): {\n ref: React.RefObject<HTMLElement>;\n width: number;\n x: number;\n y: number;\n height: number;\n} => {\n const [ref, containerWidth, containerHeight] = useResizeObserver();\n\n const [fitWidth, setFitWidth] = useState(1);\n const [fitHeight, setFitHeight] = useState(1);\n\n const [fitX, setFitX] = useState(1);\n const [fitY, setFitY] = useState(1);\n\n useEffect(() => {\n const { width: newWidth, height: newHeight, x, y } = resize(\n width,\n height,\n containerWidth,\n containerHeight,\n scaleMode,\n alignmentX,\n alignmentY,\n maxWidth,\n maxHeight,\n );\n\n setFitWidth(newWidth);\n setFitHeight(newHeight);\n setFitX(x);\n setFitY(y);\n }, [\n containerWidth,\n containerHeight,\n width,\n height,\n containerWidth,\n containerHeight,\n scaleMode,\n alignmentX,\n alignmentY,\n maxWidth,\n maxHeight,\n ]);\n\n return {\n ref,\n width: fitWidth,\n height: fitHeight,\n x: fitX,\n y: fitY,\n };\n};\n\nexport default useElementFit;\n"],"names":["ScaleMode","width","height","scaleMode","CONTAIN","alignmentX","alignmentY","maxWidth","maxHeight","ref","containerWidth","containerHeight","useResizeObserver","fitWidth","setFitWidth","useState","fitHeight","setFitHeight","fitX","setFitX","fitY","setFitY","useEffect","newWidth","newHeight","x","y","elementWidth","elementHeight","targetWidth","targetHeight","boundRatioX","boundRatioY","scale","COVER","ALIGN_ONLY","scaleMaxRatioX","scaleMaxRatioY","scaleMax","Math","min","round","resize"],"mappings":"wTAAA,IAAKA,+CAAL,SAAKA,GACHA,oBACAA,gBACAA,0BAHF,CAAKA,IAAAA,aAMUA,gCCmEO,CACpBC,EACAC,EACAC,EAAuBH,EAAUI,QACjCC,EAAqB,GACrBC,EAAqB,GACrBC,EACAC,KAQA,MAAOC,EAAKC,EAAgBC,GAAmBC,KAExCC,EAAUC,GAAeC,WAAS,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GACRJ,EAAQK,IACP,CACDhB,EACAC,EACAV,EACAC,EACAQ,EACAC,EACAR,EACAE,EACAC,EACAC,EACAC,IAGK,CACLC,IAAAA,EACAR,MAAOY,EACPX,OAAQc,EACRS,EAAGP,EACHQ,EAAGN"}

@@ -1,5 +0,5 @@

import { RefObject } from 'react';
/// <reference types="react" />
import ScaleMode from './ScaleMode';
declare const useElementFit: (width: number, height: number, scaleMode?: ScaleMode, alignmentX?: number, alignmentY?: number, maxWidth?: number | undefined, maxHeight?: number | undefined) => {
ref: RefObject<HTMLElement>;
ref: import("react").RefObject<HTMLElement>;
width: number;

@@ -6,0 +6,0 @@ x: number;

{
"name": "use-element-fit",
"version": "0.1.0",
"version": "0.2.0",
"description": "use-element-fit",

@@ -66,2 +66,4 @@ "main": "dist/index.js",

"rollup": "1.12.0",
"rollup-plugin-commonjs": "^10.0.0",
"rollup-plugin-node-resolve": "^5.0.2",
"rollup-plugin-terser": "5.0.0",

@@ -68,0 +70,0 @@ "rollup-plugin-typescript2": "0.21.1",