code
stringlengths 10
343k
| docstring
stringlengths 36
21.9k
| func_name
stringlengths 1
3.35k
| language
stringclasses 1
value | repo
stringlengths 7
58
| path
stringlengths 4
131
| url
stringlengths 44
195
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|
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);
} | Creates a new instance of ResizeObserverController.
@private | ResizeObserverController ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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_();
}
}; | Adds observer to observers list.
@param {ResizeObserverSPI} observer - Observer to be added.
@returns {void} | ResizeObserverController.prototype.addObserver ( observer ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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_();
}
}; | Removes observer from observers list.
@param {ResizeObserverSPI} observer - Observer to be removed.
@returns {void} | ResizeObserverController.prototype.removeObserver ( observer ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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();
}
}; | Invokes the update of observers. It will continue running updates insofar
it detects changes.
@returns {void} | ResizeObserverController.prototype.refresh ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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;
}; | 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_ ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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;
}; | Initializes DOM listeners.
@private
@returns {void} | ResizeObserverController.prototype.connect_ ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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;
}; | Removes DOM listeners.
@private
@returns {void} | ResizeObserverController.prototype.disconnect_ ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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();
}
}; | "Transitionend" event handler.
@private
@param {TransitionEvent} event
@returns {void} | ResizeObserverController.prototype.onTransitionEnd_ ( _a ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
ResizeObserverController.getInstance = function () {
if (!this.instance_) {
this.instance_ = new ResizeObserverController();
}
return this.instance_;
}; | Returns instance of the ResizeObserverController.
@returns {ResizeObserverController} | ResizeObserverController.getInstance ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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;
}()); | Singleton controller class which handles updates of ResizeObserver instances. | (anonymous) ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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;
}); | 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. | (anonymous) ( target , props ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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;
}); | Returns the global object associated with provided element.
@param {Object} target
@returns {Object} | (anonymous) ( target ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
function toFloat(value) {
return parseFloat(value) || 0;
} | Converts provided string to a number.
@param {number|string} value
@returns {number} | toFloat ( value ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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 borders size from provided styles.
@param {CSSStyleDeclaration} styles
@param {...string} positions - Borders positions (top, right, ...)
@returns {number} | getBordersSize ( styles ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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;
} | Extracts paddings sizes from provided styles.
@param {CSSStyleDeclaration} styles
@returns {Object} Paddings box. | getPaddings ( styles ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
function getSVGContentRect(target) {
var bbox = target.getBBox();
return createRectInit(0, 0, bbox.width, bbox.height);
} | Calculates content rectangle of provided SVG element.
@param {SVGGraphicsElement} target - Element content rectangle of which needs
to be calculated.
@returns {DOMRectInit} | getSVGContentRect ( target ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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);
} | Calculates content rectangle of provided HTMLElement.
@param {HTMLElement} target - Element for which to calculate the content rectangle.
@returns {DOMRectInit} | getHTMLElementContentRect ( target ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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 an instance of the SVGGraphicsElement.
@param {Element} target - Element to be checked.
@returns {boolean} | (anonymous) ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
function isDocumentElement(target) {
return target === getWindowOf(target).document.documentElement;
} | Checks whether provided element is a document element (<html>).
@param {Element} target - Element to be checked.
@returns {boolean} | isDocumentElement ( target ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
function getContentRect(target) {
if (!isBrowser) {
return emptyRect;
}
if (isSVGGraphicsElement(target)) {
return getSVGContentRect(target);
}
return getHTMLElementContentRect(target);
} | 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} | getContentRect ( target ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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 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} | createReadOnlyRect ( _a ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
function createRectInit(x, y, width, height) {
return { x: x, y: y, width: width, height: height };
} | 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} | createRectInit ( x , y , width , height ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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;
} | Creates an instance of ResizeObservation.
@param {Element} target - Element to be observed. | ResizeObservation ( target ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
ResizeObservation.prototype.isActive = function () {
var rect = getContentRect(this.target);
this.contentRect_ = rect;
return (rect.width !== this.broadcastWidth ||
rect.height !== this.broadcastHeight);
}; | Updates content rectangle and tells whether it's width or height properties
have changed since the last broadcast.
@returns {boolean} | ResizeObservation.prototype.isActive ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
ResizeObservation.prototype.broadcastRect = function () {
var rect = this.contentRect_;
this.broadcastWidth = rect.width;
this.broadcastHeight = rect.height;
return rect;
}; | 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 ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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;
}()); | Class that is responsible for computations of the content rectangle of
provided DOM element and for keeping track of it's changes. | (anonymous) ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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 });
} | Creates an instance of ResizeObserverEntry.
@param {Element} target - Element that is being observed.
@param {DOMRectInit} rectInit - Data of the element's content rectangle. | ResizeObserverEntry ( target , rectInit ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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;
} | 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. | ResizeObserverSPI ( callback , controller , callbackCtx ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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();
}; | Starts observing provided element.
@param {Element} target - Element to be observed.
@returns {void} | ResizeObserverSPI.prototype.observe ( target ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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 provided element.
@param {Element} target - Element to stop observing.
@returns {void} | ResizeObserverSPI.prototype.unobserve ( target ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
ResizeObserverSPI.prototype.disconnect = function () {
this.clearActive();
this.observations_.clear();
this.controller_.removeObserver(this);
}; | Stops observing all elements.
@returns {void} | ResizeObserverSPI.prototype.disconnect ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
ResizeObserverSPI.prototype.gatherActive = function () {
var _this = this;
this.clearActive();
this.observations_.forEach(function (observation) {
if (observation.isActive()) {
_this.activeObservations_.push(observation);
}
});
}; | Collects observation instances the associated element of which has changed
it's content rectangle.
@returns {void} | ResizeObserverSPI.prototype.gatherActive ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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();
}; | Invokes initial callback function with a list of ResizeObserverEntry
instances collected from active resize observations.
@returns {void} | ResizeObserverSPI.prototype.broadcastActive ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
ResizeObserverSPI.prototype.clearActive = function () {
this.activeObservations_.splice(0);
}; | Clears the collection of active observations.
@returns {void} | ResizeObserverSPI.prototype.clearActive ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
ResizeObserverSPI.prototype.hasActive = function () {
return this.activeObservations_.length > 0;
}; | Tells whether observer has active observations.
@returns {boolean} | ResizeObserverSPI.prototype.hasActive ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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);
} | Creates a new instance of ResizeObserver.
@param {ResizeObserverCallback} callback - Callback that is invoked when
dimensions of the observed elements change. | ResizeObserver ( callback ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
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;
}()); | ResizeObserver API. Encapsulates the ResizeObserver SPI implementation
exposing only those methods and properties that are defined in the spec. | (anonymous) ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/ResizeObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js | MIT |
var getRecordIndex = function(map, recordKey) {
var hashedKey = hashKey(recordKey); // Casts key to unique string (unless already string or number)
if (hashedKey === false) {
// We have to iterate through our Map structure because `recordKey` is non-primitive and not extensible
return getRecordIndexSlow(map, recordKey);
}
var recordIndex = map._table[hashedKey]; // O(1) access to record
return recordIndex !== undefined ? recordIndex : false;
}; | getRecordIndex()
Function that given a Map and a key of `any` type, returns an index number that coorelates with a record found in `this._keys[index]` and `this._values[index]`
@param {Map} map - Map structure
@param {string|number|function|object} recordKey - Record key to normalize to string accessor for hash map
@returns {number|false} - Returns either a index to access map._keys and map._values, or false if not found | getRecordIndex ( map , recordKey ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.50.2/Map/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.50.2/Map/raw.js | MIT |
var getRecordIndexSlow = function(map, recordKey) {
// We have to iterate through our Map structure because `recordKey` is non-primitive and not extensible
for (var i = 0; i < map._keys.length; i++) {
var _recordKey = map._keys[i];
if (_recordKey !== undefMarker && SameValueZero(_recordKey, recordKey)) {
return i;
}
}
return false;
}; | getRecordIndexSlow()
Alternative (and slower) function to `getRecordIndex()`. Necessary for looking up non-extensible object keys.
@param {Map} map - Map structure
@param {string|number|function|object} recordKey - Record key to normalize to string accessor for hash map
@returns {number|false} - Returns either a index to access map._keys and map._values, or false if not found | getRecordIndexSlow ( map , recordKey ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.50.2/Map/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.50.2/Map/raw.js | MIT |
var setHashIndex = function(map, recordKey, recordIndex) {
var hashedKey = hashKey(recordKey);
if (!hashedKey) {
// If hashed key is false, the recordKey is an object which is not extensible.
// That indicates we cannot use the hash map for it, so this operation becomes no-op.
return false;
}
if (recordIndex === false) {
delete map._table[hashedKey];
} else {
map._table[hashedKey] = recordIndex;
}
return true;
}; | setHashIndex()
Function that given a map, key of `any` type, and a value, creates a new entry in Map hash table
@param {Map} map
@param {string|number|function|object} recordKey - Key to translate into normalized key for hash map
@param {number} recordIndex - record index
@returns {bool} - indicates success of operation | setHashIndex ( map , recordKey , recordIndex ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.50.2/Map/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.50.2/Map/raw.js | MIT |
var hashKey = function(recordKey) {
// Check to see if we are dealing with object or function type.
if (typeof recordKey === 'object' ? recordKey !== null : typeof recordKey === 'function') {
// Check to see if we are dealing with a non extensible object
if (!Object.isExtensible(recordKey)) {
// Return `false`
return false;
}
if (!recordKey[_metaKey]) {
var uniqueHashKey = typeof(recordKey)+'-'+(++_uniqueHashId);
Object.defineProperty(recordKey, _metaKey, {
configurable: false,
enumerable: false,
writable: false,
value: uniqueHashKey
});
}
// Return previously defined hashed key
return recordKey[_metaKey];
}
// If this is just a primitive, we can cast it to a string and return it
return ''+recordKey;
};
/**
* getRecordIndex()
* Function that given a Map and a key of `any` type, returns an index number that coorelates with a record found in `this._keys[index]` and `this._values[index]`
* @param {Map} map - Map structure
* @param {string|number|function|object} recordKey - Record key to normalize to string accessor for hash map
* @returns {number|false} - Returns either a index to access map._keys and map._values, or false if not found
*/
var getRecordIndex = function(map, recordKey) {
var hashedKey = hashKey(recordKey); // Casts key to unique string (unless already string or number)
if (hashedKey === false) {
// We have to iterate through our Map structure because `recordKey` is non-primitive and not extensible
return getRecordIndexSlow(map, recordKey);
}
var recordIndex = map._table[hashedKey]; // O(1) access to record
return recordIndex !== undefined ? recordIndex : false;
};
/**
* getRecordIndexSlow()
* Alternative (and slower) function to `getRecordIndex()`. Necessary for looking up non-extensible object keys.
* @param {Map} map - Map structure
* @param {string|number|function|object} recordKey - Record key to normalize to string accessor for hash map
* @returns {number|false} - Returns either a index to access map._keys and map._values, or false if not found
*/
var getRecordIndexSlow = function(map, recordKey) {
// We have to iterate through our Map structure because `recordKey` is non-primitive and not extensible
for (var i = 0; i < map._keys.length; i++) {
var _recordKey = map._keys[i];
if (_recordKey !== undefMarker && SameValueZero(_recordKey, recordKey)) {
return i;
}
}
return false;
};
/**
* setHashIndex()
* Function that given a map, key of `any` type, and a value, creates a new entry in Map hash table
* @param {Map} map
* @param {string|number|function|object} recordKey - Key to translate into normalized key for hash map
* @param {number} recordIndex - record index
* @returns {bool} - indicates success of operation
*/
var setHashIndex = function(map, recordKey, recordIndex) {
var hashedKey = hashKey(recordKey);
if (!hashedKey) {
// If hashed key is false, the recordKey is an object which is not extensible.
// That indicates we cannot use the hash map for it, so this operation becomes no-op.
return false;
}
if (recordIndex === false) {
delete map._table[hashedKey];
} else {
map._table[hashedKey] = recordIndex;
}
return true;
};
// Deleted map items mess with iterator pointers, so rather than removing them mark them as deleted. Can't use undefined or null since those both valid keys so use a private symbol.
var undefMarker = Symbol('undef');
// 23.1.1.1 Map ( [ iterable ] )
var Map = function Map(/* iterable */) {
// 1. If NewTarget is undefined, throw a TypeError exception.
if (!(this instanceof Map)) {
throw new TypeError('Constructor Map requires "new"');
}
// 2. Let map be ? OrdinaryCreateFromConstructor(NewTarget, "%MapPrototype%", « [[MapData]] »).
var map = OrdinaryCreateFromConstructor(this, Map.prototype, {
_table: {}, // O(1) access table for retrieving records
_keys: [],
_values: [],
_size: 0,
_es6Map: true
});
// 3. Set map.[[MapData]] to a new empty List.
// Polyfill.io - This step was done as part of step two.
// Some old engines do not support ES5 getters/setters. Since Map only requires these for the size property, we can fall back to setting the size property statically each time the size of the map changes.
if (!supportsGetters) {
Object.defineProperty(map, 'size', {
configurable: true,
enumerable: false,
writable: true,
value: 0
});
}
// 4. If iterable is not present, let iterable be undefined.
var iterable = arguments.length > 0 ? arguments[0] : undefined;
// 5. If iterable is either undefined or null, return map.
if (iterable === null || iterable === undefined) {
return map;
}
// 6. Let adder be ? Get(map, "set").
var adder = map.set;
// 7. If IsCallable(adder) is false, throw a TypeError exception.
if (!IsCallable(adder)) {
throw new TypeError("Map.prototype.set is not a function");
}
// 8. Let iteratorRecord be ? GetIterator(iterable).
try {
var iteratorRecord = GetIterator(iterable);
// 9. Repeat,
// eslint-disable-next-line no-constant-condition
while (true) {
// a. Let next be ? IteratorStep(iteratorRecord).
var next = IteratorStep(iteratorRecord);
// b. If next is false, return map.
if (next === false) {
return map;
}
// c. Let nextItem be ? IteratorValue(next).
var nextItem = IteratorValue(next);
// d. If Type(nextItem) is not Object, then
if (Type(nextItem) !== 'object') {
// i. Let error be Completion{[[Type]]: throw, [[Value]]: a newly created TypeError object, [[Target]]: empty}.
try {
throw new TypeError('Iterator value ' + nextItem + ' is not an entry object');
} catch (error) {
// ii. Return ? IteratorClose(iteratorRecord, error).
return IteratorClose(iteratorRecord, error);
}
}
try {
// Polyfill.io - The try catch accounts for steps: f, h, and j.
// e. Let k be Get(nextItem, "0").
var k = nextItem[0];
// f. If k is an abrupt completion, return ? IteratorClose(iteratorRecord, k).
// g. Let v be Get(nextItem, "1").
var v = nextItem[1];
// h. If v is an abrupt completion, return ? IteratorClose(iteratorRecord, v).
// i. Let status be Call(adder, map, « k.[[Value]], v.[[Value]] »).
adder.call(map, k, v);
} catch (e) {
// j. If status is an abrupt completion, return ? IteratorClose(iteratorRecord, status).
return IteratorClose(iteratorRecord, e);
}
}
} catch (e) {
// Polyfill.io - For user agents which do not have iteration methods on argument objects or arrays, we can special case those.
if (Array.isArray(iterable) ||
Object.prototype.toString.call(iterable) === '[object Arguments]' ||
// IE 7 & IE 8 return '[object Object]' for the arguments object, we can detect by checking for the existence of the callee property
(!!iterable.callee)) {
var index;
var length = iterable.length;
for (index = 0; index < length; index++) {
adder.call(map, iterable[index][0], iterable[index][1]);
}
}
}
return map;
};
// 23.1.2.1. Map.prototype
// The initial value of Map.prototype is the intrinsic object %MapPrototype%.
// This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.
Object.defineProperty(Map, 'prototype', {
configurable: false,
enumerable: false,
writable: false,
value: {}
});
// 23.1.2.2 get Map [ @@species ]
if (supportsGetters) {
Object.defineProperty(Map, Symbol.species, {
configurable: true,
enumerable: false,
get: function () {
// 1. Return the this value.
return this;
},
set: undefined
});
} else {
CreateMethodProperty(Map, Symbol.species, Map);
}
// 23.1.3.1 Map.prototype.clear ( )
CreateMethodProperty(Map.prototype, 'clear', function clear() {
// 1. Let M be the this value.
var M = this;
// 2. If Type(M) is not Object, throw a TypeError exception.
if (Type(M) !== 'object') {
throw new TypeError('Method Map.prototype.clear called on incompatible receiver ' + Object.prototype.toString.call(M));
}
// 3. If M does not have a [[MapData]] internal slot, throw a TypeError exception.
if (M._es6Map !== true) {
throw new TypeError('Method Map.prototype.clear called on incompatible receiver ' + Object.prototype.toString.call(M));
}
// 4. Let entries be the List that is M.[[MapData]].
var entries = M._keys;
// 5. For each Record {[[Key]], [[Value]]} p that is an element of entries, do
for (var i = 0; i < entries.length; i++) {
// 5.a. Set p.[[Key]] to empty.
M._keys[i] = undefMarker;
// 5.b. Set p.[[Value]] to empty.
M._values[i] = undefMarker;
}
this._size = 0;
if (!supportsGetters) {
this.size = this._size;
}
// 5a. Clear lookup table
this._table = {};
// 6. Return undefined.
return undefined;
}
);
// 23.1.3.2. Map.prototype.constructor
CreateMethodProperty(Map.prototype, 'constructor', Map);
// 23.1.3.3. Map.prototype.delete ( key )
CreateMethodProperty(Map.prototype, 'delete', function (key) {
// 1. Let M be the this value.
var M = this;
// 2. If Type(M) is not Object, throw a TypeError exception.
if (Type(M) !== 'object') {
throw new TypeError('Method Map.prototype.clear called on incompatible receiver ' + Object.prototype.toString.call(M));
}
// 3. If M does not have a [[MapData]] internal slot, throw a TypeError exception.
if (M._es6Map !== true) {
throw new TypeError('Method Map.prototype.clear called on incompatible receiver ' + Object.prototype.toString.call(M));
}
// 4. Let entries be the List that is M.[[MapData]].
// 5. For each Record {[[Key]], [[Value]]} p that is an element of entries, do
// 5a. If p.[[Key]] is not empty and SameValueZero(p.[[Key]], key) is true, then
// i. Set p.[[Key]] to empty.
// ii. Set p.[[Value]] to empty.
// ii-a. Remove key from lookup table
// iii. Return true.
// 6. Return false.
// Implement steps 4-6 with a more optimal algo
// Steps 4-5: Access record
var recordIndex = getRecordIndex(M, key); // O(1) access to record index
if (recordIndex !== false) {
// Get record's `key` (could be `any` type);
var recordKey = M._keys[recordIndex];
// 5a. If p.[[Key]] is not empty and SameValueZero(p.[[Key]], key) is true, then
if (recordKey !== undefMarker && SameValueZero(recordKey, key)) {
// i. Set p.[[Key]] to empty.
this._keys[recordIndex] = undefMarker;
// ii. Set p.[[Value]] to empty.
this._values[recordIndex] = undefMarker;
this._size = --this._size;
if (!supportsGetters) {
this.size = this._size;
}
// iia. Remove key from lookup table
setHashIndex(this, key, false);
// iii. Return true.
return true;
}
}
// 6. Return false.
return false;
}
);
// 23.1.3.4. Map.prototype.entries ( )
CreateMethodProperty(Map.prototype, 'entries', function entries () {
// 1. Let M be the this value.
var M = this;
// 2. Return ? CreateMapIterator(M, "key+value").
return CreateMapIterator(M, 'key+value');
}
);
// 23.1.3.5. Map.prototype.forEach ( callbackfn [ , thisArg ] )
CreateMethodProperty(Map.prototype, 'forEach', function (callbackFn) {
// 1. Let M be the this value.
var M = this;
// 2. If Type(M) is not Object, throw a TypeError exception.
if (Type(M) !== 'object') {
throw new TypeError('Method Map.prototype.forEach called on incompatible receiver ' + Object.prototype.toString.call(M));
}
// 3. If M does not have a [[MapData]] internal slot, throw a TypeError exception.
if (M._es6Map !== true) {
throw new TypeError('Method Map.prototype.forEach called on incompatible receiver ' + Object.prototype.toString.call(M));
}
// 4. If IsCallable(callbackfn) is false, throw a TypeError exception.
if (!IsCallable(callbackFn)) {
throw new TypeError(Object.prototype.toString.call(callbackFn) + ' is not a function.');
}
// 5. If thisArg is present, let T be thisArg; else let T be undefined.
if (arguments[1]) {
var T = arguments[1];
}
// 6. Let entries be the List that is M.[[MapData]].
var entries = M._keys;
// 7. For each Record {[[Key]], [[Value]]} e that is an element of entries, in original key insertion order, do
for (var i = 0; i < entries.length; i++) {
// a. If e.[[Key]] is not empty, then
if (M._keys[i] !== undefMarker && M._values[i] !== undefMarker ) {
// i. Perform ? Call(callbackfn, T, « e.[[Value]], e.[[Key]], M »).
callbackFn.call(T, M._values[i], M._keys[i], M);
}
}
// 8. Return undefined.
return undefined;
}
);
// 23.1.3.6. Map.prototype.get ( key )
CreateMethodProperty(Map.prototype, 'get', function get(key) {
// 1. Let M be the this value.
var M = this;
// 2. If Type(M) is not Object, throw a TypeError exception.
if (Type(M) !== 'object') {
throw new TypeError('Method Map.prototype.get called on incompatible receiver ' + Object.prototype.toString.call(M));
}
// 3. If M does not have a [[MapData]] internal slot, throw a TypeError exception.
if (M._es6Map !== true) {
throw new TypeError('Method Map.prototype.get called on incompatible receiver ' + Object.prototype.toString.call(M));
}
// 4. Let entries be the List that is M.[[MapData]].
// 5. For each Record {[[Key]], [[Value]]} p that is an element of entries, do
// a. If p.[[Key]] is not empty and SameValueZero(p.[[Key]], key) is true, return p.[[Value]].
// 6. Return undefined.
// Implement steps 4-6 with a more optimal algo
var recordIndex = getRecordIndex(M, key); // O(1) access to record index
if (recordIndex !== false) {
var recordKey = M._keys[recordIndex];
if (recordKey !== undefMarker && SameValueZero(recordKey, key)) {
return M._values[recordIndex];
}
}
return undefined;
});
// 23.1.3.7. Map.prototype.has ( key )
CreateMethodProperty(Map.prototype, 'has', function has (key) {
// 1. Let M be the this value.
var M = this;
// 2. If Type(M) is not Object, throw a TypeError exception.
if (typeof M !== 'object') {
throw new TypeError('Method Map.prototype.has called on incompatible receiver ' + Object.prototype.toString.call(M));
}
// 3. If M does not have a [[MapData]] internal slot, throw a TypeError exception.
if (M._es6Map !== true) {
throw new TypeError('Method Map.prototype.has called on incompatible receiver ' + Object.prototype.toString.call(M));
}
// 4. Let entries be the List that is M.[[MapData]].
// 5. For each Record {[[Key]], [[Value]]} p that is an element of entries, do
// a. If p.[[Key]] is not empty and SameValueZero(p.[[Key]], key) is true, return true.
// 6. Return false.
// Implement steps 4-6 with a more optimal algo
var recordIndex = getRecordIndex(M, key); // O(1) access to record index
if (recordIndex !== false) {
var recordKey = M._keys[recordIndex];
if (recordKey !== undefMarker && SameValueZero(recordKey, key)) {
return true;
}
}
return false;
});
// 23.1.3.8. Map.prototype.keys ( )
CreateMethodProperty(Map.prototype, 'keys', function keys () {
// 1. Let M be the this value.
var M = this;
// 2. Return ? CreateMapIterator(M, "key").
return CreateMapIterator(M, "key");
});
// 23.1.3.9. Map.prototype.set ( key, value )
CreateMethodProperty(Map.prototype, 'set', function set(key, value) {
// 1. Let M be the this value.
var M = this;
// 2. If Type(M) is not Object, throw a TypeError exception.
if (Type(M) !== 'object') {
throw new TypeError('Method Map.prototype.set called on incompatible receiver ' + Object.prototype.toString.call(M));
}
// 3. If M does not have a [[MapData]] internal slot, throw a TypeError exception.
if (M._es6Map !== true) {
throw new TypeError('Method Map.prototype.set called on incompatible receiver ' + Object.prototype.toString.call(M));
}
// 4. Let entries be the List that is M.[[MapData]].
// 5. For each Record {[[Key]], [[Value]]} p that is an element of entries, do
// 6. If key is -0, let key be +0.
// 7. Let p be the Record {[[Key]]: key, [[Value]]: value}.
// 8. Append p as the last element of entries.
// 9. Return M.
// Strictly following the above steps 4-9 will lead to an inefficient algorithm.
// Step 8 also doesn't seem to be required if an entry already exists
var recordIndex = getRecordIndex(M, key); // O(1) access to record index
if (recordIndex !== false) {
// update path
M._values[recordIndex] = value;
} else {
// eslint-disable-next-line no-compare-neg-zero
if (key === -0) {
key = 0;
}
var p = {
'[[Key]]': key,
'[[Value]]': value
};
M._keys.push(p['[[Key]]']);
M._values.push(p['[[Value]]']);
setHashIndex(M, key, M._keys.length - 1); // update lookup table
++M._size;
if (!supportsGetters) {
M.size = M._size;
}
}
return M;
});
// 23.1.3.10. get Map.prototype.size
if (supportsGetters) {
Object.defineProperty(Map.prototype, 'size', {
configurable: true,
enumerable: false,
get: function () {
// 1. Let M be the this value.
var M = this;
// 2. If Type(M) is not Object, throw a TypeError exception.
if (Type(M) !== 'object') {
throw new TypeError('Method Map.prototype.size called on incompatible receiver ' + Object.prototype.toString.call(M));
}
// 3. If M does not have a [[MapData]] internal slot, throw a TypeError exception.
if (M._es6Map !== true) {
throw new TypeError('Method Map.prototype.size called on incompatible receiver ' + Object.prototype.toString.call(M));
}
// 4. Let entries be the List that is M.[[MapData]].
// 5. Let count be 0.
// 6. For each Record {[[Key]], [[Value]]} p that is an element of entries, do
// 6a. If p.[[Key]] is not empty, set count to count+1.
// 7. Return count.
// Implement 4-7 more efficently by returning pre-computed property
return this._size;
},
set: undefined
});
}
// 23.1.3.11. Map.prototype.values ( )
CreateMethodProperty(Map.prototype, 'values', function values () {
// 1. Let M be the this value.
var M = this;
// 2. Return ? CreateMapIterator(M, "value").
return CreateMapIterator(M, 'value');
}
);
// 23.1.3.12. Map.prototype [ @@iterator ] ( )
// The initial value of the @@iterator property is the same function object as the initial value of the entries property.
CreateMethodProperty(Map.prototype, Symbol.iterator, Map.prototype.entries);
// 23.1.3.13. Map.prototype [ @@toStringTag ]
// The initial value of the @@toStringTag property is the String value "Map".
// This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.
// Polyfill.io - Safari 8 implements Map.name but as a non-configurable property, which means it would throw an error if we try and configure it here.
if (!('name' in Map)) {
// 19.2.4.2 name
Object.defineProperty(Map, 'name', {
configurable: true,
enumerable: false,
writable: false,
value: 'Map'
});
}
// 23.1.5.1. CreateMapIterator ( map, kind )
function CreateMapIterator(map, kind) {
// 1. If Type(map) is not Object, throw a TypeError exception.
if (Type(map) !== 'object') {
throw new TypeError('createMapIterator called on incompatible receiver ' + Object.prototype.toString.call(map));
}
// 2. If map does not have a [[MapData]] internal slot, throw a TypeError exception.
if (map._es6Map !== true) {
throw new TypeError('createMapIterator called on incompatible receiver ' + Object.prototype.toString.call(map));
}
// 3. Let iterator be ObjectCreate(%MapIteratorPrototype%, « [[Map]], [[MapNextIndex]], [[MapIterationKind]] »).
var iterator = Object.create(MapIteratorPrototype);
// 4. Set iterator.[[Map]] to map.
Object.defineProperty(iterator, '[[Map]]', {
configurable: true,
enumerable: false,
writable: true,
value: map
});
// 5. Set iterator.[[MapNextIndex]] to 0.
Object.defineProperty(iterator, '[[MapNextIndex]]', {
configurable: true,
enumerable: false,
writable: true,
value: 0
});
// 6. Set iterator.[[MapIterationKind]] to kind.
Object.defineProperty(iterator, '[[MapIterationKind]]', {
configurable: true,
enumerable: false,
writable: true,
value: kind
});
// 7. Return iterator.
return iterator;
}
// 23.1.5.2. The %MapIteratorPrototype% Object
var MapIteratorPrototype = {};
// Polyfill.io - We use this as a quick way to check if an object is a Map Iterator instance.
Object.defineProperty(MapIteratorPrototype, 'isMapIterator', {
configurable: false,
enumerable: false,
writable: false,
value: true
});
// 23.1.5.2.1. %MapIteratorPrototype%.next ( )
CreateMethodProperty(MapIteratorPrototype, 'next', function next() {
// 1. Let O be the this value.
var O = this;
// 2. If Type(O) is not Object, throw a TypeError exception.
if (Type(O) !== 'object') {
throw new TypeError('Method %MapIteratorPrototype%.next called on incompatible receiver ' + Object.prototype.toString.call(O));
}
// 3. If O does not have all of the internal slots of a Map Iterator Instance (23.1.5.3), throw a TypeError exception.
if (!O.isMapIterator) {
throw new TypeError('Method %MapIteratorPrototype%.next called on incompatible receiver ' + Object.prototype.toString.call(O));
}
// 4. Let m be O.[[Map]].
var m = O['[[Map]]'];
// 5. Let index be O.[[MapNextIndex]].
var index = O['[[MapNextIndex]]'];
// 6. Let itemKind be O.[[MapIterationKind]].
var itemKind = O['[[MapIterationKind]]'];
// 7. If m is undefined, return CreateIterResultObject(undefined, true).
if (m === undefined) {
return CreateIterResultObject(undefined, true);
}
// 8. Assert: m has a [[MapData]] internal slot.
if (!m._es6Map) {
throw new Error(Object.prototype.toString.call(m) + ' has a [[MapData]] internal slot.');
}
// 9. Let entries be the List that is m.[[MapData]].
var entries = m._keys;
// 10. Let numEntries be the number of elements of entries.
var numEntries = entries.length;
// 11. NOTE: numEntries must be redetermined each time this method is evaluated.
// 12. Repeat, while index is less than numEntries,
while (index < numEntries) {
// a. Let e be the Record {[[Key]], [[Value]]} that is the value of entries[index].
var e = Object.create(null);
e['[[Key]]'] = m._keys[index];
e['[[Value]]'] = m._values[index];
// b. Set index to index+1.
index = index + 1;
// c. Set O.[[MapNextIndex]] to index.
O['[[MapNextIndex]]'] = index;
// d. If e.[[Key]] is not empty, then
if (e['[[Key]]'] !== undefMarker) {
// i. If itemKind is "key", let result be e.[[Key]].
if (itemKind === 'key') {
var result = e['[[Key]]'];
// ii. Else if itemKind is "value", let result be e.[[Value]].
} else if (itemKind === 'value') {
result = e['[[Value]]'];
// iii. Else,
} else {
// 1. Assert: itemKind is "key+value".
if (itemKind !== 'key+value') {
throw new Error();
}
// 2. Let result be CreateArrayFromList(« e.[[Key]], e.[[Value]] »).
result = [
e['[[Key]]'],
e['[[Value]]']
];
}
// iv. Return CreateIterResultObject(result, false).
return CreateIterResultObject(result, false);
}
}
// 13. Set O.[[Map]] to undefined.
O['[[Map]]'] = undefined;
// 14. Return CreateIterResultObject(undefined, true).
return CreateIterResultObject(undefined, true);
}
);
// 23.1.5.2.2 %MapIteratorPrototype% [ @@toStringTag ]
// The initial value of the @@toStringTag property is the String value "Map Iterator".
// This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.
CreateMethodProperty(MapIteratorPrototype, Symbol.iterator, function iterator() {
return this;
}
);
// Export the object
try {
CreateMethodProperty(global, 'Map', Map);
} catch (e) {
// IE8 throws an error here if we set enumerable to false.
// More info on table 2: https://msdn.microsoft.com/en-us/library/dd229916(v=vs.85).aspx
global.Map = Map;
}
}(self)); | hashKey()
Function that given a key of `any` type, returns a string key value to enable hash map optimization for accessing Map data structure
@param {string|integer|function|object} recordKey - Record key to normalize to string accessor for hash map
@returns {string|false} - Returns a hashed string value or false if non extensible object key | hashKey ( recordKey ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.50.2/Map/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.50.2/Map/raw.js | MIT |
function toObject(arg) {
if (arg == null) {
throw new TypeError('undefined/null cannot be converted to object');
}
return Object(arg);
} | https://tc39.es/ecma262/#sec-toobject
@param arg | toObject ( arg ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.48.0/Intl.PluralRules/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.48.0/Intl.PluralRules/raw.js | MIT |
function getOption(opts, prop, type, values, fallback) {
// const descriptor = Object.getOwnPropertyDescriptor(opts, prop);
var value = opts[prop];
if (value !== undefined) {
if (type !== 'boolean' && type !== 'string') {
throw new TypeError('invalid type');
}
if (type === 'boolean') {
value = new Boolean(value);
}
if (type === 'string') {
value = new String(value);
}
if (values !== undefined && !values.filter(function (val) { return val == value; }).length) {
throw new RangeError(value + " in not within " + values);
}
return value;
}
return fallback;
} | https://tc39.es/ecma402/#sec-getoption
@param opts
@param prop
@param type
@param values
@param fallback | getOption ( opts , prop , type , values , fallback ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.48.0/Intl.PluralRules/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.48.0/Intl.PluralRules/raw.js | MIT |
function defaultNumberOption(val, min, max, fallback) {
if (val !== undefined) {
val = Number(val);
if (isNaN(val) || val < min || val > max) {
throw new RangeError(val + " is outside of range [" + min + ", " + max + "]");
}
return Math.floor(val);
}
return fallback;
} | https://tc39.es/ecma402/#sec-defaultnumberoption
@param val
@param min
@param max
@param fallback | defaultNumberOption ( val , min , max , fallback ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.48.0/Intl.PluralRules/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.48.0/Intl.PluralRules/raw.js | MIT |
function getNumberOption(options, property, min, max, fallback) {
var val = options[property];
return defaultNumberOption(val, min, max, fallback);
} | https://tc39.es/ecma402/#sec-getnumberoption
@param options
@param property
@param min
@param max
@param fallback | getNumberOption ( options , property , min , max , fallback ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.48.0/Intl.PluralRules/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.48.0/Intl.PluralRules/raw.js | MIT |
function setNumberFormatDigitOptions(pl, opts, mnfdDefault, mxfdDefault) {
var mnid = getNumberOption(opts, 'minimumIntegerDigits', 1, 21, 1);
var mnfd = getNumberOption(opts, 'minimumFractionDigits', 0, 20, mnfdDefault);
var mxfdActualDefault = Math.max(mnfd, mxfdDefault);
var mxfd = getNumberOption(opts, 'maximumFractionDigits', mnfd, 20, mxfdActualDefault);
var mnsd = opts.minimumSignificantDigits;
var mxsd = opts.maximumSignificantDigits;
pl['[[MinimumIntegerDigits]]'] = mnid;
pl['[[MinimumFractionDigits]]'] = mnfd;
pl['[[MaximumFractionDigits]]'] = mxfd;
if (mnsd !== undefined || mxsd !== undefined) {
mnsd = defaultNumberOption(mnsd, 1, 21, 1);
mxsd = defaultNumberOption(mxsd, mnsd, 21, 21);
pl['[[MinimumSignificantDigits]]'] = mnsd;
pl['[[MaximumSignificantDigits]]'] = mxsd;
}
} | https://tc39.es/ecma402/#sec-setnfdigitoptions
@param pl
@param opts
@param mnfdDefault
@param mxfdDefault | setNumberFormatDigitOptions ( pl , opts , mnfdDefault , mxfdDefault ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.48.0/Intl.PluralRules/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.48.0/Intl.PluralRules/raw.js | MIT |
!function(a,b){function c(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function d(){var a=t.elements;return"string"==typeof a?a.split(" "):a}function e(a,b){var c=t.elements;"string"!=typeof c&&(c=c.join(" ")),"string"!=typeof a&&(a=a.join(" ")),t.elements=c+" "+a,j(b)}function f(a){var b=s[a[q]];return b||(b={},r++,a[q]=r,s[r]=b),b}function g(a,c,d){if(c||(c=b),l)return c.createElement(a);d||(d=f(c));var e;return e=d.cache[a]?d.cache[a].cloneNode():p.test(a)?(d.cache[a]=d.createElem(a)).cloneNode():d.createElem(a),!e.canHaveChildren||o.test(a)||e.tagUrn?e:d.frag.appendChild(e)}function h(a,c){if(a||(a=b),l)return a.createDocumentFragment();c=c||f(a);for(var e=c.frag.cloneNode(),g=0,h=d(),i=h.length;i>g;g++)e.createElement(h[g]);return e}function i(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return t.shivMethods?g(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+d().join().replace(/[\w\-:]+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(t,b.frag)}function j(a){a||(a=b);var d=f(a);return!t.shivCSS||k||d.hasCSS||(d.hasCSS=!!c(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),l||i(a,d),a}var k,l,m="3.7.3-pre",n=a.html5||{},o=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,p=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,q="_html5shiv",r=0,s={};!function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",k="hidden"in a,l=1==a.childNodes.length||function(){b.createElement("a");var a=b.createDocumentFragment();return"undefined"==typeof a.cloneNode||"undefined"==typeof a.createDocumentFragment||"undefined"==typeof a.createElement}()}catch(c){k=!0,l=!0}}();var t={elements:n.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:m,shivCSS:n.shivCSS!==!1,supportsUnknownElements:l,shivMethods:n.shivMethods!==!1,type:"default",shivDocument:j,createElement:g,createDocumentFragment:h,addElements:e};a.html5=t,j(b),"object"==typeof module&&module.exports&&(module.exports=t)}("undefined"!=typeof window?window:this,document); | @preserve HTML5 Shiv 3.7.3 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed | c ( a , b ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.40.0/~html5-elements/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.40.0/~html5-elements/raw.js | MIT |
global.cancelIdleCallback = function cancelIdleCallback(id) {
if(arguments.length === 0) {
throw new TypeError('cancelIdleCallback requires at least 1 argument');
}
var callbackFilter = function (callbackObject) {
return callbackObject.id !== id;
};
// Find and remove the callback from the scheduled idle callbacks,
// and nested callbacks (cancelIdleCallback may be called in an idle period).
scheduledCallbacks = scheduledCallbacks.filter(callbackFilter);
nestedCallbacks = nestedCallbacks.filter(callbackFilter);
}; | @param {number} - The idle callback identifier to cancel.
@return {undefined} | cancelIdleCallback ( id ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.42.0/requestIdleCallback/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.42.0/requestIdleCallback/raw.js | MIT |
global.IdleDeadline = function IdleDeadline() {
if (!allowIdleDeadlineConstructor) {
throw new TypeError('Illegal constructor');
}
}; | IdleDeadline Polyfill
@example
requestIdleCallback(function (deadline) {
console.log(deadline instanceof IdleDeadline); // true
}); | IdleDeadline ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.42.0/requestIdleCallback/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.42.0/requestIdleCallback/raw.js | MIT |
global.requestIdleCallback = function requestIdleCallback(callback, options) {
var id = ++idleCallbackIdentifier;
// Create an object to store the callback, its options, and the time it
// was added.
var callbackObject = {
id: id,
callback: callback,
options: options || {},
added: performance.now()
};
// If an idle callback is running already this is a nested idle callback
// and should be scheduled for a different period. If no idle callback
// is running schedule immediately.
if (isCallbackRunning) {
nestedCallbacks.push(callbackObject);
} else {
scheduledCallbacks.push(callbackObject);
}
// Run scheduled idle callbacks after the next animation frame.
scheduleAnimationFrame();
// Return the callbacks identifier.
return id;
};
/**
* @param {number} - The idle callback identifier to cancel.
* @return {undefined}
*/
global.cancelIdleCallback = function cancelIdleCallback(id) {
if(arguments.length === 0) {
throw new TypeError('cancelIdleCallback requires at least 1 argument');
}
var callbackFilter = function (callbackObject) {
return callbackObject.id !== id;
};
// Find and remove the callback from the scheduled idle callbacks,
// and nested callbacks (cancelIdleCallback may be called in an idle period).
scheduledCallbacks = scheduledCallbacks.filter(callbackFilter);
nestedCallbacks = nestedCallbacks.filter(callbackFilter);
};
/** IdleDeadline Polyfill
* @example
* requestIdleCallback(function (deadline) {
* console.log(deadline instanceof IdleDeadline); // true
* });
*/
global.IdleDeadline = function IdleDeadline() {
if (!allowIdleDeadlineConstructor) {
throw new TypeError('Illegal constructor');
}
};
Object.defineProperty(global.IdleDeadline.prototype, 'timeRemaining', {
value: function() {
throw new TypeError('Illegal invocation');
}
});
if (Object.prototype.hasOwnProperty('__defineGetter__')) {
Object.defineProperty(global.IdleDeadline.prototype, 'didTimeout', {
get: function () {
throw new TypeError('Illegal invocation');
}
});
} else {
Object.defineProperty(global.IdleDeadline.prototype, 'didTimeout', {
value: undefined
});
}
}(this)); | @param {function} callback
@return {number} - The idle callback identifier. | requestIdleCallback ( callback , options ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.42.0/requestIdleCallback/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.42.0/requestIdleCallback/raw.js | MIT |
var setHashIndex = function(map, recordKey, recordIndex) {
var hashedKey = hashKey(recordKey);
if (hashedKey === false) {
// If hashed key is false, the recordKey is an object which is not extensible.
// That indicates we cannot use the hash map for it, so this operation becomes no-op.
return false;
}
if (recordIndex === false) {
delete map._table[hashedKey];
} else {
map._table[hashedKey] = recordIndex;
}
return true;
}; | setHashIndex()
Function that given a map, key of `any` type, and a value, creates a new entry in Map hash table
@param {Map} map
@param {string|number|function|object} recordKey - Key to translate into normalized key for hash map
@param {number|bool} recordIndex - new record index for the hashedKey or `false` to delete the record index for the hashedKey
@returns {bool} - indicates success of operation | setHashIndex ( map , recordKey , recordIndex ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/Map/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/Map/raw.js | MIT |
function setInternalSlot(map, pl, field, value) {
if (!map.get(pl)) {
map.set(pl, Object.create(null));
}
var slots = map.get(pl);
slots[field] = value;
} | Cannot do Math.log(x) / Math.log(10) bc if IEEE floating point issue
@param x number | setInternalSlot ( map , pl , field , value ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | MIT |
function CanonicalizeLocaleList(locales) {
// TODO
return Intl.getCanonicalLocales(locales);
} | http://ecma-international.org/ecma-402/7.0/index.html#sec-canonicalizelocalelist
@param locales | CanonicalizeLocaleList ( locales ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | MIT |
function ToString(o) {
// Only symbol is irregular...
if (typeof o === 'symbol') {
throw TypeError('Cannot convert a Symbol value to a string');
}
return String(o);
} | https://tc39.es/ecma262/#sec-tostring | ToString ( o ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | MIT |
function BestAvailableLocale(availableLocales, locale) {
var candidate = locale;
while (true) {
if (availableLocales.has(candidate)) {
return candidate;
}
var pos = candidate.lastIndexOf('-');
if (!~pos) {
return undefined;
}
if (pos >= 2 && candidate[pos - 2] === '-') {
pos -= 2;
}
candidate = candidate.slice(0, pos);
}
} | https://tc39.es/ecma402/#sec-bestavailablelocale
@param availableLocales
@param locale | BestAvailableLocale ( availableLocales , locale ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | MIT |
function LookupMatcher(availableLocales, requestedLocales, getDefaultLocale) {
var result = { locale: '' };
for (var _i = 0, requestedLocales_1 = requestedLocales; _i < requestedLocales_1.length; _i++) {
var locale = requestedLocales_1[_i];
var noExtensionLocale = locale.replace(UNICODE_EXTENSION_SEQUENCE_REGEX, '');
var availableLocale = BestAvailableLocale(availableLocales, noExtensionLocale);
if (availableLocale) {
result.locale = availableLocale;
if (locale !== noExtensionLocale) {
result.extension = locale.slice(noExtensionLocale.length + 1, locale.length);
}
return result;
}
}
result.locale = getDefaultLocale();
return result;
} | https://tc39.es/ecma402/#sec-lookupmatcher
@param availableLocales
@param requestedLocales
@param getDefaultLocale | LookupMatcher ( availableLocales , requestedLocales , getDefaultLocale ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | MIT |
function UnicodeExtensionValue(extension, key) {
invariant(key.length === 2, 'key must have 2 elements');
var size = extension.length;
var searchValue = "-" + key + "-";
var pos = extension.indexOf(searchValue);
if (pos !== -1) {
var start = pos + 4;
var end = start;
var k = start;
var done = false;
while (!done) {
var e = extension.indexOf('-', k);
var len = void 0;
if (e === -1) {
len = size - k;
}
else {
len = e - k;
}
if (len === 2) {
done = true;
}
else if (e === -1) {
end = size;
done = true;
}
else {
end = e;
k = e + 1;
}
}
return extension.slice(start, end);
}
searchValue = "-" + key;
pos = extension.indexOf(searchValue);
if (pos !== -1 && pos + 3 === size) {
return '';
}
return undefined;
} | https://tc39.es/ecma402/#sec-unicodeextensionvalue
@param extension
@param key | UnicodeExtensionValue ( extension , key ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | MIT |
function ResolveLocale(availableLocales, requestedLocales, options, relevantExtensionKeys, localeData, getDefaultLocale) {
var matcher = options.localeMatcher;
var r;
if (matcher === 'lookup') {
r = LookupMatcher(availableLocales, requestedLocales, getDefaultLocale);
}
else {
r = BestFitMatcher(availableLocales, requestedLocales, getDefaultLocale);
}
var foundLocale = r.locale;
var result = { locale: '', dataLocale: foundLocale };
var supportedExtension = '-u';
for (var _i = 0, relevantExtensionKeys_1 = relevantExtensionKeys; _i < relevantExtensionKeys_1.length; _i++) {
var key = relevantExtensionKeys_1[_i];
invariant(foundLocale in localeData, "Missing locale data for " + foundLocale);
var foundLocaleData = localeData[foundLocale];
invariant(typeof foundLocaleData === 'object' && foundLocaleData !== null, "locale data " + key + " must be an object");
var keyLocaleData = foundLocaleData[key];
invariant(Array.isArray(keyLocaleData), "keyLocaleData for " + key + " must be an array");
var value = keyLocaleData[0];
invariant(typeof value === 'string' || value === null, "value must be string or null but got " + typeof value + " in key " + key);
var supportedExtensionAddition = '';
if (r.extension) {
var requestedValue = UnicodeExtensionValue(r.extension, key);
if (requestedValue !== undefined) {
if (requestedValue !== '') {
if (~keyLocaleData.indexOf(requestedValue)) {
value = requestedValue;
supportedExtensionAddition = "-" + key + "-" + value;
}
}
else if (~requestedValue.indexOf('true')) {
value = 'true';
supportedExtensionAddition = "-" + key;
}
}
}
if (key in options) {
var optionsValue = options[key];
invariant(typeof optionsValue === 'string' ||
typeof optionsValue === 'undefined' ||
optionsValue === null, 'optionsValue must be String, Undefined or Null');
if (~keyLocaleData.indexOf(optionsValue)) {
if (optionsValue !== value) {
value = optionsValue;
supportedExtensionAddition = '';
}
}
}
result[key] = value;
supportedExtension += supportedExtensionAddition;
}
if (supportedExtension.length > 2) {
var privateIndex = foundLocale.indexOf('-x-');
if (privateIndex === -1) {
foundLocale = foundLocale + supportedExtension;
}
else {
var preExtension = foundLocale.slice(0, privateIndex);
var postExtension = foundLocale.slice(privateIndex, foundLocale.length);
foundLocale = preExtension + supportedExtension + postExtension;
}
foundLocale = Intl.getCanonicalLocales(foundLocale)[0];
}
result.locale = foundLocale;
return result;
} | https://tc39.es/ecma402/#sec-resolvelocale | ResolveLocale ( availableLocales , requestedLocales , options , relevantExtensionKeys , localeData , getDefaultLocale ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | MIT |
function toUpperCase(str) {
return str.replace(/([a-z])/g, function (_, c) { return c.toUpperCase(); });
} | This follows https://tc39.es/ecma402/#sec-case-sensitivity-and-case-mapping
@param str string to convert | toUpperCase ( str ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | MIT |
function IsWellFormedCurrencyCode(currency) {
currency = toUpperCase(currency);
if (currency.length !== 3) {
return false;
}
if (NOT_A_Z_REGEX.test(currency)) {
return false;
}
return true;
} | https://tc39.es/ecma402/#sec-iswellformedcurrencycode | IsWellFormedCurrencyCode ( currency ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | MIT |
function LookupSupportedLocales(availableLocales, requestedLocales) {
var subset = [];
for (var _i = 0, requestedLocales_1 = requestedLocales; _i < requestedLocales_1.length; _i++) {
var locale = requestedLocales_1[_i];
var noExtensionLocale = locale.replace(UNICODE_EXTENSION_SEQUENCE_REGEX, '');
var availableLocale = BestAvailableLocale(availableLocales, noExtensionLocale);
if (availableLocale) {
subset.push(availableLocale);
}
}
return subset;
} | https://tc39.es/ecma402/#sec-lookupsupportedlocales
@param availableLocales
@param requestedLocales | LookupSupportedLocales ( availableLocales , requestedLocales ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | MIT |
function SupportedLocales(availableLocales, requestedLocales, options) {
var matcher = 'best fit';
if (options !== undefined) {
options = ToObject(options);
matcher = GetOption(options, 'localeMatcher', 'string', ['lookup', 'best fit'], 'best fit');
}
if (matcher === 'best fit') {
return LookupSupportedLocales(availableLocales, requestedLocales);
}
return LookupSupportedLocales(availableLocales, requestedLocales);
} | https://tc39.es/ecma402/#sec-supportedlocales
@param availableLocales
@param requestedLocales
@param options | SupportedLocales ( availableLocales , requestedLocales , options ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | MIT |
function hasMissingICUBug() {
if (Intl.DisplayNames) {
var regionNames = new Intl.DisplayNames(['en'], {
type: 'region',
});
return regionNames.of('CA') === 'CA';
}
return false;
} | https://bugs.chromium.org/p/chromium/issues/detail?id=1097432 | hasMissingICUBug ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | MIT |
function BestFitMatcher(availableLocales, requestedLocales, getDefaultLocale) {
var minimizedAvailableLocaleMap = {};
var minimizedAvailableLocales = new Set();
availableLocales.forEach(function (locale) {
var minimizedLocale = new Intl.Locale(locale)
.minimize()
.toString();
minimizedAvailableLocaleMap[minimizedLocale] = locale;
minimizedAvailableLocales.add(minimizedLocale);
});
var foundLocale;
for (var _i = 0, requestedLocales_1 = requestedLocales; _i < requestedLocales_1.length; _i++) {
var l = requestedLocales_1[_i];
if (foundLocale) {
break;
}
var noExtensionLocale = l.replace(UNICODE_EXTENSION_SEQUENCE_REGEX, '');
if (availableLocales.has(noExtensionLocale)) {
foundLocale = noExtensionLocale;
break;
}
if (minimizedAvailableLocales.has(noExtensionLocale)) {
foundLocale = minimizedAvailableLocaleMap[noExtensionLocale];
break;
}
var locale = new Intl.Locale(noExtensionLocale);
var maximizedRequestedLocale = locale.maximize().toString();
var minimizedRequestedLocale = locale.minimize().toString();
// Check minimized locale
if (minimizedAvailableLocales.has(minimizedRequestedLocale)) {
foundLocale = minimizedAvailableLocaleMap[minimizedRequestedLocale];
break;
}
// Lookup algo on maximized locale
foundLocale = BestAvailableLocale(minimizedAvailableLocales, maximizedRequestedLocale);
}
return {
locale: foundLocale || getDefaultLocale(),
};
}
/**
* https://tc39.es/ecma402/#sec-unicodeextensionvalue
* @param extension
* @param key
*/
function UnicodeExtensionValue(extension, key) {
invariant(key.length === 2, 'key must have 2 elements');
var size = extension.length;
var searchValue = "-" + key + "-";
var pos = extension.indexOf(searchValue);
if (pos !== -1) {
var start = pos + 4;
var end = start;
var k = start;
var done = false;
while (!done) {
var e = extension.indexOf('-', k);
var len = void 0;
if (e === -1) {
len = size - k;
}
else {
len = e - k;
}
if (len === 2) {
done = true;
}
else if (e === -1) {
end = size;
done = true;
}
else {
end = e;
k = e + 1;
}
}
return extension.slice(start, end);
}
searchValue = "-" + key;
pos = extension.indexOf(searchValue);
if (pos !== -1 && pos + 3 === size) {
return '';
}
return undefined;
}
/**
* https://tc39.es/ecma402/#sec-resolvelocale
*/
function ResolveLocale(availableLocales, requestedLocales, options, relevantExtensionKeys, localeData, getDefaultLocale) {
var matcher = options.localeMatcher;
var r;
if (matcher === 'lookup') {
r = LookupMatcher(availableLocales, requestedLocales, getDefaultLocale);
}
else {
r = BestFitMatcher(availableLocales, requestedLocales, getDefaultLocale);
}
var foundLocale = r.locale;
var result = { locale: '', dataLocale: foundLocale };
var supportedExtension = '-u';
for (var _i = 0, relevantExtensionKeys_1 = relevantExtensionKeys; _i < relevantExtensionKeys_1.length; _i++) {
var key = relevantExtensionKeys_1[_i];
invariant(foundLocale in localeData, "Missing locale data for " + foundLocale);
var foundLocaleData = localeData[foundLocale];
invariant(typeof foundLocaleData === 'object' && foundLocaleData !== null, "locale data " + key + " must be an object");
var keyLocaleData = foundLocaleData[key];
invariant(Array.isArray(keyLocaleData), "keyLocaleData for " + key + " must be an array");
var value = keyLocaleData[0];
invariant(typeof value === 'string' || value === null, "value must be string or null but got " + typeof value + " in key " + key);
var supportedExtensionAddition = '';
if (r.extension) {
var requestedValue = UnicodeExtensionValue(r.extension, key);
if (requestedValue !== undefined) {
if (requestedValue !== '') {
if (~keyLocaleData.indexOf(requestedValue)) {
value = requestedValue;
supportedExtensionAddition = "-" + key + "-" + value;
}
}
else if (~requestedValue.indexOf('true')) {
value = 'true';
supportedExtensionAddition = "-" + key;
}
}
}
if (key in options) {
var optionsValue = options[key];
invariant(typeof optionsValue === 'string' ||
typeof optionsValue === 'undefined' ||
optionsValue === null, 'optionsValue must be String, Undefined or Null');
if (~keyLocaleData.indexOf(optionsValue)) {
if (optionsValue !== value) {
value = optionsValue;
supportedExtensionAddition = '';
}
}
}
result[key] = value;
supportedExtension += supportedExtensionAddition;
}
if (supportedExtension.length > 2) {
var privateIndex = foundLocale.indexOf('-x-');
if (privateIndex === -1) {
foundLocale = foundLocale + supportedExtension;
}
else {
var preExtension = foundLocale.slice(0, privateIndex);
var postExtension = foundLocale.slice(privateIndex, foundLocale.length);
foundLocale = preExtension + supportedExtension + postExtension;
}
foundLocale = Intl.getCanonicalLocales(foundLocale)[0];
}
result.locale = foundLocale;
return result;
}
/**
* This follows https://tc39.es/ecma402/#sec-case-sensitivity-and-case-mapping
* @param str string to convert
*/
function toUpperCase(str) {
return str.replace(/([a-z])/g, function (_, c) { return c.toUpperCase(); });
}
var NOT_A_Z_REGEX = /[^A-Z]/;
/**
* https://tc39.es/ecma402/#sec-iswellformedcurrencycode
*/
function IsWellFormedCurrencyCode(currency) {
currency = toUpperCase(currency);
if (currency.length !== 3) {
return false;
}
if (NOT_A_Z_REGEX.test(currency)) {
return false;
}
return true;
}
/**
* https://tc39.es/ecma402/#sec-lookupsupportedlocales
* @param availableLocales
* @param requestedLocales
*/
function LookupSupportedLocales(availableLocales, requestedLocales) {
var subset = [];
for (var _i = 0, requestedLocales_1 = requestedLocales; _i < requestedLocales_1.length; _i++) {
var locale = requestedLocales_1[_i];
var noExtensionLocale = locale.replace(UNICODE_EXTENSION_SEQUENCE_REGEX, '');
var availableLocale = BestAvailableLocale(availableLocales, noExtensionLocale);
if (availableLocale) {
subset.push(availableLocale);
}
}
return subset;
}
/**
* https://tc39.es/ecma402/#sec-supportedlocales
* @param availableLocales
* @param requestedLocales
* @param options
*/
function SupportedLocales(availableLocales, requestedLocales, options) {
var matcher = 'best fit';
if (options !== undefined) {
options = ToObject(options);
matcher = GetOption(options, 'localeMatcher', 'string', ['lookup', 'best fit'], 'best fit');
}
if (matcher === 'best fit') {
return LookupSupportedLocales(availableLocales, requestedLocales);
}
return LookupSupportedLocales(availableLocales, requestedLocales);
}
var DisplayNames = /** @class */ (function () {
function DisplayNames(locales, options) {
var _newTarget = this.constructor;
if (_newTarget === undefined) {
throw TypeError("Constructor Intl.DisplayNames requires 'new'");
}
var requestedLocales = CanonicalizeLocaleList(locales);
options = ToObject(options);
var opt = Object.create(null);
var localeData = DisplayNames.localeData;
var matcher = GetOption(options, 'localeMatcher', 'string', ['lookup', 'best fit'], 'best fit');
opt.localeMatcher = matcher;
var r = ResolveLocale(DisplayNames.availableLocales, requestedLocales, opt, [], // there is no relevantExtensionKeys
DisplayNames.localeData, DisplayNames.getDefaultLocale);
var style = GetOption(options, 'style', 'string', ['narrow', 'short', 'long'], 'long');
setSlot(this, 'style', style);
var type = GetOption(options, 'type', 'string', ['language', 'currency', 'region', 'script'], undefined);
if (type === undefined) {
throw TypeError("Intl.DisplayNames constructor requires \"type\" option");
}
setSlot(this, 'type', type);
var fallback = GetOption(options, 'fallback', 'string', ['code', 'none'], 'code');
setSlot(this, 'fallback', fallback);
setSlot(this, 'locale', r.locale);
var dataLocale = r.dataLocale;
var dataLocaleData = localeData[dataLocale];
invariant(!!dataLocaleData, "Missing locale data for " + dataLocale);
setSlot(this, 'localeData', dataLocaleData);
invariant(dataLocaleData !== undefined, "locale data for " + r.locale + " does not exist.");
var types = dataLocaleData.types;
invariant(typeof types === 'object' && types != null, 'invalid types data');
var typeFields = types[type];
invariant(typeof typeFields === 'object' && typeFields != null, 'invalid typeFields data');
var styleFields = typeFields[style];
invariant(typeof styleFields === 'object' && styleFields != null, 'invalid styleFields data');
setSlot(this, 'fields', styleFields);
}
DisplayNames.supportedLocalesOf = function (locales, options) {
return SupportedLocales(DisplayNames.availableLocales, CanonicalizeLocaleList(locales), options);
};
DisplayNames.__addLocaleData = function () {
var data = [];
for (var _i = 0; _i < arguments.length; _i++) {
data[_i] = arguments[_i];
}
for (var _a = 0, data_1 = data; _a < data_1.length; _a++) {
var _b = data_1[_a], d = _b.data, locale = _b.locale;
var minimizedLocale = new Intl.Locale(locale)
.minimize()
.toString();
DisplayNames.localeData[locale] = DisplayNames.localeData[minimizedLocale] = d;
DisplayNames.availableLocales.add(minimizedLocale);
DisplayNames.availableLocales.add(locale);
if (!DisplayNames.__defaultLocale) {
DisplayNames.__defaultLocale = minimizedLocale;
}
}
};
DisplayNames.prototype.of = function (code) {
checkReceiver(this, 'of');
var type = getSlot(this, 'type');
var codeAsString = ToString(code);
if (!isValidCodeForDisplayNames(type, codeAsString)) {
throw RangeError('invalid code for Intl.DisplayNames.prototype.of');
}
var _a = getMultiInternalSlots(__INTERNAL_SLOT_MAP__, this, 'localeData', 'style', 'fallback'), localeData = _a.localeData, style = _a.style, fallback = _a.fallback;
// Canonicalize the case.
var canonicalCode;
// This is only used to store extracted language region.
var regionSubTag;
switch (type) {
// Normalize the locale id and remove the region.
case 'language': {
canonicalCode = CanonicalizeLocaleList(codeAsString)[0];
var regionMatch = /-([a-z]{2}|\d{3})\b/i.exec(canonicalCode);
if (regionMatch) {
// Remove region subtag
canonicalCode =
canonicalCode.substring(0, regionMatch.index) +
canonicalCode.substring(regionMatch.index + regionMatch[0].length);
regionSubTag = regionMatch[1];
}
break;
}
// currency code should be all upper-case.
case 'currency':
canonicalCode = codeAsString.toUpperCase();
break;
// script code should be title case
case 'script':
canonicalCode =
codeAsString[0] + codeAsString.substring(1).toLowerCase();
break;
// region shold be all upper-case
case 'region':
canonicalCode = codeAsString.toUpperCase();
break;
}
var typesData = localeData.types[type];
// If the style of choice does not exist, fallback to "long".
var name = typesData[style][canonicalCode] || typesData.long[canonicalCode];
if (name !== undefined) {
// If there is a region subtag in the language id, use locale pattern to interpolate the region
if (regionSubTag) {
// Retrieve region display names
var regionsData = localeData.types.region;
var regionDisplayName = regionsData[style][regionSubTag] || regionsData.long[regionSubTag];
if (regionDisplayName || fallback === 'code') {
// Interpolate into locale-specific pattern.
var pattern = localeData.patterns.locale;
return pattern
.replace('{0}', name)
.replace('{1}', regionDisplayName || regionSubTag);
}
}
else {
return name;
}
}
if (fallback === 'code') {
return codeAsString;
}
};
DisplayNames.prototype.resolvedOptions = function () {
checkReceiver(this, 'resolvedOptions');
return __assign({}, getMultiInternalSlots(__INTERNAL_SLOT_MAP__, this, 'locale', 'style', 'type', 'fallback'));
};
DisplayNames.getDefaultLocale = function () {
return DisplayNames.__defaultLocale;
};
DisplayNames.localeData = {};
DisplayNames.availableLocales = new Set();
DisplayNames.__defaultLocale = '';
DisplayNames.polyfilled = true;
return DisplayNames;
}());
// https://tc39.es/proposal-intl-displaynames/#sec-isvalidcodefordisplaynames
function isValidCodeForDisplayNames(type, code) {
switch (type) {
case 'language':
// subset of unicode_language_id
// languageCode ["-" scriptCode] ["-" regionCode] *("-" variant)
// where:
// - languageCode is either a two letters ISO 639-1 language code or a three letters ISO 639-2 language code.
// - scriptCode is should be an ISO-15924 four letters script code
// - regionCode is either an ISO-3166 two letters region code, or a three digits UN M49 Geographic Regions.
return /^[a-z]{2,3}(-[a-z]{4})?(-([a-z]{2}|\d{3}))?(-([a-z\d]{5,8}|\d[a-z\d]{3}))*$/i.test(code);
case 'region':
// unicode_region_subtag
return /^([a-z]{2}|\d{3})$/i.test(code);
case 'script':
// unicode_script_subtag
return /^[a-z]{4}$/i.test(code);
case 'currency':
return IsWellFormedCurrencyCode(code);
}
}
try {
// IE11 does not have Symbol
if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
Object.defineProperty(DisplayNames.prototype, Symbol.toStringTag, {
value: 'Intl.DisplayNames',
configurable: true,
enumerable: false,
writable: false,
});
}
Object.defineProperty(DisplayNames, 'length', {
value: 2,
writable: false,
enumerable: false,
configurable: true,
});
}
catch (e) {
// Make test 262 compliant
}
var __INTERNAL_SLOT_MAP__ = new WeakMap();
function getSlot(instance, key) {
return getInternalSlot(__INTERNAL_SLOT_MAP__, instance, key);
}
function setSlot(instance, key, value) {
setInternalSlot(__INTERNAL_SLOT_MAP__, instance, key, value);
}
function checkReceiver(receiver, methodName) {
if (!(receiver instanceof DisplayNames)) {
throw TypeError("Method Intl.DisplayNames.prototype." + methodName + " called on incompatible receiver");
}
}
/**
* https://bugs.chromium.org/p/chromium/issues/detail?id=1097432
*/
function hasMissingICUBug() {
if (Intl.DisplayNames) {
var regionNames = new Intl.DisplayNames(['en'], {
type: 'region',
});
return regionNames.of('CA') === 'CA';
}
return false;
}
function shouldPolyfill() {
return !Intl.DisplayNames || hasMissingICUBug();
}
if (shouldPolyfill()) {
Object.defineProperty(Intl, 'DisplayNames', {
value: DisplayNames,
enumerable: false,
writable: true,
configurable: true,
});
}
}))); | https://tc39.es/ecma402/#sec-bestfitmatcher
@param availableLocales
@param requestedLocales
@param getDefaultLocale | BestFitMatcher ( availableLocales , requestedLocales , getDefaultLocale ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DisplayNames/raw.js | MIT |
function bestFitFormatMatcherScore(options, format) {
var score = 0;
if (options.hour12 && !format.hour12) {
score -= removalPenalty;
}
else if (!options.hour12 && format.hour12) {
score -= additionPenalty;
}
for (var _i = 0, DATE_TIME_PROPS_1 = DATE_TIME_PROPS; _i < DATE_TIME_PROPS_1.length; _i++) {
var prop = DATE_TIME_PROPS_1[_i];
var optionsProp = options[prop];
var formatProp = format[prop];
if (optionsProp === undefined && formatProp !== undefined) {
score -= additionPenalty;
}
else if (optionsProp !== undefined && formatProp === undefined) {
score -= removalPenalty;
}
else if (optionsProp !== formatProp) {
// extra penalty for numeric vs non-numeric
if (isNumericType(optionsProp) !==
isNumericType(formatProp)) {
score -= differentNumericTypePenalty;
}
else {
var values = ['2-digit', 'numeric', 'narrow', 'short', 'long'];
var optionsPropIndex = values.indexOf(optionsProp);
var formatPropIndex = values.indexOf(formatProp);
var delta = Math.max(-2, Math.min(formatPropIndex - optionsPropIndex, 2));
if (delta === 2) {
score -= longMorePenalty;
}
else if (delta === 1) {
score -= shortMorePenalty;
}
else if (delta === -1) {
score -= shortLessPenalty;
}
else if (delta === -2) {
score -= longLessPenalty;
}
}
}
}
return score;
} | Credit: https://github.com/andyearnshaw/Intl.js/blob/0958dc1ad8153f1056653ea22b8208f0df289a4e/src/12.datetimeformat.js#L611
with some modifications
@param options
@param format | bestFitFormatMatcherScore ( options , format ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function BestFitFormatMatcher(options, formats) {
var bestScore = -Infinity;
var bestFormat = formats[0];
invariant(Array.isArray(formats), 'formats should be a list of things');
for (var _i = 0, formats_1 = formats; _i < formats_1.length; _i++) {
var format = formats_1[_i];
var score = bestFitFormatMatcherScore(options, format);
if (score > bestScore) {
bestScore = score;
bestFormat = format;
}
}
var skeletonFormat = __assign({}, bestFormat);
var patternFormat = { rawPattern: bestFormat.rawPattern };
processDateTimePattern(bestFormat.rawPattern, patternFormat);
// Kinda following https://github.com/unicode-org/icu/blob/dd50e38f459d84e9bf1b0c618be8483d318458ad/icu4j/main/classes/core/src/com/ibm/icu/text/DateTimePatternGenerator.java
// Method adjustFieldTypes
for (var prop in skeletonFormat) {
var skeletonValue = skeletonFormat[prop];
var patternValue = patternFormat[prop];
var requestedValue = options[prop];
// Don't mess with minute/second or we can get in the situation of
// 7:0:0 which is weird
if (prop === 'minute' || prop === 'second') {
continue;
}
// Nothing to do here
if (!requestedValue) {
continue;
}
// https://unicode.org/reports/tr35/tr35-dates.html#Matching_Skeletons
// Looks like we should not convert numeric to alphabetic but the other way
// around is ok
if (isNumericType(patternValue) &&
!isNumericType(requestedValue)) {
continue;
}
if (skeletonValue === requestedValue) {
continue;
}
patternFormat[prop] = requestedValue;
}
// Copy those over
patternFormat.pattern = skeletonFormat.pattern;
patternFormat.pattern12 = skeletonFormat.pattern12;
patternFormat.skeleton = skeletonFormat.skeleton;
patternFormat.rangePatterns = skeletonFormat.rangePatterns;
patternFormat.rangePatterns12 = skeletonFormat.rangePatterns12;
return patternFormat;
} | https://tc39.es/ecma402/#sec-bestfitformatmatcher
Just alias to basic for now
@param options
@param formats
@param implDetails Implementation details | BestFitFormatMatcher ( options , formats ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function CanonicalizeTimeZoneName(tz, _a) {
var tzData = _a.tzData, uppercaseLinks = _a.uppercaseLinks;
var uppercasedTz = tz.toUpperCase();
var uppercasedZones = Object.keys(tzData).reduce(function (all, z) {
all[z.toUpperCase()] = z;
return all;
}, {});
var ianaTimeZone = uppercaseLinks[uppercasedTz] || uppercasedZones[uppercasedTz];
if (ianaTimeZone === 'Etc/UTC' || ianaTimeZone === 'Etc/GMT') {
return 'UTC';
}
return ianaTimeZone;
} | https://tc39.es/ecma402/#sec-canonicalizetimezonename
@param tz | CanonicalizeTimeZoneName ( tz , _a ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function BasicFormatMatcher(options, formats) {
var bestScore = -Infinity;
var bestFormat = formats[0];
invariant(Array.isArray(formats), 'formats should be a list of things');
for (var _i = 0, formats_1 = formats; _i < formats_1.length; _i++) {
var format = formats_1[_i];
var score = 0;
for (var _a = 0, DATE_TIME_PROPS_1 = DATE_TIME_PROPS; _a < DATE_TIME_PROPS_1.length; _a++) {
var prop = DATE_TIME_PROPS_1[_a];
var optionsProp = options[prop];
var formatProp = format[prop];
if (optionsProp === undefined && formatProp !== undefined) {
score -= additionPenalty;
}
else if (optionsProp !== undefined && formatProp === undefined) {
score -= removalPenalty;
}
else if (optionsProp !== formatProp) {
var values = ['2-digit', 'numeric', 'narrow', 'short', 'long'];
var optionsPropIndex = values.indexOf(optionsProp);
var formatPropIndex = values.indexOf(formatProp);
var delta = Math.max(-2, Math.min(formatPropIndex - optionsPropIndex, 2));
if (delta === 2) {
score -= longMorePenalty;
}
else if (delta === 1) {
score -= shortMorePenalty;
}
else if (delta === -1) {
score -= shortLessPenalty;
}
else if (delta === -2) {
score -= longLessPenalty;
}
}
}
if (score > bestScore) {
bestScore = score;
bestFormat = format;
}
}
return __assign({}, bestFormat);
} | https://tc39.es/ecma402/#sec-basicformatmatcher
@param options
@param formats | BasicFormatMatcher ( options , formats ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function ToNumber(val) {
if (val === undefined) {
return NaN;
}
if (val === null) {
return +0;
}
if (typeof val === 'boolean') {
return val ? 1 : +0;
}
if (typeof val === 'number') {
return val;
}
if (typeof val === 'symbol' || typeof val === 'bigint') {
throw new TypeError('Cannot convert symbol/bigint to number');
}
return Number(val);
} | https://tc39.es/ecma262/#sec-tonumber
@param val | ToNumber ( val ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function ToInteger(n) {
var number = ToNumber(n);
if (isNaN(number) || SameValue(number, -0)) {
return 0;
}
if (isFinite(number)) {
return number;
}
var integer = Math.floor(Math.abs(number));
if (number < 0) {
integer = -integer;
}
if (SameValue(integer, -0)) {
return 0;
}
return integer;
} | https://tc39.es/ecma262/#sec-tointeger
@param n | ToInteger ( n ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function TimeClip(time) {
if (!isFinite(time)) {
return NaN;
}
if (Math.abs(time) > 8.64 * 1e16) {
return NaN;
}
return ToInteger(time);
} | https://tc39.es/ecma262/#sec-timeclip
@param time | TimeClip ( time ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function SameValue(x, y) {
if (Object.is) {
return Object.is(x, y);
}
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
}
// Step 6.a: NaN == NaN
return x !== x && y !== y;
} | https://www.ecma-international.org/ecma-262/11.0/index.html#sec-samevalue
@param x
@param y | SameValue ( x , y ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function ArrayCreate(len) {
return new Array(len);
} | https://www.ecma-international.org/ecma-262/11.0/index.html#sec-arraycreate
@param len | ArrayCreate ( len ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function Type(x) {
if (x === null) {
return 'Null';
}
if (typeof x === 'undefined') {
return 'Undefined';
}
if (typeof x === 'function' || typeof x === 'object') {
return 'Object';
}
if (typeof x === 'number') {
return 'Number';
}
if (typeof x === 'boolean') {
return 'Boolean';
}
if (typeof x === 'string') {
return 'String';
}
if (typeof x === 'symbol') {
return 'Symbol';
}
if (typeof x === 'bigint') {
return 'BigInt';
}
} | https://www.ecma-international.org/ecma-262/11.0/index.html#sec-type
@param x | Type ( x ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function mod(x, y) {
return x - Math.floor(x / y) * y;
} | https://www.ecma-international.org/ecma-262/11.0/index.html#eqn-modulo
@param x
@param y
@return k of the same sign as y | mod ( x , y ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function Day(t) {
return Math.floor(t / MS_PER_DAY);
} | https://tc39.es/ecma262/#eqn-Day
@param t | Day ( t ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function WeekDay(t) {
return mod(Day(t) + 4, 7);
} | https://tc39.es/ecma262/#sec-week-day
@param t | WeekDay ( t ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function DayFromYear(y) {
return (365 * (y - 1970) +
Math.floor((y - 1969) / 4) -
Math.floor((y - 1901) / 100) +
Math.floor((y - 1601) / 400));
} | https://tc39.es/ecma262/#sec-year-number
@param y | DayFromYear ( y ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function YearFromTime(t) {
var min = Math.ceil(t / MS_PER_DAY / 366);
var y = min;
while (TimeFromYear(y) <= t) {
y++;
}
return y - 1;
} | https://tc39.es/ecma262/#sec-year-number
@param t | YearFromTime ( t ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function MonthFromTime(t) {
var dwy = DayWithinYear(t);
var leap = InLeapYear(t);
if (dwy >= 0 && dwy < 31) {
return 0;
}
if (dwy < 59 + leap) {
return 1;
}
if (dwy < 90 + leap) {
return 2;
}
if (dwy < 120 + leap) {
return 3;
}
if (dwy < 151 + leap) {
return 4;
}
if (dwy < 181 + leap) {
return 5;
}
if (dwy < 212 + leap) {
return 6;
}
if (dwy < 243 + leap) {
return 7;
}
if (dwy < 273 + leap) {
return 8;
}
if (dwy < 304 + leap) {
return 9;
}
if (dwy < 334 + leap) {
return 10;
}
if (dwy < 365 + leap) {
return 11;
}
throw new Error('Invalid time');
} | https://tc39.es/ecma262/#sec-month-number
@param t | MonthFromTime ( t ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function FormatDateTimePattern(dtf, patternParts, x, _a) {
var getInternalSlots = _a.getInternalSlots, localeData = _a.localeData, getDefaultTimeZone = _a.getDefaultTimeZone, tzData = _a.tzData;
x = TimeClip(x);
/** IMPL START */
var internalSlots = getInternalSlots(dtf);
var dataLocale = internalSlots.dataLocale;
var dataLocaleData = localeData[dataLocale];
/** IMPL END */
var locale = internalSlots.locale;
var nfOptions = Object.create(null);
nfOptions.useGrouping = false;
var nf = new Intl.NumberFormat(locale, nfOptions);
var nf2Options = Object.create(null);
nf2Options.minimumIntegerDigits = 2;
nf2Options.useGrouping = false;
var nf2 = new Intl.NumberFormat(locale, nf2Options);
var tm = ToLocalTime(x,
// @ts-ignore
internalSlots.calendar, internalSlots.timeZone, { tzData: tzData });
var result = [];
for (var _i = 0, patternParts_1 = patternParts; _i < patternParts_1.length; _i++) {
var patternPart = patternParts_1[_i];
var p = patternPart.type;
if (p === 'literal') {
result.push({
type: 'literal',
value: patternPart.value,
});
}
else if (DATE_TIME_PROPS.indexOf(p) > -1) {
var fv = '';
var f = internalSlots[p];
// @ts-ignore
var v = tm[p];
if (p === 'year' && v <= 0) {
v = 1 - v;
}
if (p === 'month') {
v++;
}
var hourCycle = internalSlots.hourCycle;
if (p === 'hour' && (hourCycle === 'h11' || hourCycle === 'h12')) {
v = v % 12;
if (v === 0 && hourCycle === 'h12') {
v = 12;
}
}
if (p === 'hour' && hourCycle === 'h24') {
if (v === 0) {
v = 24;
}
}
if (f === 'numeric') {
fv = nf.format(v);
}
else if (f === '2-digit') {
fv = nf2.format(v);
if (fv.length > 2) {
fv = fv.slice(fv.length - 2, fv.length);
}
}
else if (f === 'narrow' || f === 'short' || f === 'long') {
if (p === 'era') {
fv = dataLocaleData[p][f][v];
}
else if (p === 'timeZoneName') {
var timeZoneName = dataLocaleData.timeZoneName, gmtFormat = dataLocaleData.gmtFormat, hourFormat = dataLocaleData.hourFormat;
var timeZone = internalSlots.timeZone || getDefaultTimeZone();
var timeZoneData = timeZoneName[timeZone];
if (timeZoneData && timeZoneData[f]) {
fv = timeZoneData[f][+tm.inDST];
}
else {
// Fallback to gmtFormat
fv = offsetToGmtString(gmtFormat, hourFormat, tm.timeZoneOffset, f);
}
}
else if (p === 'month') {
fv = dataLocaleData.month[f][v - 1];
}
else {
fv = dataLocaleData[p][f][v];
}
}
result.push({
type: p,
value: fv,
});
}
else if (p === 'ampm') {
var v = tm.hour;
var fv = void 0;
if (v > 11) {
fv = dataLocaleData.pm;
}
else {
fv = dataLocaleData.am;
}
result.push({
type: 'dayPeriod',
value: fv,
});
}
else if (p === 'relatedYear') {
var v = tm.relatedYear;
// @ts-ignore
var fv = nf.format(v);
result.push({
// @ts-ignore TODO: Fix TS type
type: 'relatedYear',
value: fv,
});
}
else if (p === 'yearName') {
var v = tm.yearName;
// @ts-ignore
var fv = nf.format(v);
result.push({
// @ts-ignore TODO: Fix TS type
type: 'yearName',
value: fv,
});
}
}
return result;
} | https://tc39.es/ecma402/#sec-partitiondatetimepattern
@param dtf
@param x | FormatDateTimePattern ( dtf , patternParts , x , _a ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function FormatDateTime(dtf, x, implDetails) {
var parts = PartitionDateTimePattern(dtf, x, implDetails);
var result = '';
for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
var part = parts_1[_i];
result += part.value;
}
return result;
} | https://tc39.es/ecma402/#sec-formatdatetime
@param dtf DateTimeFormat
@param x | FormatDateTime ( dtf , x , implDetails ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function FormatDateTimeToParts(dtf, x, implDetails) {
var parts = PartitionDateTimePattern(dtf, x, implDetails);
var result = ArrayCreate(0);
for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
var part = parts_1[_i];
result.push({
type: part.type,
value: part.value,
});
}
return result;
} | https://tc39.es/ecma402/#sec-formatdatetimetoparts
@param dtf
@param x
@param implDetails | FormatDateTimeToParts ( dtf , x , implDetails ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function ToDateTimeOptions(options, required, defaults) {
if (options === undefined) {
options = null;
}
else {
options = ToObject(options);
}
options = Object.create(options);
var needDefaults = true;
if (required === 'date' || required === 'any') {
for (var _i = 0, _a = ['weekday', 'year', 'month', 'day']; _i < _a.length; _i++) {
var prop = _a[_i];
var value = options[prop];
if (value !== undefined) {
needDefaults = false;
}
}
}
if (required === 'time' || required === 'any') {
for (var _b = 0, _c = ['hour', 'minute', 'second']; _b < _c.length; _b++) {
var prop = _c[_b];
var value = options[prop];
if (value !== undefined) {
needDefaults = false;
}
}
}
if (options.dateStyle !== undefined || options.timeStyle !== undefined) {
needDefaults = false;
}
if (required === 'date' && options.timeStyle) {
throw new TypeError('Intl.DateTimeFormat date was required but timeStyle was included');
}
if (required === 'time' && options.dateStyle) {
throw new TypeError('Intl.DateTimeFormat time was required but dateStyle was included');
}
if (needDefaults && (defaults === 'date' || defaults === 'all')) {
for (var _d = 0, _e = ['year', 'month', 'day']; _d < _e.length; _d++) {
var prop = _e[_d];
options[prop] = 'numeric';
}
}
if (needDefaults && (defaults === 'time' || defaults === 'all')) {
for (var _f = 0, _g = ['hour', 'minute', 'second']; _f < _g.length; _f++) {
var prop = _g[_f];
options[prop] = 'numeric';
}
}
return options;
} | https://tc39.es/ecma402/#sec-todatetimeoptions
@param options
@param required
@param defaults | ToDateTimeOptions ( options , required , defaults ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function IsValidTimeZoneName(tz, _a) {
var tzData = _a.tzData, uppercaseLinks = _a.uppercaseLinks;
var uppercasedTz = tz.toUpperCase();
var zoneNames = new Set(Object.keys(tzData).map(function (z) { return z.toUpperCase(); }));
return zoneNames.has(uppercasedTz) || uppercasedTz in uppercaseLinks;
} | https://tc39.es/ecma402/#sec-isvalidtimezonename
@param tz
@param implDetails implementation details | IsValidTimeZoneName ( tz , _a ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function hasChromeLt71Bug() {
return (new Intl.DateTimeFormat('en', {
hourCycle: 'h11',
hour: 'numeric',
}).formatToParts(0)[2].type !== 'dayPeriod');
} | https://bugs.chromium.org/p/chromium/issues/detail?id=865351 | hasChromeLt71Bug ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function toLocaleString(x, locales, options) {
var dtf = new DateTimeFormat(locales, options);
return dtf.format(x);
} | Number.prototype.toLocaleString ponyfill
https://tc39.es/ecma402/#sup-number.prototype.tolocalestring | toLocaleString ( x , locales , options ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.98.0/Intl.DateTimeFormat/raw.js | MIT |
function canonicalizeUnicodeLocaleId(locale) {
locale.lang = canonicalizeUnicodeLanguageId(locale.lang);
if (locale.extensions) {
for (var _i = 0, _a = locale.extensions; _i < _a.length; _i++) {
var extension = _a[_i];
switch (extension.type) {
case 'u':
extension.keywords = canonicalizeKVs(extension.keywords);
if (extension.attributes) {
extension.attributes = canonicalizeAttrs(extension.attributes);
}
break;
case 't':
if (extension.lang) {
extension.lang = canonicalizeUnicodeLanguageId(extension.lang);
}
extension.fields = canonicalizeKVs(extension.fields);
break;
default:
extension.value = extension.value.toLowerCase();
break;
}
}
locale.extensions.sort(compareExtension);
}
return locale;
}
exports.canonicalizeUnicodeLocaleId = canonicalizeUnicodeLocaleId;
}); | Canonicalize based on
https://www.unicode.org/reports/tr35/tr35.html#Canonical_Unicode_Locale_Identifiers
https://tc39.es/ecma402/#sec-canonicalizeunicodelocaleid
IMPORTANT: This modifies the object inline
@param locale | canonicalizeUnicodeLocaleId ( locale ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.101.0/polyfills/__dist/Intl.Locale/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.101.0/polyfills/__dist/Intl.Locale/raw.js | MIT |
function CanonicalizeLocaleList(locales) {
if (locales === undefined) {
return [];
}
var seen = [];
if (typeof locales === 'string') {
locales = [locales];
}
for (var _i = 0, locales_1 = locales; _i < locales_1.length; _i++) {
var locale = locales_1[_i];
var canonicalizedTag = emitter.emitUnicodeLocaleId(canonicalizer.canonicalizeUnicodeLocaleId(parser.parseUnicodeLocaleId(locale)));
if (seen.indexOf(canonicalizedTag) < 0) {
seen.push(canonicalizedTag);
}
}
return seen;
} | https://tc39.es/ecma402/#sec-canonicalizelocalelist
@param locales | CanonicalizeLocaleList ( locales ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.101.0/polyfills/__dist/Intl.Locale/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.101.0/polyfills/__dist/Intl.Locale/raw.js | MIT |
Locale.prototype.maximize = function () {
var locale = getInternalSlots(this).locale;
try {
var maximizedLocale = addLikelySubtags(locale);
return new Locale(maximizedLocale);
}
catch (e) {
return new Locale(locale);
}
}; | https://www.unicode.org/reports/tr35/#Likely_Subtags | Locale.prototype.maximize ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.101.0/polyfills/__dist/Intl.Locale/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.101.0/polyfills/__dist/Intl.Locale/raw.js | MIT |
get: function () {
var locale = getInternalSlots(this).locale;
return intlGetcanonicallocales.parseUnicodeLanguageId(locale).lang;
}, | https://tc39.es/proposal-intl-locale/#sec-Intl.Locale.prototype.language | get ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.101.0/polyfills/__dist/Intl.Locale/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.101.0/polyfills/__dist/Intl.Locale/raw.js | MIT |
get: function () {
var locale = getInternalSlots(this).locale;
return intlGetcanonicallocales.parseUnicodeLanguageId(locale).script;
}, | https://tc39.es/proposal-intl-locale/#sec-Intl.Locale.prototype.script | get ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.101.0/polyfills/__dist/Intl.Locale/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.101.0/polyfills/__dist/Intl.Locale/raw.js | MIT |
get: function () {
var locale = getInternalSlots(this).locale;
return intlGetcanonicallocales.parseUnicodeLanguageId(locale).region;
}, | https://tc39.es/proposal-intl-locale/#sec-Intl.Locale.prototype.region | get ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.101.0/polyfills/__dist/Intl.Locale/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.101.0/polyfills/__dist/Intl.Locale/raw.js | MIT |
function hasIntlGetCanonicalLocalesBug() {
try {
return new Intl.Locale('und-x-private').toString() === 'x-private';
}
catch (e) {
return true;
}
} | https://bugs.chromium.org/p/v8/issues/detail?id=10682 | hasIntlGetCanonicalLocalesBug ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.101.0/polyfills/__dist/Intl.Locale/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.101.0/polyfills/__dist/Intl.Locale/raw.js | MIT |
function removeLikelySubtags(tag) {
var maxLocale = addLikelySubtags(tag);
if (!maxLocale) {
return tag;
}
maxLocale = intlGetcanonicallocales.emitUnicodeLanguageId(__assign(__assign({}, intlGetcanonicallocales.parseUnicodeLanguageId(maxLocale)), { variants: [] }));
var ast = intlGetcanonicallocales.parseUnicodeLocaleId(tag);
var _a = ast.lang, lang = _a.lang, script = _a.script, region = _a.region, variants = _a.variants;
var trial = addLikelySubtags(intlGetcanonicallocales.emitUnicodeLanguageId({ lang: lang, variants: [] }));
if (trial === maxLocale) {
return intlGetcanonicallocales.emitUnicodeLocaleId(__assign(__assign({}, ast), { lang: mergeUnicodeLanguageId(lang, undefined, undefined, variants) }));
}
if (region) {
var trial_1 = addLikelySubtags(intlGetcanonicallocales.emitUnicodeLanguageId({ lang: lang, region: region, variants: [] }));
if (trial_1 === maxLocale) {
return intlGetcanonicallocales.emitUnicodeLocaleId(__assign(__assign({}, ast), { lang: mergeUnicodeLanguageId(lang, undefined, region, variants) }));
}
}
if (script) {
var trial_2 = addLikelySubtags(intlGetcanonicallocales.emitUnicodeLanguageId({ lang: lang, script: script, variants: [] }));
if (trial_2 === maxLocale) {
return intlGetcanonicallocales.emitUnicodeLocaleId(__assign(__assign({}, ast), { lang: mergeUnicodeLanguageId(lang, script, undefined, variants) }));
}
}
return tag;
}
var Locale = /** @class */ (function () {
function Locale(tag, opts) {
// test262/test/intl402/RelativeTimeFormat/constructor/constructor/newtarget-undefined.js
// Cannot use `new.target` bc of IE11 & TS transpiles it to something else
var newTarget = this && this instanceof Locale ? this.constructor : void 0;
if (!newTarget) {
throw new TypeError("Intl.Locale must be called with 'new'");
}
var relevantExtensionKeys = Locale.relevantExtensionKeys;
if (relevantExtensionKeys.indexOf('kf') > -1) ;
if (relevantExtensionKeys.indexOf('kn') > -1) ;
if (tag === undefined) {
throw new TypeError("First argument to Intl.Locale constructor can't be empty or missing");
}
if (typeof tag !== 'string' && typeof tag !== 'object') {
throw new TypeError('tag must be a string or object');
}
var internalSlots;
if (typeof tag === 'object' &&
(internalSlots = getInternalSlots(tag)) &&
internalSlots.initializedLocale) {
tag = internalSlots.locale;
}
else {
tag = tag.toString();
}
internalSlots = getInternalSlots(this);
var options;
if (opts === undefined) {
options = Object.create(null);
}
else {
options = ToObject(opts);
}
tag = applyOptionsToTag(tag, options);
var opt = Object.create(null);
var calendar = GetOption(options, 'calendar', 'string', undefined, undefined);
if (calendar !== undefined) {
if (!UNICODE_TYPE_REGEX.test(calendar)) {
throw new RangeError('invalid calendar');
}
}
opt.ca = calendar;
var collation = GetOption(options, 'collation', 'string', undefined, undefined);
if (collation !== undefined) {
if (!UNICODE_TYPE_REGEX.test(collation)) {
throw new RangeError('invalid collation');
}
}
opt.co = collation;
var hc = GetOption(options, 'hourCycle', 'string', ['h11', 'h12', 'h23', 'h24'], undefined);
opt.hc = hc;
var kf = GetOption(options, 'caseFirst', 'string', ['upper', 'lower', 'false'], undefined);
opt.kf = kf;
var _kn = GetOption(options, 'numeric', 'boolean', undefined, undefined);
var kn;
if (_kn !== undefined) {
kn = String(_kn);
}
opt.kn = kn;
var numberingSystem = GetOption(options, 'numberingSystem', 'string', undefined, undefined);
if (numberingSystem !== undefined) {
if (!UNICODE_TYPE_REGEX.test(numberingSystem)) {
throw new RangeError('Invalid numberingSystem');
}
}
opt.nu = numberingSystem;
var r = applyUnicodeExtensionToTag(tag, opt, relevantExtensionKeys);
internalSlots.locale = r.locale;
internalSlots.calendar = r.ca;
internalSlots.collation = r.co;
internalSlots.hourCycle = r.hc;
if (relevantExtensionKeys.indexOf('kf') > -1) {
internalSlots.caseFirst = r.kf;
}
if (relevantExtensionKeys.indexOf('kn') > -1) {
internalSlots.numeric = SameValue(r.kn, 'true');
}
internalSlots.numberingSystem = r.nu;
}
/**
* https://www.unicode.org/reports/tr35/#Likely_Subtags
*/
Locale.prototype.maximize = function () {
var locale = getInternalSlots(this).locale;
try {
var maximizedLocale = addLikelySubtags(locale);
return new Locale(maximizedLocale);
}
catch (e) {
return new Locale(locale);
}
};
/**
* https://www.unicode.org/reports/tr35/#Likely_Subtags
*/
Locale.prototype.minimize = function () {
var locale = getInternalSlots(this).locale;
try {
var minimizedLocale = removeLikelySubtags(locale);
return new Locale(minimizedLocale);
}
catch (e) {
return new Locale(locale);
}
};
Locale.prototype.toString = function () {
return getInternalSlots(this).locale;
};
Object.defineProperty(Locale.prototype, "baseName", {
get: function () {
var locale = getInternalSlots(this).locale;
return intlGetcanonicallocales.emitUnicodeLanguageId(intlGetcanonicallocales.parseUnicodeLanguageId(locale));
},
enumerable: false,
configurable: true
});
Object.defineProperty(Locale.prototype, "calendar", {
get: function () {
return getInternalSlots(this).calendar;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Locale.prototype, "collation", {
get: function () {
return getInternalSlots(this).collation;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Locale.prototype, "hourCycle", {
get: function () {
return getInternalSlots(this).hourCycle;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Locale.prototype, "caseFirst", {
get: function () {
return getInternalSlots(this).caseFirst;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Locale.prototype, "numeric", {
get: function () {
return getInternalSlots(this).numeric;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Locale.prototype, "numberingSystem", {
get: function () {
return getInternalSlots(this).numberingSystem;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Locale.prototype, "language", {
/**
* https://tc39.es/proposal-intl-locale/#sec-Intl.Locale.prototype.language
*/
get: function () {
var locale = getInternalSlots(this).locale;
return intlGetcanonicallocales.parseUnicodeLanguageId(locale).lang;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Locale.prototype, "script", {
/**
* https://tc39.es/proposal-intl-locale/#sec-Intl.Locale.prototype.script
*/
get: function () {
var locale = getInternalSlots(this).locale;
return intlGetcanonicallocales.parseUnicodeLanguageId(locale).script;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Locale.prototype, "region", {
/**
* https://tc39.es/proposal-intl-locale/#sec-Intl.Locale.prototype.region
*/
get: function () {
var locale = getInternalSlots(this).locale;
return intlGetcanonicallocales.parseUnicodeLanguageId(locale).region;
},
enumerable: false,
configurable: true
});
Locale.relevantExtensionKeys = RELEVANT_EXTENSION_KEYS;
return Locale;
}());
try {
if (typeof Symbol !== 'undefined') {
Object.defineProperty(Locale.prototype, Symbol.toStringTag, {
value: 'Intl.Locale',
writable: false,
enumerable: false,
configurable: true,
});
}
Object.defineProperty(Locale.prototype.constructor, 'length', {
value: 1,
writable: false,
enumerable: false,
configurable: true,
});
}
catch (e) {
// Meta fix so we're test262-compliant, not important
}
/**
* https://bugs.chromium.org/p/v8/issues/detail?id=10682
*/
function hasIntlGetCanonicalLocalesBug() {
try {
return new Intl.Locale('und-x-private').toString() === 'x-private';
}
catch (e) {
return true;
}
}
function shouldPolyfill() {
return (typeof Intl === 'undefined' ||
!('Locale' in Intl) ||
hasIntlGetCanonicalLocalesBug());
}
if (shouldPolyfill()) {
Object.defineProperty(Intl, 'Locale', {
value: Locale,
writable: true,
enumerable: false,
configurable: true,
});
}
}))); | From: https://github.com/unicode-org/icu/blob/4231ca5be053a22a1be24eb891817458c97db709/icu4j/main/classes/core/src/com/ibm/icu/util/ULocale.java#L2395
@param tag | removeLikelySubtags ( tag ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.101.0/polyfills/__dist/Intl.Locale/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.101.0/polyfills/__dist/Intl.Locale/raw.js | MIT |
'finally': function (onFinally) {
return this.then(function (val) {
return Yaku.resolve(onFinally()).then(function () {
return val;
}); | Register a callback to be invoked when a promise is settled (either fulfilled or rejected).
Similar with the try-catch-finally, it's often used for cleanup.
@param {Function} onFinally A Function called when the Promise is settled.
It will not receive any argument.
@return {Yaku} A Promise that will reject if onFinally throws an error or returns a rejected promise.
Else it will resolve previous promise's final state (either fulfilled or rejected).
@example
```js
var Promise = require('yaku');
var p = Math.random() > 0.5 ? Promise.resolve() : Promise.reject();
p.finally(() => {
console.log('finally');
});
``` | (anonymous) ( val ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/Promise/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/Promise/raw.js | MIT |
Yaku.nextTick = isBrowser ?
function (fn) {
nativePromise ?
new nativePromise(function (resolve) { resolve(); }).then(fn) :
setTimeout(fn); | Only Node has `process.nextTick` function. For browser there are
so many ways to polyfill it. Yaku won't do it for you, instead you
can choose what you prefer. For example, this project
[next-tick](https://github.com/medikoo/next-tick).
By default, Yaku will use `process.nextTick` on Node, `setTimeout` on browser.
@type {Function}
@example
```js
var Promise = require('yaku');
Promise.nextTick = require('next-tick');
```
@example
You can even use sync resolution if you really know what you are doing.
```js
var Promise = require('yaku');
Promise.nextTick = fn => fn();
``` | Yaku.nextTick ( fn ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.52.1/Promise/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/Promise/raw.js | MIT |
function InertRoot(rootElement, inertManager) {
_classCallCheck(this, InertRoot);
/** @type {!InertManager} */
this._inertManager = inertManager;
/** @type {!Element} */
this._rootElement = rootElement;
/**
* @type {!Set<!InertNode>}
* All managed focusable nodes in this InertRoot's subtree.
*/
this._managedNodes = new Set();
// Make the subtree hidden from assistive technology
if (this._rootElement.hasAttribute('aria-hidden')) {
/** @type {?string} */
this._savedAriaHidden = this._rootElement.getAttribute('aria-hidden');
} else {
this._savedAriaHidden = null;
}
this._rootElement.setAttribute('aria-hidden', 'true');
// Make all focusable elements in the subtree unfocusable and add them to _managedNodes
this._makeSubtreeUnfocusable(this._rootElement);
// Watch for:
// - any additions in the subtree: make them unfocusable too
// - any removals from the subtree: remove them from this inert root's managed nodes
// - attribute changes: if `tabindex` is added, or removed from an intrinsically focusable
// element, make that node a managed node.
this._observer = new MutationObserver(this._onMutation.bind(this));
this._observer.observe(this._rootElement, { attributes: true, childList: true, subtree: true });
} | @param {!Element} rootElement The Element at the root of the inert subtree.
@param {!InertManager} inertManager The global singleton InertManager object. | InertRoot ( rootElement , inertManager ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.110.1/Element.prototype.inert/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.110.1/Element.prototype.inert/raw.js | MIT |
var InertRoot = function () {
/**
* @param {!Element} rootElement The Element at the root of the inert subtree.
* @param {!InertManager} inertManager The global singleton InertManager object.
*/
function InertRoot(rootElement, inertManager) {
_classCallCheck(this, InertRoot);
/** @type {!InertManager} */
this._inertManager = inertManager;
/** @type {!Element} */
this._rootElement = rootElement;
/**
* @type {!Set<!InertNode>}
* All managed focusable nodes in this InertRoot's subtree.
*/
this._managedNodes = new Set();
// Make the subtree hidden from assistive technology
if (this._rootElement.hasAttribute('aria-hidden')) {
/** @type {?string} */
this._savedAriaHidden = this._rootElement.getAttribute('aria-hidden');
} else {
this._savedAriaHidden = null;
}
this._rootElement.setAttribute('aria-hidden', 'true');
// Make all focusable elements in the subtree unfocusable and add them to _managedNodes
this._makeSubtreeUnfocusable(this._rootElement);
// Watch for:
// - any additions in the subtree: make them unfocusable too
// - any removals from the subtree: remove them from this inert root's managed nodes
// - attribute changes: if `tabindex` is added, or removed from an intrinsically focusable
// element, make that node a managed node.
this._observer = new MutationObserver(this._onMutation.bind(this));
this._observer.observe(this._rootElement, { attributes: true, childList: true, subtree: true });
}
/**
* Call this whenever this object is about to become obsolete. This unwinds all of the state
* stored in this object and updates the state of all of the managed nodes.
*/
_createClass(InertRoot, [{
key: 'destructor',
value: function destructor() {
this._observer.disconnect();
if (this._rootElement) {
if (this._savedAriaHidden !== null) {
this._rootElement.setAttribute('aria-hidden', this._savedAriaHidden);
} else {
this._rootElement.removeAttribute('aria-hidden');
}
}
this._managedNodes.forEach(function (inertNode) {
this._unmanageNode(inertNode.node);
}, this);
// Note we cast the nulls to the ANY type here because:
// 1) We want the class properties to be declared as non-null, or else we
// need even more casts throughout this code. All bets are off if an
// instance has been destroyed and a method is called.
// 2) We don't want to cast "this", because we want type-aware optimizations
// to know which properties we're setting.
this._observer = /** @type {?} */null;
this._rootElement = /** @type {?} */null;
this._managedNodes = /** @type {?} */null;
this._inertManager = /** @type {?} */null;
}
/**
* @return {!Set<!InertNode>} A copy of this InertRoot's managed nodes set.
*/
}, {
key: '_makeSubtreeUnfocusable',
/**
* @param {!Node} startNode
*/
value: function _makeSubtreeUnfocusable(startNode) {
var _this2 = this;
composedTreeWalk(startNode, function (node) {
return _this2._visitNode(node);
});
var activeElement = document.activeElement;
if (!document.body.contains(startNode)) {
// startNode may be in shadow DOM, so find its nearest shadowRoot to get the activeElement.
var node = startNode;
/** @type {!ShadowRoot|undefined} */
var root = undefined;
while (node) {
if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
root = /** @type {!ShadowRoot} */node;
break;
}
node = node.parentNode;
}
if (root) {
activeElement = root.activeElement;
}
}
if (startNode.contains(activeElement)) {
activeElement.blur();
// In IE11, if an element is already focused, and then set to tabindex=-1
// calling blur() will not actually move the focus.
// To work around this we call focus() on the body instead.
if (activeElement === document.activeElement) {
document.body.focus();
}
}
}
/**
* @param {!Node} node
*/
}, {
key: '_visitNode',
value: function _visitNode(node) {
if (node.nodeType !== Node.ELEMENT_NODE) {
return;
}
var element = /** @type {!Element} */node;
// If a descendant inert root becomes un-inert, its descendants will still be inert because of
// this inert root, so all of its managed nodes need to be adopted by this InertRoot.
if (element !== this._rootElement && element.hasAttribute('inert')) {
this._adoptInertRoot(element);
}
if (matches.call(element, _focusableElementsString) || element.hasAttribute('tabindex')) {
this._manageNode(element);
}
}
/**
* Register the given node with this InertRoot and with InertManager.
* @param {!Node} node
*/
}, {
key: '_manageNode',
value: function _manageNode(node) {
var inertNode = this._inertManager.register(node, this);
this._managedNodes.add(inertNode);
}
/**
* Unregister the given node with this InertRoot and with InertManager.
* @param {!Node} node
*/
}, {
key: '_unmanageNode',
value: function _unmanageNode(node) {
var inertNode = this._inertManager.deregister(node, this);
if (inertNode) {
this._managedNodes['delete'](inertNode);
}
}
/**
* Unregister the entire subtree starting at `startNode`.
* @param {!Node} startNode
*/
}, {
key: '_unmanageSubtree',
value: function _unmanageSubtree(startNode) {
var _this3 = this;
composedTreeWalk(startNode, function (node) {
return _this3._unmanageNode(node);
});
}
/**
* If a descendant node is found with an `inert` attribute, adopt its managed nodes.
* @param {!Element} node
*/
}, {
key: '_adoptInertRoot',
value: function _adoptInertRoot(node) {
var inertSubroot = this._inertManager.getInertRoot(node);
// During initialisation this inert root may not have been registered yet,
// so register it now if need be.
if (!inertSubroot) {
this._inertManager.setInert(node, true);
inertSubroot = this._inertManager.getInertRoot(node);
}
inertSubroot.managedNodes.forEach(function (savedInertNode) {
this._manageNode(savedInertNode.node);
}, this);
}
/**
* Callback used when mutation observer detects subtree additions, removals, or attribute changes.
* @param {!Array<!MutationRecord>} records
* @param {!MutationObserver} self
*/
}, {
key: '_onMutation',
value: function _onMutation(records, _self) {
records.forEach(function (record) {
var target = /** @type {!Element} */record.target;
if (record.type === 'childList') {
// Manage added nodes
slice.call(record.addedNodes).forEach(function (node) {
this._makeSubtreeUnfocusable(node);
}, this);
// Un-manage removed nodes
slice.call(record.removedNodes).forEach(function (node) {
this._unmanageSubtree(node);
}, this);
} else if (record.type === 'attributes') {
if (record.attributeName === 'tabindex') {
// Re-initialise inert node if tabindex changes
this._manageNode(target);
} else if (target !== this._rootElement && record.attributeName === 'inert' && target.hasAttribute('inert')) {
// If a new inert root is added, adopt its managed nodes and make sure it knows about the
// already managed nodes from this inert subroot.
this._adoptInertRoot(target);
var inertSubroot = this._inertManager.getInertRoot(target);
this._managedNodes.forEach(function (managedNode) {
if (target.contains(managedNode.node)) {
inertSubroot._manageNode(managedNode.node);
}
});
}
}
}, this);
}
}, {
key: 'managedNodes',
get: function get() {
return new Set(this._managedNodes);
}
/** @return {boolean} */
}, {
key: 'hasSavedAriaHidden',
get: function get() {
return this._savedAriaHidden !== null;
}
/** @param {?string} ariaHidden */
}, {
key: 'savedAriaHidden',
set: function set(ariaHidden) {
this._savedAriaHidden = ariaHidden;
}
/** @return {?string} */
,
get: function get() {
return this._savedAriaHidden;
}
}]);
return InertRoot;
}(); | `InertRoot` manages a single inert subtree, i.e. a DOM subtree whose root element has an `inert`
attribute.
Its main functions are:
- to create and maintain a set of managed `InertNode`s, including when mutations occur in the
subtree. The `makeSubtreeUnfocusable()` method handles collecting `InertNode`s via registering
each focusable node in the subtree with the singleton `InertManager` which manages all known
focusable nodes within inert subtrees. `InertManager` ensures that a single `InertNode`
instance exists for each focusable node which has at least one inert root as an ancestor.
- to notify all managed `InertNode`s when this subtree stops being inert (i.e. when the `inert`
attribute is removed from the root node). This is handled in the destructor, which calls the
`deregister` method on `InertManager` for each managed inert node. | InertRoot ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.110.1/Element.prototype.inert/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.110.1/Element.prototype.inert/raw.js | MIT |
function InertNode(node, inertRoot) {
_classCallCheck(this, InertNode);
/** @type {!Node} */
this._node = node;
/** @type {boolean} */
this._overrodeFocusMethod = false;
/**
* @type {!Set<!InertRoot>} The set of descendant inert roots.
* If and only if this set becomes empty, this node is no longer inert.
*/
this._inertRoots = new Set([inertRoot]);
/** @type {?number} */
this._savedTabIndex = null;
/** @type {boolean} */
this._destroyed = false;
// Save any prior tabindex info and make this node untabbable
this.ensureUntabbable();
} | @param {!Node} node A focusable element to be made inert.
@param {!InertRoot} inertRoot The inert root element associated with this inert node. | InertNode ( node , inertRoot ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.110.1/Element.prototype.inert/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.110.1/Element.prototype.inert/raw.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.