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 |
---|---|---|---|---|---|---|---|
value: function _throwIfDestroyed() {
if (this.destroyed) {
throw new Error('Trying to access destroyed InertNode');
}
} | Throw if user tries to access destroyed InertNode. | _throwIfDestroyed ( ) | 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 InertNode = function () {
/**
* @param {!Node} node A focusable element to be made inert.
* @param {!InertRoot} inertRoot The inert root element associated with this inert node.
*/
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();
}
/**
* Call this whenever this object is about to become obsolete.
* This makes the managed node focusable again and deletes all of the previously stored state.
*/
_createClass(InertNode, [{
key: 'destructor',
value: function destructor() {
this._throwIfDestroyed();
if (this._node && this._node.nodeType === Node.ELEMENT_NODE) {
var element = /** @type {!Element} */this._node;
if (this._savedTabIndex !== null) {
element.setAttribute('tabindex', this._savedTabIndex);
} else {
element.removeAttribute('tabindex');
}
// Use `delete` to restore native focus method.
if (this._overrodeFocusMethod) {
delete element.focus;
}
}
// See note in InertRoot.destructor for why we cast these nulls to ANY.
this._node = /** @type {?} */null;
this._inertRoots = /** @type {?} */null;
this._destroyed = true;
}
/**
* @type {boolean} Whether this object is obsolete because the managed node is no longer inert.
* If the object has been destroyed, any attempt to access it will cause an exception.
*/
}, {
key: '_throwIfDestroyed',
/**
* Throw if user tries to access destroyed InertNode.
*/
value: function _throwIfDestroyed() {
if (this.destroyed) {
throw new Error('Trying to access destroyed InertNode');
}
}
/** @return {boolean} */
}, {
key: 'ensureUntabbable',
/** Save the existing tabindex value and make the node untabbable and unfocusable */
value: function ensureUntabbable() {
if (this.node.nodeType !== Node.ELEMENT_NODE) {
return;
}
var element = /** @type {!Element} */this.node;
if (matches.call(element, _focusableElementsString)) {
if ( /** @type {!HTMLElement} */element.tabIndex === -1 && this.hasSavedTabIndex) {
return;
}
if (element.hasAttribute('tabindex')) {
this._savedTabIndex = /** @type {!HTMLElement} */element.tabIndex;
}
element.setAttribute('tabindex', '-1');
if (element.nodeType === Node.ELEMENT_NODE) {
element.focus = function () {};
this._overrodeFocusMethod = true;
}
} else if (element.hasAttribute('tabindex')) {
this._savedTabIndex = /** @type {!HTMLElement} */element.tabIndex;
element.removeAttribute('tabindex');
}
}
/**
* Add another inert root to this inert node's set of managing inert roots.
* @param {!InertRoot} inertRoot
*/
}, {
key: 'addInertRoot',
value: function addInertRoot(inertRoot) {
this._throwIfDestroyed();
this._inertRoots.add(inertRoot);
}
/**
* Remove the given inert root from this inert node's set of managing inert roots.
* If the set of managing inert roots becomes empty, this node is no longer inert,
* so the object should be destroyed.
* @param {!InertRoot} inertRoot
*/
}, {
key: 'removeInertRoot',
value: function removeInertRoot(inertRoot) {
this._throwIfDestroyed();
this._inertRoots['delete'](inertRoot);
if (this._inertRoots.size === 0) {
this.destructor();
}
}
}, {
key: 'destroyed',
get: function get() {
return (/** @type {!InertNode} */this._destroyed
);
}
}, {
key: 'hasSavedTabIndex',
get: function get() {
return this._savedTabIndex !== null;
}
/** @return {!Node} */
}, {
key: 'node',
get: function get() {
this._throwIfDestroyed();
return this._node;
}
/** @param {?number} tabIndex */
}, {
key: 'savedTabIndex',
set: function set(tabIndex) {
this._throwIfDestroyed();
this._savedTabIndex = tabIndex;
}
/** @return {?number} */
,
get: function get() {
this._throwIfDestroyed();
return this._savedTabIndex;
}
}]);
return InertNode;
}(); | `InertNode` initialises and manages a single inert node.
A node is inert if it is a descendant of one or more inert root elements.
On construction, `InertNode` saves the existing `tabindex` value for the node, if any, and
either removes the `tabindex` attribute or sets it to `-1`, depending on whether the element
is intrinsically focusable or not.
`InertNode` maintains a set of `InertRoot`s which are descendants of this `InertNode`. When an
`InertRoot` is destroyed, and calls `InertManager.deregister()`, the `InertManager` notifies the
`InertNode` via `removeInertRoot()`, which in turn destroys the `InertNode` if no `InertRoot`s
remain in the set. On destruction, `InertNode` reinstates the stored `tabindex` if one exists,
or removes the `tabindex` attribute if the element is intrinsically focusable. | InertNode ( ) | 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 InertManager = function () {
/**
* @param {!Document} document
*/
function InertManager(document) {
_classCallCheck(this, InertManager);
if (!document) {
throw new Error('Missing required argument; InertManager needs to wrap a document.');
}
/** @type {!Document} */
this._document = document;
/**
* All managed nodes known to this InertManager. In a map to allow looking up by Node.
* @type {!Map<!Node, !InertNode>}
*/
this._managedNodes = new Map();
/**
* All inert roots known to this InertManager. In a map to allow looking up by Node.
* @type {!Map<!Node, !InertRoot>}
*/
this._inertRoots = new Map();
/**
* Observer for mutations on `document.body`.
* @type {!MutationObserver}
*/
this._observer = new MutationObserver(this._watchForInert.bind(this));
// Add inert style.
addInertStyle(document.head || document.body || document.documentElement);
// Wait for document to be loaded.
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', this._onDocumentLoaded.bind(this));
} else {
this._onDocumentLoaded();
}
}
/**
* Set whether the given element should be an inert root or not.
* @param {!Element} root
* @param {boolean} inert
*/
_createClass(InertManager, [{
key: 'setInert',
value: function setInert(root, inert) {
if (inert) {
if (this._inertRoots.has(root)) {
// element is already inert
return;
}
var inertRoot = new InertRoot(root, this);
root.setAttribute('inert', '');
this._inertRoots.set(root, inertRoot);
// If not contained in the document, it must be in a shadowRoot.
// Ensure inert styles are added there.
if (!this._document.body.contains(root)) {
var parent = root.parentNode;
while (parent) {
if (parent.nodeType === 11) {
addInertStyle(parent);
}
parent = parent.parentNode;
}
}
} else {
if (!this._inertRoots.has(root)) {
// element is already non-inert
return;
}
var _inertRoot = this._inertRoots.get(root);
_inertRoot.destructor();
this._inertRoots['delete'](root);
root.removeAttribute('inert');
}
}
/**
* Get the InertRoot object corresponding to the given inert root element, if any.
* @param {!Node} element
* @return {!InertRoot|undefined}
*/
}, {
key: 'getInertRoot',
value: function getInertRoot(element) {
return this._inertRoots.get(element);
}
/**
* Register the given InertRoot as managing the given node.
* In the case where the node has a previously existing inert root, this inert root will
* be added to its set of inert roots.
* @param {!Node} node
* @param {!InertRoot} inertRoot
* @return {!InertNode} inertNode
*/
}, {
key: 'register',
value: function register(node, inertRoot) {
var inertNode = this._managedNodes.get(node);
if (inertNode !== undefined) {
// node was already in an inert subtree
inertNode.addInertRoot(inertRoot);
} else {
inertNode = new InertNode(node, inertRoot);
}
this._managedNodes.set(node, inertNode);
return inertNode;
}
/**
* De-register the given InertRoot as managing the given inert node.
* Removes the inert root from the InertNode's set of managing inert roots, and remove the inert
* node from the InertManager's set of managed nodes if it is destroyed.
* If the node is not currently managed, this is essentially a no-op.
* @param {!Node} node
* @param {!InertRoot} inertRoot
* @return {?InertNode} The potentially destroyed InertNode associated with this node, if any.
*/
}, {
key: 'deregister',
value: function deregister(node, inertRoot) {
var inertNode = this._managedNodes.get(node);
if (!inertNode) {
return null;
}
inertNode.removeInertRoot(inertRoot);
if (inertNode.destroyed) {
this._managedNodes['delete'](node);
}
return inertNode;
}
/**
* Callback used when document has finished loading.
*/
}, {
key: '_onDocumentLoaded',
value: function _onDocumentLoaded() {
// Find all inert roots in document and make them actually inert.
var inertElements = slice.call(this._document.querySelectorAll('[inert]'));
inertElements.forEach(function (inertElement) {
this.setInert(inertElement, true);
}, this);
// Comment this out to use programmatic API only.
this._observer.observe(this._document.body || this._document.documentElement, {attributes: true, subtree: true, childList: true});
}
/**
* Callback used when mutation observer detects attribute changes.
* @param {!Array<!MutationRecord>} records
* @param {!MutationObserver} self
*/
}, {
key: '_watchForInert',
value: function _watchForInert(records, _self) {
var _this = this;
records.forEach(function (record) {
switch (record.type) {
case 'childList':
slice.call(record.addedNodes).forEach(function (node) {
if (node.nodeType !== Node.ELEMENT_NODE) {
return;
}
var inertElements = slice.call(node.querySelectorAll('[inert]'));
if (matches.call(node, '[inert]')) {
inertElements.unshift(node);
}
inertElements.forEach(function (inertElement) {
this.setInert(inertElement, true);
}, _this);
}, _this);
break;
case 'attributes':
if (record.attributeName !== 'inert') {
return;
}
var target = /** @type {!Element} */record.target;
var inert = target.hasAttribute('inert');
_this.setInert(target, inert);
break;
}
}, this);
}
}]);
return InertManager;
}(); | InertManager is a per-document singleton object which manages all inert roots and nodes.
When an element becomes an inert root by having an `inert` attribute set and/or its `inert`
property set to `true`, the `setInert` method creates an `InertRoot` object for the element.
The `InertRoot` in turn registers itself as managing all of the element's focusable descendant
nodes via the `register()` method. The `InertManager` ensures that a single `InertNode` instance
is created for each such node, via the `_managedNodes` map. | 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 |
function composedTreeWalk(node, callback, shadowRootAncestor) {
if (node.nodeType == Node.ELEMENT_NODE) {
var element = /** @type {!Element} */node;
if (callback) {
callback(element);
}
// Descend into node:
// If it has a ShadowRoot, ignore all child elements - these will be picked
// up by the <content> or <shadow> elements. Descend straight into the
// ShadowRoot.
var shadowRoot = /** @type {!HTMLElement} */element.shadowRoot;
if (shadowRoot) {
composedTreeWalk(shadowRoot, callback, shadowRoot);
return;
}
// If it is a <content> element, descend into distributed elements - these
// are elements from outside the shadow root which are rendered inside the
// shadow DOM.
if (element.localName == 'content') {
var content = /** @type {!HTMLContentElement} */element;
// Verifies if ShadowDom v0 is supported.
var distributedNodes = content.getDistributedNodes ? content.getDistributedNodes() : [];
for (var i = 0; i < distributedNodes.length; i++) {
composedTreeWalk(distributedNodes[i], callback, shadowRootAncestor);
}
return;
}
// If it is a <slot> element, descend into assigned nodes - these
// are elements from outside the shadow root which are rendered inside the
// shadow DOM.
if (element.localName == 'slot') {
var slot = /** @type {!HTMLSlotElement} */element;
// Verify if ShadowDom v1 is supported.
var _distributedNodes = slot.assignedNodes ? slot.assignedNodes({ flatten: true }) : [];
for (var _i = 0; _i < _distributedNodes.length; _i++) {
composedTreeWalk(_distributedNodes[_i], callback, shadowRootAncestor);
}
return;
}
}
// If it is neither the parent of a ShadowRoot, a <content> element, a <slot>
// element, nor a <shadow> element recurse normally.
var child = node.firstChild;
while (child != null) {
composedTreeWalk(child, callback, shadowRootAncestor);
child = child.nextSibling;
}
} | Recursively walk the composed tree from |node|.
@param {!Node} node
@param {(function (!Element))=} callback Callback to be called for each element traversed,
before descending into child nodes.
@param {?ShadowRoot=} shadowRootAncestor The nearest ShadowRoot ancestor, if any. | composedTreeWalk ( node , callback , shadowRootAncestor ) | 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 addInertStyle(node) {
if (node.querySelector('style#inert-style')) {
return;
}
var style = document.createElement('style');
style.setAttribute('id', 'inert-style');
style.textContent = '\n' + '[inert] {\n' + ' pointer-events: none;\n' + ' cursor: default;\n' + '}\n' + '\n' + '[inert], [inert] * {\n' + ' user-select: none;\n' + ' -webkit-user-select: none;\n' + ' -moz-user-select: none;\n' + ' -ms-user-select: none;\n' + '}\n';
node.appendChild(style);
} | Adds a style element to the node containing the inert specific styles
@param {!Node} node | addInertStyle ( node ) | 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 HasOwnProperty(o, prop) {
return Object.prototype.hasOwnProperty.call(o, prop);
} | https://www.ecma-international.org/ecma-262/11.0/index.html#sec-hasownproperty
@param o
@param prop | HasOwnProperty ( o , prop ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | MIT |
function IsSanctionedSimpleUnitIdentifier(unitIdentifier) {
return SIMPLE_UNITS.indexOf(unitIdentifier) > -1;
} | https://tc39.es/ecma402/#sec-issanctionedsimpleunitidentifier | IsSanctionedSimpleUnitIdentifier ( unitIdentifier ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | MIT |
function IsWellFormedUnitIdentifier(unit) {
unit = toLowerCase(unit);
if (IsSanctionedSimpleUnitIdentifier(unit)) {
return true;
}
var units = unit.split('-per-');
if (units.length !== 2) {
return false;
}
var numerator = units[0], denominator = units[1];
if (!IsSanctionedSimpleUnitIdentifier(numerator) ||
!IsSanctionedSimpleUnitIdentifier(denominator)) {
return false;
}
return true;
} | https://tc39.es/ecma402/#sec-iswellformedunitidentifier
@param unit | IsWellFormedUnitIdentifier ( unit ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | MIT |
function ComputeExponentForMagnitude(numberFormat, magnitude, _a) {
var getInternalSlots = _a.getInternalSlots;
var internalSlots = getInternalSlots(numberFormat);
var notation = internalSlots.notation, dataLocaleData = internalSlots.dataLocaleData, numberingSystem = internalSlots.numberingSystem;
switch (notation) {
case 'standard':
return 0;
case 'scientific':
return magnitude;
case 'engineering':
return Math.floor(magnitude / 3) * 3;
default: {
// Let exponent be an implementation- and locale-dependent (ILD) integer by which to scale a
// number of the given magnitude in compact notation for the current locale.
var compactDisplay = internalSlots.compactDisplay, style = internalSlots.style, currencyDisplay = internalSlots.currencyDisplay;
var thresholdMap = void 0;
if (style === 'currency' && currencyDisplay !== 'name') {
var currency = dataLocaleData.numbers.currency[numberingSystem] ||
dataLocaleData.numbers.currency[dataLocaleData.numbers.nu[0]];
thresholdMap = currency.short;
}
else {
var decimal = dataLocaleData.numbers.decimal[numberingSystem] ||
dataLocaleData.numbers.decimal[dataLocaleData.numbers.nu[0]];
thresholdMap = compactDisplay === 'long' ? decimal.long : decimal.short;
}
if (!thresholdMap) {
return 0;
}
var num = String(Math.pow(10, magnitude));
var thresholds = Object.keys(thresholdMap); // TODO: this can be pre-processed
if (num < thresholds[0]) {
return 0;
}
if (num > thresholds[thresholds.length - 1]) {
return thresholds[thresholds.length - 1].length - 1;
}
var i = thresholds.indexOf(num);
if (i === -1) {
return 0;
}
// See https://unicode.org/reports/tr35/tr35-numbers.html#Compact_Number_Formats
// Special handling if the pattern is precisely `0`.
var magnitudeKey = thresholds[i];
// TODO: do we need to handle plural here?
var compactPattern = thresholdMap[magnitudeKey].other;
if (compactPattern === '0') {
return 0;
}
// Example: in zh-TW, `10000000` maps to `0000萬`. So we need to return 8 - 4 = 4 here.
return (magnitudeKey.length -
thresholdMap[magnitudeKey].other.match(/0+/)[0].length);
}
}
} | The abstract operation ComputeExponentForMagnitude computes an exponent by which to scale a
number of the given magnitude (power of ten of the most significant digit) according to the
locale and the desired notation (scientific, engineering, or compact). | ComputeExponentForMagnitude ( numberFormat , magnitude , _a ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | MIT |
function ToRawFixed(x, minFraction, maxFraction) {
var f = maxFraction;
var n = Math.round(x * Math.pow(10, f));
var xFinal = n / Math.pow(10, f);
// n is a positive integer, but it is possible to be greater than 1e21.
// In such case we will go the slow path.
// See also: https://tc39.es/ecma262/#sec-numeric-types-number-tostring
var m;
if (n < 1e21) {
m = n.toString();
}
else {
m = n.toString();
var _a = m.split('e'), mantissa = _a[0], exponent = _a[1];
m = mantissa.replace('.', '');
m = m + repeat('0', Math.max(+exponent - m.length + 1, 0));
}
var int;
if (f !== 0) {
var k = m.length;
if (k <= f) {
var z = repeat('0', f + 1 - k);
m = z + m;
k = f + 1;
}
var a = m.slice(0, k - f);
var b = m.slice(k - f);
m = a + "." + b;
int = a.length;
}
else {
int = m.length;
}
var cut = maxFraction - minFraction;
while (cut > 0 && m[m.length - 1] === '0') {
m = m.slice(0, -1);
cut--;
}
if (m[m.length - 1] === '.') {
m = m.slice(0, -1);
}
return { formattedString: m, roundedNumber: xFinal, integerDigitsCount: int };
} | TODO: dedup with intl-pluralrules and support BigInt
https://tc39.es/ecma402/#sec-torawfixed
@param x a finite non-negative Number or BigInt
@param minFraction and integer between 0 and 20
@param maxFraction and integer between 0 and 20 | ToRawFixed ( x , minFraction , maxFraction ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | MIT |
function FormatNumericToString(intlObject, x) {
var isNegative = x < 0 || SameValue(x, -0);
if (isNegative) {
x = -x;
}
var result;
var rourndingType = intlObject.roundingType;
switch (rourndingType) {
case 'significantDigits':
result = ToRawPrecision(x, intlObject.minimumSignificantDigits, intlObject.maximumSignificantDigits);
break;
case 'fractionDigits':
result = ToRawFixed(x, intlObject.minimumFractionDigits, intlObject.maximumFractionDigits);
break;
default:
result = ToRawPrecision(x, 1, 2);
if (result.integerDigitsCount > 1) {
result = ToRawFixed(x, 0, 0);
}
break;
}
x = result.roundedNumber;
var string = result.formattedString;
var int = result.integerDigitsCount;
var minInteger = intlObject.minimumIntegerDigits;
if (int < minInteger) {
var forwardZeros = repeat('0', minInteger - int);
string = forwardZeros + string;
}
if (isNegative) {
x = -x;
}
return { roundedNumber: x, formattedString: string };
} | https://tc39.es/ecma402/#sec-formatnumberstring | FormatNumericToString ( intlObject , x ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | MIT |
function ComputeExponent(numberFormat, x, _a) {
var getInternalSlots = _a.getInternalSlots;
if (x === 0) {
return [0, 0];
}
if (x < 0) {
x = -x;
}
var magnitude = getMagnitude(x);
var exponent = ComputeExponentForMagnitude(numberFormat, magnitude, {
getInternalSlots: getInternalSlots,
});
// Preserve more precision by doing multiplication when exponent is negative.
x = exponent < 0 ? x * Math.pow(10, -exponent) : x / Math.pow(10, exponent);
var formatNumberResult = FormatNumericToString(getInternalSlots(numberFormat), x);
if (formatNumberResult.roundedNumber === 0) {
return [exponent, magnitude];
}
var newMagnitude = getMagnitude(formatNumberResult.roundedNumber);
if (newMagnitude === magnitude - exponent) {
return [exponent, magnitude];
}
return [
ComputeExponentForMagnitude(numberFormat, magnitude + 1, {
getInternalSlots: getInternalSlots,
}),
magnitude + 1,
];
} | The abstract operation ComputeExponent computes an exponent (power of ten) by which to scale x
according to the number formatting settings. It handles cases such as 999 rounding up to 1000,
requiring a different exponent.
NOT IN SPEC: it returns [exponent, magnitude]. | ComputeExponent ( numberFormat , x , _a ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | MIT |
function CurrencyDigits(c, _a) {
var currencyDigitsData = _a.currencyDigitsData;
return HasOwnProperty(currencyDigitsData, c)
? currencyDigitsData[c]
: 2;
} | https://tc39.es/ecma402/#sec-currencydigits | CurrencyDigits ( c , _a ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | MIT |
function SetNumberFormatUnitOptions(nf, options, _a) {
if (options === void 0) { options = Object.create(null); }
var getInternalSlots = _a.getInternalSlots;
var internalSlots = getInternalSlots(nf);
var style = GetOption(options, 'style', 'string', ['decimal', 'percent', 'currency', 'unit'], 'decimal');
internalSlots.style = style;
var currency = GetOption(options, 'currency', 'string', undefined, undefined);
if (currency !== undefined && !IsWellFormedCurrencyCode(currency)) {
throw RangeError('Malformed currency code');
}
if (style === 'currency' && currency === undefined) {
throw TypeError('currency cannot be undefined');
}
var currencyDisplay = GetOption(options, 'currencyDisplay', 'string', ['code', 'symbol', 'narrowSymbol', 'name'], 'symbol');
var currencySign = GetOption(options, 'currencySign', 'string', ['standard', 'accounting'], 'standard');
var unit = GetOption(options, 'unit', 'string', undefined, undefined);
if (unit !== undefined && !IsWellFormedUnitIdentifier(unit)) {
throw RangeError('Invalid unit argument for Intl.NumberFormat()');
}
if (style === 'unit' && unit === undefined) {
throw TypeError('unit cannot be undefined');
}
var unitDisplay = GetOption(options, 'unitDisplay', 'string', ['short', 'narrow', 'long'], 'short');
if (style === 'currency') {
internalSlots.currency = currency.toUpperCase();
internalSlots.currencyDisplay = currencyDisplay;
internalSlots.currencySign = currencySign;
}
if (style === 'unit') {
internalSlots.unit = unit;
internalSlots.unitDisplay = unitDisplay;
}
} | https://tc39.es/ecma402/#sec-setnumberformatunitoptions | SetNumberFormatUnitOptions ( nf , options , _a ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | MIT |
function SetNumberFormatDigitOptions(internalSlots, opts, mnfdDefault, mxfdDefault, notation) {
var mnid = GetNumberOption(opts, 'minimumIntegerDigits', 1, 21, 1);
var mnfd = opts.minimumFractionDigits;
var mxfd = opts.maximumFractionDigits;
var mnsd = opts.minimumSignificantDigits;
var mxsd = opts.maximumSignificantDigits;
internalSlots.minimumIntegerDigits = mnid;
if (mnsd !== undefined || mxsd !== undefined) {
internalSlots.roundingType = 'significantDigits';
mnsd = DefaultNumberOption(mnsd, 1, 21, 1);
mxsd = DefaultNumberOption(mxsd, mnsd, 21, 21);
internalSlots.minimumSignificantDigits = mnsd;
internalSlots.maximumSignificantDigits = mxsd;
}
else if (mnfd !== undefined || mxfd !== undefined) {
internalSlots.roundingType = 'fractionDigits';
mnfd = DefaultNumberOption(mnfd, 0, 20, mnfdDefault);
var mxfdActualDefault = Math.max(mnfd, mxfdDefault);
mxfd = DefaultNumberOption(mxfd, mnfd, 20, mxfdActualDefault);
internalSlots.minimumFractionDigits = mnfd;
internalSlots.maximumFractionDigits = mxfd;
}
else if (notation === 'compact') {
internalSlots.roundingType = 'compactRounding';
}
else {
internalSlots.roundingType = 'fractionDigits';
internalSlots.minimumFractionDigits = mnfdDefault;
internalSlots.maximumFractionDigits = mxfdDefault;
}
} | https://tc39.es/ecma402/#sec-setnfdigitoptions | SetNumberFormatDigitOptions ( internalSlots , opts , mnfdDefault , mxfdDefault , notation ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | MIT |
function InitializeNumberFormat(nf, locales, opts, _a) {
var getInternalSlots = _a.getInternalSlots, localeData = _a.localeData, availableLocales = _a.availableLocales, numberingSystemNames = _a.numberingSystemNames, getDefaultLocale = _a.getDefaultLocale, currencyDigitsData = _a.currencyDigitsData;
// @ts-ignore
var requestedLocales = CanonicalizeLocaleList(locales);
var options = opts === undefined ? Object.create(null) : ToObject(opts);
var opt = Object.create(null);
var matcher = GetOption(options, 'localeMatcher', 'string', ['lookup', 'best fit'], 'best fit');
opt.localeMatcher = matcher;
var numberingSystem = GetOption(options, 'numberingSystem', 'string', undefined, undefined);
if (numberingSystem !== undefined &&
numberingSystemNames.indexOf(numberingSystem) < 0) {
// 8.a. If numberingSystem does not match the Unicode Locale Identifier type nonterminal,
// throw a RangeError exception.
throw RangeError("Invalid numberingSystems: " + numberingSystem);
}
opt.nu = numberingSystem;
var r = ResolveLocale(availableLocales, requestedLocales, opt,
// [[RelevantExtensionKeys]] slot, which is a constant
['nu'], localeData, getDefaultLocale);
var dataLocaleData = localeData[r.dataLocale];
invariant(!!dataLocaleData, "Missing locale data for " + r.dataLocale);
var internalSlots = getInternalSlots(nf);
internalSlots.locale = r.locale;
internalSlots.dataLocale = r.dataLocale;
internalSlots.numberingSystem = r.nu;
internalSlots.dataLocaleData = dataLocaleData;
SetNumberFormatUnitOptions(nf, options, { getInternalSlots: getInternalSlots });
var style = internalSlots.style;
var mnfdDefault;
var mxfdDefault;
if (style === 'currency') {
var currency = internalSlots.currency;
var cDigits = CurrencyDigits(currency, { currencyDigitsData: currencyDigitsData });
mnfdDefault = cDigits;
mxfdDefault = cDigits;
}
else {
mnfdDefault = 0;
mxfdDefault = style === 'percent' ? 0 : 3;
}
var notation = GetOption(options, 'notation', 'string', ['standard', 'scientific', 'engineering', 'compact'], 'standard');
internalSlots.notation = notation;
SetNumberFormatDigitOptions(internalSlots, options, mnfdDefault, mxfdDefault, notation);
var compactDisplay = GetOption(options, 'compactDisplay', 'string', ['short', 'long'], 'short');
if (notation === 'compact') {
internalSlots.compactDisplay = compactDisplay;
}
var useGrouping = GetOption(options, 'useGrouping', 'boolean', undefined, true);
internalSlots.useGrouping = useGrouping;
var signDisplay = GetOption(options, 'signDisplay', 'string', ['auto', 'never', 'always', 'exceptZero'], 'auto');
internalSlots.signDisplay = signDisplay;
return nf;
} | https://tc39.es/ecma402/#sec-initializenumberformat | InitializeNumberFormat ( nf , locales , opts , _a ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | MIT |
var NumberFormat = function (locales, options) {
// Cannot use `new.target` bc of IE11 & TS transpiles it to something else
if (!this || !(this instanceof NumberFormat)) {
return new NumberFormat(locales, options);
}
InitializeNumberFormat(this, locales, options, {
getInternalSlots: getInternalSlots,
localeData: NumberFormat.localeData,
availableLocales: NumberFormat.availableLocales,
getDefaultLocale: NumberFormat.getDefaultLocale,
currencyDigitsData: currencyDigitsData,
numberingSystemNames: numberingSystemNames,
});
var internalSlots = getInternalSlots(this);
var dataLocale = internalSlots.dataLocale;
var dataLocaleData = NumberFormat.localeData[dataLocale];
invariant(dataLocaleData !== undefined, "Cannot load locale-dependent data for " + dataLocale + ".");
internalSlots.pl = new Intl.PluralRules(dataLocale, {
minimumFractionDigits: internalSlots.minimumFractionDigits,
maximumFractionDigits: internalSlots.maximumFractionDigits,
minimumIntegerDigits: internalSlots.minimumIntegerDigits,
minimumSignificantDigits: internalSlots.minimumSignificantDigits,
maximumSignificantDigits: internalSlots.maximumSignificantDigits,
});
return this;
}; | https://tc39.es/ecma402/#sec-intl-numberformat-constructor | NumberFormat ( locales , options ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | MIT |
function supportsES2020() {
try {
var s = new Intl.NumberFormat('en', {
style: 'unit',
// @ts-expect-error the built-in typing isn't supporting ES2020 yet.
unit: 'bit',
unitDisplay: 'long',
notation: 'scientific',
}).format(10000);
// Check for a plurality bug in environment that uses the older versions of ICU:
// https://unicode-org.atlassian.net/browse/ICU-13836
if (s !== '1E4 bits') {
return false;
}
}
catch (e) {
return false;
}
return true;
} | Check if Intl.NumberFormat is ES2020 compatible.
Caveat: we are not checking `toLocaleString`.
@public
@param unit unit to check | supportsES2020 ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.104.0/Intl.NumberFormat/raw.js | MIT |
function MutationObserver(listener) {
/**
* @type {Array.<Object>}
* @private
*/
this._watched = [];
/** @private */
this._listener = listener;
} | @param {function(Array.<MutationRecord>, MutationObserver)} listener
@constructor | MutationObserver ( listener ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
function startMutationChecker(observer) {
(function check() {
var mutations = observer.takeRecords();
if (mutations.length) { // fire away
// calling the listener with context is not spec but currently consistent with FF and WebKit
observer._listener(mutations, observer);
}
/** @private */
observer._timeout = setTimeout(check, MutationObserver._period);
})();
} | Start a recursive timeout function to check all items being observed for mutations
@type {MutationObserver} observer
@private | startMutationChecker ( observer ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
settings.afilter = reduce(config.attributeFilter, function (a, b) {
a[b] = true;
return a;
}, {}); | converts to a {key: true} dict for faster lookup
@type {Object.<String,Boolean>} | (anonymous) ( a , b ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
takeRecords: function () {
var mutations = [];
var watched = this._watched;
for (var i = 0; i < watched.length; i++) {
watched[i].fn(mutations);
}
return mutations;
}, | Finds mutations since last check and empties the "record queue" i.e. mutations will only be found once
@expose
@return {Array.<MutationRecord>} | takeRecords ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
function MutationRecord(data) {
var settings = { // technically these should be on proto so hasOwnProperty will return false for non explicitly props
type: null,
target: null,
addedNodes: [],
removedNodes: [],
previousSibling: null,
nextSibling: null,
attributeName: null,
attributeNamespace: null,
oldValue: null
};
for (var prop in data) {
if (has(settings, prop) && data[prop] !== undefined) settings[prop] = data[prop];
}
return settings;
} | Simple MutationRecord pseudoclass. No longer exposing as its not fully compliant
@param {Object} data
@return {Object} a MutationRecord | MutationRecord ( data ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
return function (mutations) {
var olen = mutations.length, dirty;
if (config.charData && $target.nodeType === 3 && $target.nodeValue !== $oldstate.charData) {
mutations.push(new MutationRecord({
type: "characterData",
target: $target,
oldValue: $oldstate.charData
}));
}
// Alright we check base level changes in attributes... easy
if (config.attr && $oldstate.attr) {
findAttributeMutations(mutations, $target, $oldstate.attr, config.afilter);
}
// check childlist or subtree for mutations
if (config.kids || config.descendents) {
dirty = searchSubtree(mutations, $target, $oldstate, config);
}
// reclone data structure if theres changes
if (dirty || mutations.length !== olen) {
/** type {Elestuct} */
$oldstate = clone($target, config);
}
}; | consumes array of mutations we can push to
@param {Array.<MutationRecord>} mutations | (anonymous) ( mutations ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
function createMutationSearcher($target, config) {
/** type {Elestuct} */
var $oldstate = clone($target, config); // create the cloned datastructure
/**
* consumes array of mutations we can push to
*
* @param {Array.<MutationRecord>} mutations
*/
return function (mutations) {
var olen = mutations.length, dirty;
if (config.charData && $target.nodeType === 3 && $target.nodeValue !== $oldstate.charData) {
mutations.push(new MutationRecord({
type: "characterData",
target: $target,
oldValue: $oldstate.charData
}));
}
// Alright we check base level changes in attributes... easy
if (config.attr && $oldstate.attr) {
findAttributeMutations(mutations, $target, $oldstate.attr, config.afilter);
}
// check childlist or subtree for mutations
if (config.kids || config.descendents) {
dirty = searchSubtree(mutations, $target, $oldstate, config);
}
// reclone data structure if theres changes
if (dirty || mutations.length !== olen) {
/** type {Elestuct} */
$oldstate = clone($target, config);
}
};
} | Creates a func to find all the mutations
@param {Node} $target
@param {!Object} config : A custom mutation config | createMutationSearcher ( $target , config ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
function getAttributeSimple(el, attr) {
// There is a potential for a warning to occur here if the attribute is a
// custom attribute in IE<9 with a custom .toString() method. This is
// just a warning and doesn't affect execution (see #21)
return attr.value;
} | Gets an attribute value in an environment without attribute bug
@param {Node} el
@param {Attr} attr
@return {String} an attribute value | getAttributeSimple ( el , attr ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
function getAttributeWithStyleHack(el, attr) {
// As with getAttributeSimple there is a potential warning for custom attribtues in IE7.
return attr.name !== "style" ? attr.value : el.style.cssText;
} | Gets an attribute value with special hack for style attribute (see #4)
@param {Node} el
@param {Attr} attr
@return {String} an attribute value | getAttributeWithStyleHack ( el , attr ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
function findAttributeMutations(mutations, $target, $oldstate, filter) {
var checked = {};
var attributes = $target.attributes;
var attr;
var name;
var i = attributes.length;
while (i--) {
attr = attributes[i];
name = attr.name;
if (!filter || has(filter, name)) {
if (getAttributeValue($target, attr) !== $oldstate[name]) {
// The pushing is redundant but gzips very nicely
mutations.push(MutationRecord({
type: "attributes",
target: $target,
attributeName: name,
oldValue: $oldstate[name],
attributeNamespace: attr.namespaceURI // in ie<8 it incorrectly will return undefined
}));
}
checked[name] = true;
}
}
for (name in $oldstate) {
if (!(checked[name])) {
mutations.push(MutationRecord({
target: $target,
type: "attributes",
attributeName: name,
oldValue: $oldstate[name]
}));
}
}
} | fast helper to check to see if attributes object of an element has changed
doesnt handle the textnode case
@param {Array.<MutationRecord>} mutations
@param {Node} $target
@param {Object.<string, string>} $oldstate : Custom attribute clone data structure from clone
@param {Object} filter | findAttributeMutations ( mutations , $target , $oldstate , filter ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
function findMutations(node, old) {
var $kids = node.childNodes;
var $oldkids = old.kids;
var klen = $kids.length;
// $oldkids will be undefined for text and comment nodes
var olen = $oldkids ? $oldkids.length : 0;
// if (!olen && !klen) return; // both empty; clearly no changes
// we delay the intialization of these for marginal performance in the expected case (actually quite signficant on large subtrees when these would be otherwise unused)
// map of checked element of ids to prevent registering the same conflict twice
var map;
// array of potential conflicts (ie nodes that may have been re arranged)
var conflicts;
var id; // element id from getElementId helper
var idx; // index of a moved or inserted element
var oldstruct;
// current and old nodes
var $cur;
var $old;
// track the number of added nodes so we can resolve conflicts more accurately
var numAddedNodes = 0;
// iterate over both old and current child nodes at the same time
var i = 0, j = 0;
// while there is still anything left in $kids or $oldkids (same as i < $kids.length || j < $oldkids.length;)
while (i < klen || j < olen) {
// current and old nodes at the indexs
$cur = $kids[i];
oldstruct = $oldkids[j];
$old = oldstruct && oldstruct.node;
if ($cur === $old) { // expected case - optimized for this case
// check attributes as specified by config
if (config.attr && oldstruct.attr) /* oldstruct.attr instead of textnode check */findAttributeMutations(mutations, $cur, oldstruct.attr, config.afilter);
// check character data if node is a comment or textNode and it's being observed
if (config.charData && oldstruct.charData !== undefined && $cur.nodeValue !== oldstruct.charData) {
mutations.push(MutationRecord({
type: "characterData",
target: $cur,
oldValue: oldstruct.charData
}));
}
// resolve conflicts; it will be undefined if there are no conflicts - otherwise an array
if (conflicts) resolveConflicts(conflicts, node, $kids, $oldkids, numAddedNodes);
// recurse on next level of children. Avoids the recursive call when there are no children left to iterate
if (config.descendents && ($cur.childNodes.length || oldstruct.kids && oldstruct.kids.length)) findMutations($cur, oldstruct);
i++;
j++;
} else { // (uncommon case) lookahead until they are the same again or the end of children
dirty = true;
if (!map) { // delayed initalization (big perf benefit)
map = {};
conflicts = [];
}
if ($cur) {
// check id is in the location map otherwise do a indexOf search
if (!(map[id = getElementId($cur)])) { // to prevent double checking
// mark id as found
map[id] = true;
// custom indexOf using comparitor checking oldkids[i].node === $cur
if ((idx = indexOfCustomNode($oldkids, $cur, j)) === -1) {
if (config.kids) {
mutations.push(MutationRecord({
type: "childList",
target: node,
addedNodes: [$cur], // $cur is a new node
nextSibling: $cur.nextSibling,
previousSibling: $cur.previousSibling
}));
numAddedNodes++;
}
} else {
conflicts.push({ // add conflict
i: i,
j: idx
});
}
}
i++;
}
if ($old &&
// special case: the changes may have been resolved: i and j appear congurent so we can continue using the expected case
$old !== $kids[i]
) {
if (!(map[id = getElementId($old)])) {
map[id] = true;
if ((idx = indexOf($kids, $old, i)) === -1) {
if (config.kids) {
mutations.push(MutationRecord({
type: "childList",
target: old.node,
removedNodes: [$old],
nextSibling: $oldkids[j + 1], // praise no indexoutofbounds exception
previousSibling: $oldkids[j - 1]
}));
numAddedNodes--;
}
} else {
conflicts.push({
i: idx,
j: j
});
}
}
j++;
}
}// end uncommon case
}// end loop
// resolve any remaining conflicts
if (conflicts) resolveConflicts(conflicts, node, $kids, $oldkids, numAddedNodes);
} | Main worker. Finds and adds mutations if there are any
@param {Node} node
@param {!Object} old : A cloned data structure using internal clone | findMutations ( node , old ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
function searchSubtree(mutations, $target, $oldstate, config) {
// Track if the tree is dirty and has to be recomputed (#14).
var dirty;
/*
* Helper to identify node rearrangment and stuff...
* There is no gaurentee that the same node will be identified for both added and removed nodes
* if the positions have been shuffled.
* conflicts array will be emptied by end of operation
*/
function resolveConflicts(conflicts, node, $kids, $oldkids, numAddedNodes) {
// the distance between the first conflicting node and the last
var distance = conflicts.length - 1;
// prevents same conflict being resolved twice consider when two nodes switch places.
// only one should be given a mutation event (note -~ is used as a math.ceil shorthand)
var counter = -~((distance - numAddedNodes) / 2);
var $cur;
var oldstruct;
var conflict;
while ((conflict = conflicts.pop())) {
$cur = $kids[conflict.i];
oldstruct = $oldkids[conflict.j];
// attempt to determine if there was node rearrangement... won't gaurentee all matches
// also handles case where added/removed nodes cause nodes to be identified as conflicts
if (config.kids && counter && Math.abs(conflict.i - conflict.j) >= distance) {
mutations.push(MutationRecord({
type: "childList",
target: node,
addedNodes: [$cur],
removedNodes: [$cur],
// haha don't rely on this please
nextSibling: $cur.nextSibling,
previousSibling: $cur.previousSibling
}));
counter--; // found conflict
}
// Alright we found the resorted nodes now check for other types of mutations
if (config.attr && oldstruct.attr) findAttributeMutations(mutations, $cur, oldstruct.attr, config.afilter);
if (config.charData && $cur.nodeType === 3 && $cur.nodeValue !== oldstruct.charData) {
mutations.push(MutationRecord({
type: "characterData",
target: $cur,
oldValue: oldstruct.charData
}));
}
// now look @ subtree
if (config.descendents) findMutations($cur, oldstruct);
}
}
/**
* Main worker. Finds and adds mutations if there are any
* @param {Node} node
* @param {!Object} old : A cloned data structure using internal clone
*/
function findMutations(node, old) {
var $kids = node.childNodes;
var $oldkids = old.kids;
var klen = $kids.length;
// $oldkids will be undefined for text and comment nodes
var olen = $oldkids ? $oldkids.length : 0;
// if (!olen && !klen) return; // both empty; clearly no changes
// we delay the intialization of these for marginal performance in the expected case (actually quite signficant on large subtrees when these would be otherwise unused)
// map of checked element of ids to prevent registering the same conflict twice
var map;
// array of potential conflicts (ie nodes that may have been re arranged)
var conflicts;
var id; // element id from getElementId helper
var idx; // index of a moved or inserted element
var oldstruct;
// current and old nodes
var $cur;
var $old;
// track the number of added nodes so we can resolve conflicts more accurately
var numAddedNodes = 0;
// iterate over both old and current child nodes at the same time
var i = 0, j = 0;
// while there is still anything left in $kids or $oldkids (same as i < $kids.length || j < $oldkids.length;)
while (i < klen || j < olen) {
// current and old nodes at the indexs
$cur = $kids[i];
oldstruct = $oldkids[j];
$old = oldstruct && oldstruct.node;
if ($cur === $old) { // expected case - optimized for this case
// check attributes as specified by config
if (config.attr && oldstruct.attr) /* oldstruct.attr instead of textnode check */findAttributeMutations(mutations, $cur, oldstruct.attr, config.afilter);
// check character data if node is a comment or textNode and it's being observed
if (config.charData && oldstruct.charData !== undefined && $cur.nodeValue !== oldstruct.charData) {
mutations.push(MutationRecord({
type: "characterData",
target: $cur,
oldValue: oldstruct.charData
}));
}
// resolve conflicts; it will be undefined if there are no conflicts - otherwise an array
if (conflicts) resolveConflicts(conflicts, node, $kids, $oldkids, numAddedNodes);
// recurse on next level of children. Avoids the recursive call when there are no children left to iterate
if (config.descendents && ($cur.childNodes.length || oldstruct.kids && oldstruct.kids.length)) findMutations($cur, oldstruct);
i++;
j++;
} else { // (uncommon case) lookahead until they are the same again or the end of children
dirty = true;
if (!map) { // delayed initalization (big perf benefit)
map = {};
conflicts = [];
}
if ($cur) {
// check id is in the location map otherwise do a indexOf search
if (!(map[id = getElementId($cur)])) { // to prevent double checking
// mark id as found
map[id] = true;
// custom indexOf using comparitor checking oldkids[i].node === $cur
if ((idx = indexOfCustomNode($oldkids, $cur, j)) === -1) {
if (config.kids) {
mutations.push(MutationRecord({
type: "childList",
target: node,
addedNodes: [$cur], // $cur is a new node
nextSibling: $cur.nextSibling,
previousSibling: $cur.previousSibling
}));
numAddedNodes++;
}
} else {
conflicts.push({ // add conflict
i: i,
j: idx
});
}
}
i++;
}
if ($old &&
// special case: the changes may have been resolved: i and j appear congurent so we can continue using the expected case
$old !== $kids[i]
) {
if (!(map[id = getElementId($old)])) {
map[id] = true;
if ((idx = indexOf($kids, $old, i)) === -1) {
if (config.kids) {
mutations.push(MutationRecord({
type: "childList",
target: old.node,
removedNodes: [$old],
nextSibling: $oldkids[j + 1], // praise no indexoutofbounds exception
previousSibling: $oldkids[j - 1]
}));
numAddedNodes--;
}
} else {
conflicts.push({
i: idx,
j: j
});
}
}
j++;
}
}// end uncommon case
}// end loop
// resolve any remaining conflicts
if (conflicts) resolveConflicts(conflicts, node, $kids, $oldkids, numAddedNodes);
}
findMutations($target, $oldstate);
return dirty;
} | searchSubtree: array of mutations so far, element, element clone, bool
synchronous dfs comparision of two nodes
This function is applied to any observed element with childList or subtree specified
Sorry this is kind of confusing as shit, tried to comment it a bit...
codereview.stackexchange.com/questions/38351 discussion of an earlier version of this func
@param {Array} mutations
@param {Node} $target
@param {!Object} $oldstate : A custom cloned node from clone()
@param {!Object} config : A custom mutation config | searchSubtree ( mutations , $target , $oldstate , config ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
elestruct.attr = reduce($target.attributes, function (memo, attr) {
if (!config.afilter || config.afilter[attr.name]) {
memo[attr.name] = getAttributeValue($target, attr);
}
return memo;
}, {}); | clone live attribute list to an object structure {name: val}
@type {Object.<string, string>} | (anonymous) ( memo , attr ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
function clone($target, config) {
var recurse = true; // set true so childList we'll always check the first level
return (function copy($target) {
var elestruct = {
/** @type {Node} */
node: $target
};
// Store current character data of target text or comment node if the config requests
// those properties to be observed.
if (config.charData && ($target.nodeType === 3 || $target.nodeType === 8)) {
elestruct.charData = $target.nodeValue;
}
// its either a element, comment, doc frag or document node
else {
// Add attr only if subtree is specified or top level and avoid if
// attributes is a document object (#13).
if (config.attr && recurse && $target.nodeType === 1) {
/**
* clone live attribute list to an object structure {name: val}
* @type {Object.<string, string>}
*/
elestruct.attr = reduce($target.attributes, function (memo, attr) {
if (!config.afilter || config.afilter[attr.name]) {
memo[attr.name] = getAttributeValue($target, attr);
}
return memo;
}, {});
}
// whether we should iterate the children of $target node
if (recurse && ((config.kids || config.charData) || (config.attr && config.descendents))) {
/** @type {Array.<!Object>} : Array of custom clone */
elestruct.kids = map($target.childNodes, copy);
}
recurse = config.descendents;
}
return elestruct;
})($target);
} | Utility
Cones a element into a custom data structure designed for comparision. https://gist.github.com/megawac/8201012
@param {Node} $target
@param {!Object} config : A custom mutation config
@return {!Object} : Cloned data structure | clone ( $target , config ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
function indexOfCustomNode(set, $node, idx) {
return indexOf(set, $node, idx, JSCompiler_renameProperty("node"));
} | indexOf an element in a collection of custom nodes
@param {NodeList} set
@param {!Object} $node : A custom cloned node
@param {number} idx : index to start the loop
@return {number} | indexOfCustomNode ( set , $node , idx ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
function getElementId($ele) {
try {
return $ele.id || ($ele[expando] = $ele[expando] || counter++);
} catch (o_O) { // ie <8 will throw if you set an unknown property on a text node
try {
return $ele.nodeValue; // naive
} catch (shitie) { // when text node is removed: https://gist.github.com/megawac/8355978 :(
return counter++;
}
}
} | Attempt to uniquely id an element for hashing. We could optimize this for legacy browsers but it hopefully wont be called enough to be a concern
@param {Node} $ele
@return {(string|number)} | getElementId ( $ele ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
function map(set, iterator) {
var results = [];
for (var index = 0; index < set.length; index++) {
results[index] = iterator(set[index], index, set);
}
return results;
} | **map** Apply a mapping function to each item of a set
@param {Array|NodeList} set
@param {Function} iterator | map ( set , iterator ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
function reduce(set, iterator, memo) {
for (var index = 0; index < set.length; index++) {
memo = iterator(memo, set[index], index, set);
}
return memo;
} | **Reduce** builds up a single result from a list of values
@param {Array|NodeList|NamedNodeMap} set
@param {Function} iterator
@param {*} [memo] Initial value of the memo. | reduce ( set , iterator , memo ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
function has(obj, prop) {
return obj[prop] !== undefined; // will be nicely inlined by gcc
} | @param {Object} obj
@param {(string|number)} prop
@return {boolean} | has ( obj , prop ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
function indexOf(set, item, idx, prop) {
for (/*idx = ~~idx*/; idx < set.length; idx++) {// start idx is always given as this is internal
if ((prop ? set[idx][prop] : set[idx]) === item) return idx;
}
return -1;
}
/**
* @param {Object} obj
* @param {(string|number)} prop
* @return {boolean}
*/
function has(obj, prop) {
return obj[prop] !== undefined; // will be nicely inlined by gcc
}
// GCC hack see https://stackoverflow.com/a/23202438/1517919
function JSCompiler_renameProperty(a) {
return a;
}
return MutationObserver;
})(void 0); | **indexOf** find index of item in collection.
@param {Array|NodeList} set
@param {Object} item
@param {number} idx
@param {string} [prop] Property on set item to compare to item | indexOf ( set , item , idx , prop ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/MutationObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/MutationObserver/raw.js | MIT |
function stringListFromIterable(list) {
if (list === undefined) {
return [];
}
var result = [];
for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
var el = list_1[_i];
if (typeof el !== 'string') {
throw new TypeError("array list[" + list.indexOf(el) + "] is not type String");
}
result.push(el);
}
return result;
} | https://tc39.es/proposal-intl-list-format/#sec-createstringlistfromiterable
@param list list | stringListFromIterable ( list ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/Intl.ListFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/Intl.ListFormat/raw.js | MIT |
function GetOperands(s) {
invariant(typeof s === 'string', "GetOperands should have been called with a string");
var n = ToNumber(s);
invariant(isFinite(n), 'n should be finite');
var dp = s.indexOf('.');
var iv;
var f;
var v;
var fv = '';
if (dp === -1) {
iv = n;
f = 0;
v = 0;
}
else {
iv = s.slice(0, dp);
fv = s.slice(dp, s.length);
f = ToNumber(fv);
v = fv.length;
}
var i = Math.abs(ToNumber(iv));
var w;
var t;
if (f !== 0) {
var ft = fv.replace(/0+$/, '');
w = ft.length;
t = ToNumber(ft);
}
else {
w = 0;
t = 0;
}
return {
Number: n,
IntegerDigits: i,
NumberOfFractionDigits: v,
NumberOfFractionDigitsWithoutTrailing: w,
FractionDigits: f,
FractionDigitsWithoutTrailing: t,
};
} | http://ecma-international.org/ecma-402/7.0/index.html#sec-getoperands
@param s | GetOperands ( s ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.104.0/Intl.PluralRules/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.104.0/Intl.PluralRules/raw.js | MIT |
function ResolvePlural(pl, n, _a) {
var getInternalSlots = _a.getInternalSlots, PluralRuleSelect = _a.PluralRuleSelect;
var internalSlots = getInternalSlots(pl);
invariant(Type(internalSlots) === 'Object', 'pl has to be an object');
invariant('initializedPluralRules' in internalSlots, 'pluralrules must be initialized');
invariant(Type(n) === 'Number', 'n must be a number');
if (!isFinite(n)) {
return 'other';
}
var locale = internalSlots.locale, type = internalSlots.type;
var res = FormatNumericToString(internalSlots, n);
var s = res.formattedString;
var operands = GetOperands(s);
return PluralRuleSelect(locale, type, n, operands);
} | http://ecma-international.org/ecma-402/7.0/index.html#sec-resolveplural
@param pl
@param n
@param PluralRuleSelect Has to pass in bc it's implementation-specific | ResolvePlural ( pl , n , _a ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.104.0/Intl.PluralRules/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.104.0/Intl.PluralRules/raw.js | MIT |
function PluralRuleSelect(locale, type, _n, _a) {
var IntegerDigits = _a.IntegerDigits, NumberOfFractionDigits = _a.NumberOfFractionDigits, FractionDigits = _a.FractionDigits;
return PluralRules.localeData[locale].fn(NumberOfFractionDigits
? IntegerDigits + "." + FractionDigits
: IntegerDigits, type === 'ordinal');
}
var PluralRules = /** @class */ (function () {
function PluralRules(locales, options) {
// 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 PluralRules ? this.constructor : void 0;
if (!newTarget) {
throw new TypeError("Intl.PluralRules must be called with 'new'");
}
return InitializePluralRules(this, locales, options, {
availableLocales: PluralRules.availableLocales,
relevantExtensionKeys: PluralRules.relevantExtensionKeys,
localeData: PluralRules.localeData,
getDefaultLocale: PluralRules.getDefaultLocale,
getInternalSlots: getInternalSlots,
});
}
PluralRules.prototype.resolvedOptions = function () {
validateInstance(this, 'resolvedOptions');
var opts = Object.create(null);
var internalSlots = getInternalSlots(this);
opts.locale = internalSlots.locale;
opts.type = internalSlots.type;
[
'minimumIntegerDigits',
'minimumFractionDigits',
'maximumFractionDigits',
'minimumSignificantDigits',
'maximumSignificantDigits',
].forEach(function (field) {
var val = internalSlots[field];
if (val !== undefined) {
opts[field] = val;
}
});
opts.pluralCategories = __spreadArrays(PluralRules.localeData[opts.locale].categories[opts.type]);
return opts;
};
PluralRules.prototype.select = function (val) {
var pr = this;
validateInstance(pr, 'select');
var n = ToNumber(val);
return ResolvePlural(pr, n, { getInternalSlots: getInternalSlots, PluralRuleSelect: PluralRuleSelect });
};
PluralRules.prototype.toString = function () {
return '[object Intl.PluralRules]';
};
PluralRules.supportedLocalesOf = function (locales, options) {
return SupportedLocales(PluralRules.availableLocales, CanonicalizeLocaleList(locales), options);
};
PluralRules.__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;
PluralRules.localeData[locale] = d;
PluralRules.availableLocales.add(locale);
if (!PluralRules.__defaultLocale) {
PluralRules.__defaultLocale = locale;
}
}
};
PluralRules.getDefaultLocale = function () {
return PluralRules.__defaultLocale;
};
PluralRules.localeData = {};
PluralRules.availableLocales = new Set();
PluralRules.__defaultLocale = '';
PluralRules.relevantExtensionKeys = [];
PluralRules.polyfilled = true;
return PluralRules;
}());
try {
// IE11 does not have Symbol
if (typeof Symbol !== 'undefined') {
Object.defineProperty(PluralRules.prototype, Symbol.toStringTag, {
value: 'Intl.PluralRules',
writable: false,
enumerable: false,
configurable: true,
});
}
try {
// https://github.com/tc39/test262/blob/master/test/intl402/PluralRules/length.js
Object.defineProperty(PluralRules, 'length', {
value: 0,
writable: false,
enumerable: false,
configurable: true,
});
}
catch (error) {
// IE 11 sets Function.prototype.length to be non-configurable which will cause the
// above Object.defineProperty to throw an error.
}
// https://github.com/tc39/test262/blob/master/test/intl402/RelativeTimeFormat/constructor/length.js
Object.defineProperty(PluralRules.prototype.constructor, 'length', {
value: 0,
writable: false,
enumerable: false,
configurable: true,
});
// https://github.com/tc39/test262/blob/master/test/intl402/RelativeTimeFormat/constructor/supportedLocalesOf/length.js
Object.defineProperty(PluralRules.supportedLocalesOf, 'length', {
value: 1,
writable: false,
enumerable: false,
configurable: true,
});
}
catch (ex) {
// Meta fixes for test262
}
function shouldPolyfill() {
return (typeof Intl === 'undefined' ||
!('PluralRules' in Intl) ||
new Intl.PluralRules('en', { minimumFractionDigits: 2 }).select(1) ===
'one');
}
if (shouldPolyfill()) {
Object.defineProperty(Intl, 'PluralRules', {
value: PluralRules,
writable: true,
enumerable: false,
configurable: true,
});
}
}))); | http://ecma-international.org/ecma-402/7.0/index.html#sec-pluralruleselect
@param locale
@param type
@param _n
@param param3 | PluralRuleSelect ( locale , type , _n , _a ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.104.0/Intl.PluralRules/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.104.0/Intl.PluralRules/raw.js | MIT |
var alignNearest = function (scrollingEdgeStart, scrollingEdgeEnd, scrollingSize, scrollingBorderStart, scrollingBorderEnd, elementEdgeStart, elementEdgeEnd, elementSize) {
/**
* If element edge A and element edge B are both outside scrolling box edge A and scrolling box edge B
*
* ┌──┐
* ┏━│━━│━┓
* │ │
* ┃ │ │ ┃ do nothing
* │ │
* ┗━│━━│━┛
* └──┘
*
* If element edge C and element edge D are both outside scrolling box edge C and scrolling box edge D
*
* ┏ ━ ━ ━ ━ ┓
* ┌───────────┐
* │┃ ┃│ do nothing
* └───────────┘
* ┗ ━ ━ ━ ━ ┛
*/
if ((elementEdgeStart < scrollingEdgeStart && elementEdgeEnd > scrollingEdgeEnd) ||
(elementEdgeStart > scrollingEdgeStart && elementEdgeEnd < scrollingEdgeEnd)) {
return 0;
}
/**
* If element edge A is outside scrolling box edge A and element height is less than scrolling box height
*
* ┌──┐
* ┏━│━━│━┓ ┏━┌━━┐━┓
* └──┘ │ │
* from ┃ ┃ to ┃ └──┘ ┃
*
* ┗━ ━━ ━┛ ┗━ ━━ ━┛
*
* If element edge B is outside scrolling box edge B and element height is greater than scrolling box height
*
* ┏━ ━━ ━┓ ┏━┌━━┐━┓
* │ │
* from ┃ ┌──┐ ┃ to ┃ │ │ ┃
* │ │ │ │
* ┗━│━━│━┛ ┗━│━━│━┛
* │ │ └──┘
* │ │
* └──┘
*
* If element edge C is outside scrolling box edge C and element width is less than scrolling box width
*
* from to
* ┏ ━ ━ ━ ━ ┓ ┏ ━ ━ ━ ━ ┓
* ┌───┐ ┌───┐
* │ ┃ │ ┃ ┃ │ ┃
* └───┘ └───┘
* ┗ ━ ━ ━ ━ ┛ ┗ ━ ━ ━ ━ ┛
*
* If element edge D is outside scrolling box edge D and element width is greater than scrolling box width
*
* from to
* ┏ ━ ━ ━ ━ ┓ ┏ ━ ━ ━ ━ ┓
* ┌───────────┐ ┌───────────┐
* ┃ │ ┃ │ ┃ ┃ │
* └───────────┘ └───────────┘
* ┗ ━ ━ ━ ━ ┛ ┗ ━ ━ ━ ━ ┛
*/
if ((elementEdgeStart <= scrollingEdgeStart && elementSize <= scrollingSize) ||
(elementEdgeEnd >= scrollingEdgeEnd && elementSize >= scrollingSize)) {
return elementEdgeStart - scrollingEdgeStart - scrollingBorderStart;
}
/**
* If element edge B is outside scrolling box edge B and element height is less than scrolling box height
*
* ┏━ ━━ ━┓ ┏━ ━━ ━┓
*
* from ┃ ┃ to ┃ ┌──┐ ┃
* ┌──┐ │ │
* ┗━│━━│━┛ ┗━└━━┘━┛
* └──┘
*
* If element edge A is outside scrolling box edge A and element height is greater than scrolling box height
*
* ┌──┐
* │ │
* │ │ ┌──┐
* ┏━│━━│━┓ ┏━│━━│━┓
* │ │ │ │
* from ┃ └──┘ ┃ to ┃ │ │ ┃
* │ │
* ┗━ ━━ ━┛ ┗━└━━┘━┛
*
* If element edge C is outside scrolling box edge C and element width is greater than scrolling box width
*
* from to
* ┏ ━ ━ ━ ━ ┓ ┏ ━ ━ ━ ━ ┓
* ┌───────────┐ ┌───────────┐
* │ ┃ │ ┃ │ ┃ ┃
* └───────────┘ └───────────┘
* ┗ ━ ━ ━ ━ ┛ ┗ ━ ━ ━ ━ ┛
*
* If element edge D is outside scrolling box edge D and element width is less than scrolling box width
*
* from to
* ┏ ━ ━ ━ ━ ┓ ┏ ━ ━ ━ ━ ┓
* ┌───┐ ┌───┐
* ┃ │ ┃ │ ┃ │ ┃
* └───┘ └───┘
* ┗ ━ ━ ━ ━ ┛ ┗ ━ ━ ━ ━ ┛
*
*/
if ((elementEdgeEnd > scrollingEdgeEnd && elementSize < scrollingSize) ||
(elementEdgeStart < scrollingEdgeStart && elementSize > scrollingSize)) {
return elementEdgeEnd - scrollingEdgeEnd + scrollingBorderEnd;
}
return 0;
}; | Find out which edge to align against when logical scroll position is "nearest"
Interesting fact: "nearest" works similarily to "if-needed", if the element is fully visible it will not scroll it
Legends:
┌────────┐ ┏ ━ ━ ━ ┓
│ target │ frame
└────────┘ ┗ ━ ━ ━ ┛ | alignNearest ( scrollingEdgeStart , scrollingEdgeEnd , scrollingSize , scrollingBorderStart , scrollingBorderEnd , elementEdgeStart , elementEdgeEnd , elementSize ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.104.0/smoothscroll/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.104.0/smoothscroll/raw.js | MIT |
function findFields(locale) {
var localeData = RelativeTimeFormat.__localeData__;
var data = localeData[locale.toLowerCase()];
// The locale data is de-duplicated, so we have to traverse the locale's
// hierarchy until we find `fields` to return.
while (data) {
if (data.fields) {
return data.fields;
}
data = data.parentLocale
? localeData[data.parentLocale.toLowerCase()]
: undefined;
}
throw new Error("Locale data added to RelativeTimeFormat is missing 'fields' for \"" + locale + "\"");
} | Find the correct field data in our CLDR data
@param locale locale | findFields ( locale ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.89.4/Intl.RelativeTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.89.4/Intl.RelativeTimeFormat/raw.js | MIT |
function SingularRelativeTimeUnit(unit) {
invariant(Type(unit) === 'String', 'unit must be a string');
if (unit === 'seconds')
return 'second';
if (unit === 'minutes')
return 'minute';
if (unit === 'hours')
return 'hour';
if (unit === 'days')
return 'day';
if (unit === 'weeks')
return 'week';
if (unit === 'months')
return 'month';
if (unit === 'quarters')
return 'quarter';
if (unit === 'years')
return 'year';
if (unit !== 'second' &&
unit !== 'minute' &&
unit !== 'hour' &&
unit !== 'day' &&
unit !== 'week' &&
unit !== 'month' &&
unit !== 'quarter' &&
unit !== 'year') {
throw new RangeError('invalid unit');
}
return unit;
} | https://tc39.es/proposal-intl-relative-time/#sec-singularrelativetimeunit
@param unit | SingularRelativeTimeUnit ( unit ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.101.0/polyfills/__dist/Intl.RelativeTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.101.0/polyfills/__dist/Intl.RelativeTimeFormat/raw.js | MIT |
function IntersectionObserverEntry(entry) {
this.time = entry.time;
this.target = entry.target;
this.rootBounds = entry.rootBounds;
this.boundingClientRect = entry.boundingClientRect;
this.intersectionRect = entry.intersectionRect || getEmptyRect();
try {
this.isIntersecting = !!entry.intersectionRect;
} catch (err) {
// This means we are using the IntersectionObserverEntry polyfill which has only defined a getter
}
// Calculates the intersection ratio.
var targetRect = this.boundingClientRect;
var targetArea = targetRect.width * targetRect.height;
var intersectionRect = this.intersectionRect;
var intersectionArea = intersectionRect.width * intersectionRect.height;
// Sets intersection ratio.
if (targetArea) {
this.intersectionRatio = intersectionArea / targetArea;
} else {
// If area is zero and is intersecting, sets to 1, otherwise to 0
this.intersectionRatio = this.isIntersecting ? 1 : 0;
}
} | Creates the global IntersectionObserverEntry constructor.
https://wicg.github.io/IntersectionObserver/#intersection-observer-entry
@param {Object} entry A dictionary of instance properties.
@constructor | IntersectionObserverEntry ( entry ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.34.0/IntersectionObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.34.0/IntersectionObserver/raw.js | MIT |
IntersectionObserver.prototype._monitorIntersections = function() {
if (!this._monitoringIntersections) {
this._monitoringIntersections = true;
this._checkForIntersections();
// If a poll interval is set, use polling instead of listening to
// resize and scroll events or DOM mutations.
if (this.POLL_INTERVAL) {
this._monitoringInterval = setInterval(
this._checkForIntersections, this.POLL_INTERVAL);
}
else {
addEvent(window, 'resize', this._checkForIntersections, true);
addEvent(document, 'scroll', this._checkForIntersections, true);
if ('MutationObserver' in window) {
this._domObserver = new MutationObserver(this._checkForIntersections);
this._domObserver.observe(document, {
attributes: true,
childList: true,
characterData: true,
subtree: true
});
}
}
}
}; | Starts polling for intersection changes if the polling is not already
happening, and if the page's visibilty state is visible.
@private | IntersectionObserver.prototype._monitorIntersections ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.34.0/IntersectionObserver/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.34.0/IntersectionObserver/raw.js | MIT |
(function(global) {
var counter = Date.now() % 1e9;
var WeakSet = function WeakSet(data) {
this.name = '__st' + (Math.random() * 1e9 >>> 0) + (counter++ + '__');
data && data.forEach && data.forEach(this.add, this);
};
WeakSet.prototype["add"] = function(obj) {
var name = this.name;
if (!obj[name]) Object.defineProperty(obj, name, {value: true, writable: true});
return this;
};
WeakSet.prototype["delete"] = function(obj) {
if (!obj[this.name]) return false;
obj[this.name] = undefined;
return true;
};
WeakSet.prototype["has"] = function(obj) {
return !!obj[this.name];
};
WeakSet.prototype.constructor = WeakSet;
WeakSet.name = "WeakSet";
global.WeakSet = WeakSet;
}(this)); | @license
Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt | (anonymous) ( global ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.25.1/WeakSet/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.25.1/WeakSet/raw.js | MIT |
return function lookupMatcher(availableLocales, requestedLocales) {
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 | lookupMatcher ( availableLocales , requestedLocales ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.96.0/Intl.RelativeTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.96.0/Intl.RelativeTimeFormat/raw.js | MIT |
function makePartsList(pattern, unit, parts) {
var e_1, _a, e_2, _b;
var patternParts = partitionPattern(pattern);
var result = [];
try {
for (var patternParts_1 = __values(patternParts), patternParts_1_1 = patternParts_1.next(); !patternParts_1_1.done; patternParts_1_1 = patternParts_1.next()) {
var patternPart = patternParts_1_1.value;
if (isLiteralPart(patternPart)) {
result.push({
type: 'literal',
value: patternPart.value,
});
}
else {
invariant(patternPart.type === '0', "Malformed pattern " + pattern);
try {
for (var parts_1 = (e_2 = void 0, __values(parts)), parts_1_1 = parts_1.next(); !parts_1_1.done; parts_1_1 = parts_1.next()) {
var part = parts_1_1.value;
result.push({
type: part.type,
value: part.value,
unit: unit,
});
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (parts_1_1 && !parts_1_1.done && (_b = parts_1.return)) _b.call(parts_1);
}
finally { if (e_2) throw e_2.error; }
}
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (patternParts_1_1 && !patternParts_1_1.done && (_a = patternParts_1.return)) _a.call(patternParts_1);
}
finally { if (e_1) throw e_1.error; }
}
return result;
} | https://tc39.es/proposal-intl-relative-time/#sec-makepartslist
@param pattern
@param unit
@param parts | makePartsList ( pattern , unit , parts ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.96.0/Intl.RelativeTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.96.0/Intl.RelativeTimeFormat/raw.js | MIT |
function formatNumericToString(internalSlots, x) {
var isNegative = x < 0 || objectIs(x, -0);
if (isNegative) {
x = -x;
}
var result;
var rourndingType = internalSlots.roundingType;
switch (rourndingType) {
case 'significantDigits':
result = toRawPrecision(x, internalSlots.minimumSignificantDigits, internalSlots.maximumSignificantDigits);
break;
case 'fractionDigits':
result = toRawFixed(x, internalSlots.minimumFractionDigits, internalSlots.maximumFractionDigits);
break;
default:
result = toRawPrecision(x, 1, 2);
if (result.integerDigitsCount > 1) {
result = toRawFixed(x, 0, 0);
}
break;
}
x = result.roundedNumber;
var string = result.formattedString;
var int = result.integerDigitsCount;
var minInteger = internalSlots.minimumIntegerDigits;
if (int < minInteger) {
var forwardZeros = repeat('0', minInteger - int);
string = forwardZeros + string;
}
if (isNegative) {
x = -x;
}
return { roundedNumber: x, formattedString: string };
} | https://tc39.es/ecma402/#sec-formatnumberstring
TODO: dedup with intl-pluralrules | formatNumericToString ( internalSlots , x ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.96.0/Intl.NumberFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.96.0/Intl.NumberFormat/raw.js | MIT |
function removeUnicodeExtensionFromLocale(canonicalLocale) {
var extensionIndex = canonicalLocale.indexOf('-u-');
return extensionIndex >= 0
? canonicalLocale.slice(0, extensionIndex)
: canonicalLocale;
} | Chop off the unicode extension from the locale string. | removeUnicodeExtensionFromLocale ( canonicalLocale ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.96.0/Intl.NumberFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.96.0/Intl.NumberFormat/raw.js | MIT |
function isUnitSupported(unit) {
try {
new Intl.NumberFormat(undefined, {
style: 'unit',
// @ts-ignore
unit: unit,
});
}
catch (e) {
return false;
}
return true;
} | Check if a formatting number with unit is supported
@public
@param unit unit to check | isUnitSupported ( unit ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.96.0/Intl.NumberFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.96.0/Intl.NumberFormat/raw.js | MIT |
(function() {
var defineProperty = Object.defineProperty;
var counter = Date.now() % 1e9;
var WeakMap = function WeakMap (data) {
this.name = '__st' + (Math.random() * 1e9 >>> 0) + (counter++ + '__');
// If data is iterable (indicated by presence of a forEach method), pre-populate the map
data && data.forEach && data.forEach(function (item) {
this.set.apply(this, item);
}, this);
};
WeakMap.prototype["set"] = function(key, value) {
if (typeof key !== 'object' && typeof key !== 'function')
throw new TypeError('Invalid value used as weak map key');
var entry = key[this.name];
if (entry && entry[0] === key)
entry[1] = value;
else
defineProperty(key, this.name, {value: [key, value], writable: true});
return this;
};
WeakMap.prototype["get"] = function(key) {
var entry;
return (entry = key[this.name]) && entry[0] === key ?
entry[1] : undefined;
};
WeakMap.prototype["delete"] = function(key) {
var entry = key[this.name];
if (!entry || entry[0] !== key) return false;
entry[0] = entry[1] = undefined;
return true;
};
WeakMap.prototype["has"] = function(key) {
var entry = key[this.name];
if (!entry) return false;
return entry[0] === key;
};
WeakMap.prototype.constructor = WeakMap;
WeakMap.name = "WeakMap";
this.WeakMap = WeakMap;
}()); | @license
Portions of this polyfill are a derivative work of the Polymer project, which requires the following licence notice:
Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt | (anonymous) ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.25.1/WeakMap/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.25.1/WeakMap/raw.js | MIT |
function hasUnthrownDateTimeStyleBug() {
try {
return !!new Intl.DateTimeFormat('en', {
dateStyle: 'short',
hour: 'numeric',
}).format(new Date(0));
}
catch (e) {
return false;
}
} | Node 14's version of Intl.DateTimeFormat does not throw
when dateStyle/timeStyle is used with other options.
This was fixed in newer V8 versions | hasUnthrownDateTimeStyleBug ( ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.103.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.103.0/Intl.DateTimeFormat/raw.js | MIT |
function isValidTimeZoneName(tz) {
var uppercasedTz = tz.toUpperCase();
var zoneNames = new Set(Object.keys(DateTimeFormat.tzData).map(function (z) { return z.toUpperCase(); }));
return zoneNames.has(uppercasedTz) || uppercasedTz in UPPERCASED_LINKS;
} | https://tc39.es/ecma402/#sec-isvalidtimezonename
@param tz | isValidTimeZoneName ( tz ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.96.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.96.0/Intl.DateTimeFormat/raw.js | MIT |
function initializeDateTimeFormat(dtf, locales, opts) {
// @ts-ignore
var requestedLocales = Intl.getCanonicalLocales(locales);
var options = toDateTimeOptions(opts, 'any', 'date');
var opt = Object.create(null);
var matcher = getOption(options, 'localeMatcher', 'string', ['lookup', 'best fit'], 'best fit');
opt.localeMatcher = matcher;
var calendar = getOption(options, 'calendar', 'string', undefined, undefined);
if (calendar !== undefined && !TYPE_REGEX.test(calendar)) {
throw new RangeError('Malformed calendar');
}
var internalSlots = getInternalSlots(dtf);
opt.ca = calendar;
var numberingSystem = getOption(options, 'numberingSystem', 'string', undefined, undefined);
if (numberingSystem !== undefined && !TYPE_REGEX.test(numberingSystem)) {
throw new RangeError('Malformed numbering system');
}
opt.nu = numberingSystem;
var hour12 = getOption(options, 'hour12', 'boolean', undefined, undefined);
var hourCycle = getOption(options, 'hourCycle', 'string', ['h11', 'h12', 'h23', 'h24'], undefined);
if (hour12 !== undefined) {
// @ts-ignore
hourCycle = null;
}
opt.hc = hourCycle;
var r = createResolveLocale(DateTimeFormat.getDefaultLocale)(DateTimeFormat.availableLocales, requestedLocales,
// TODO: Fix the type
opt,
// [[RelevantExtensionKeys]] slot, which is a constant
['nu', 'ca', 'hc'], DateTimeFormat.localeData);
internalSlots.locale = r.locale;
calendar = r.ca;
internalSlots.calendar = calendar;
internalSlots.hourCycle = r.hc;
internalSlots.numberingSystem = r.nu;
var dataLocale = r.dataLocale;
internalSlots.dataLocale = dataLocale;
var timeZone = options.timeZone;
if (timeZone !== undefined) {
timeZone = String(timeZone);
if (!isValidTimeZoneName(timeZone)) {
throw new RangeError('Invalid timeZoneName');
}
timeZone = canonicalizeTimeZoneName(timeZone);
}
else {
timeZone = DateTimeFormat.__defaultLocale;
}
internalSlots.timeZone = timeZone;
opt = Object.create(null);
opt.weekday = getOption(options, 'weekday', 'string', ['narrow', 'short', 'long'], undefined);
opt.era = getOption(options, 'era', 'string', ['narrow', 'short', 'long'], undefined);
opt.year = getOption(options, 'year', 'string', ['2-digit', 'numeric'], undefined);
opt.month = getOption(options, 'month', 'string', ['2-digit', 'numeric', 'narrow', 'short', 'long'], undefined);
opt.day = getOption(options, 'day', 'string', ['2-digit', 'numeric'], undefined);
opt.hour = getOption(options, 'hour', 'string', ['2-digit', 'numeric'], undefined);
opt.minute = getOption(options, 'minute', 'string', ['2-digit', 'numeric'], undefined);
opt.second = getOption(options, 'second', 'string', ['2-digit', 'numeric'], undefined);
opt.timeZoneName = getOption(options, 'timeZoneName', 'string', ['short', 'long'], undefined);
var dataLocaleData = DateTimeFormat.localeData[dataLocale];
var formats = dataLocaleData.formats[calendar];
matcher = getOption(options, 'formatMatcher', 'string', ['basic', 'best fit'], 'best fit');
var bestFormat;
if (matcher === 'basic') {
bestFormat = basicFormatMatcher(opt, formats);
}
else {
opt.hour12 =
internalSlots.hourCycle === 'h11' || internalSlots.hourCycle === 'h12';
bestFormat = bestFitFormatMatcher(opt, formats);
}
for (var prop in opt) {
var p = bestFormat[prop];
if (p !== undefined) {
internalSlots[prop] = p;
}
}
var pattern;
if (internalSlots.hour !== undefined) {
var hcDefault = dataLocaleData.hourCycle;
var hc = internalSlots.hourCycle;
if (hc == null) {
hc = hcDefault;
}
if (hour12 !== undefined) {
if (hour12) {
if (hcDefault === 'h11' || hcDefault === 'h23') {
hc = 'h11';
}
else {
hc = 'h12';
}
}
else {
invariant(!hour12, 'hour12 must not be set');
if (hcDefault === 'h11' || hcDefault === 'h23') {
hc = 'h23';
}
else {
hc = 'h24';
}
}
}
internalSlots.hourCycle = hc;
if (hc === 'h11' || hc === 'h12') {
pattern = bestFormat.pattern12;
}
else {
pattern = bestFormat.pattern;
}
}
else {
// @ts-ignore
internalSlots.hourCycle = undefined;
pattern = bestFormat.pattern;
}
internalSlots.pattern = pattern;
return dtf;
} | https://tc39.es/ecma402/#sec-initializedatetimeformat
@param dtf DateTimeFormat
@param locales locales
@param opts options | initializeDateTimeFormat ( dtf , locales , opts ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.96.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.96.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_2 = formats; _i < formats_2.length; _i++) {
var format = formats_2[_i];
var score = bestFitFormatMatcherScore(options, format);
if (score > bestScore) {
bestScore = score;
bestFormat = format;
}
}
bestFormat = __assign$1({}, bestFormat);
// Kinda following https://github.com/unicode-org/icu/blob/dd50e38f459d84e9bf1b0c618be8483d318458ad/icu4j/main/classes/core/src/com/ibm/icu/text/DateTimePatternGenerator.java
for (var prop in bestFormat) {
var bestValue = bestFormat[prop];
var inputValue = 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 (!inputValue) {
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(bestValue) &&
!isNumericType(inputValue)) {
continue;
}
// Otherwise use the input value
bestFormat[prop] = inputValue;
}
return bestFormat;
} | https://tc39.es/ecma402/#sec-bestfitformatmatcher
Just alias to basic for now
@param options
@param formats | bestFitFormatMatcher ( options , formats ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.96.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.96.0/Intl.DateTimeFormat/raw.js | MIT |
function formatDateTimeParts(dtf, x) {
return partitionDateTimePattern(dtf, x);
} | https://tc39.es/ecma402/#sec-formatdatetimetoparts
@param dtf DateTimeFormat
@param x | formatDateTimeParts ( dtf , x ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.96.0/Intl.DateTimeFormat/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.96.0/Intl.DateTimeFormat/raw.js | MIT |
function toRawPrecision(x, minPrecision, maxPrecision) {
var m = x.toPrecision(maxPrecision);
if (~m.indexOf('.') && maxPrecision > minPrecision) {
var cut = maxPrecision - minPrecision;
while (cut > 0 && m[m.length - 1] === '0') {
m = m.slice(0, m.length - 1);
cut--;
}
if (m[m.length - 1] === '.') {
return m.slice(0, m.length - 1);
}
}
return m;
} | https://tc39.es/ecma402/#sec-torawprecision
@param x
@param minPrecision
@param maxPrecision | toRawPrecision ( x , minPrecision , maxPrecision ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.96.0/Intl.PluralRules/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.96.0/Intl.PluralRules/raw.js | MIT |
function toRawFixed(x, minInteger, minFraction, maxFraction) {
var cut = maxFraction - minFraction;
var m = x.toFixed(maxFraction);
while (cut > 0 && m[m.length - 1] === '0') {
m = m.slice(0, m.length - 1);
cut--;
}
if (m[m.length - 1] === '.') {
m = m.slice(0, m.length - 1);
}
var int = m.split('.')[0].length;
if (int < minInteger) {
var z = '';
for (; z.length < minInteger - int; z += '0')
;
m = z + m;
}
return m;
} | https://tc39.es/ecma402/#sec-torawfixed
@param x
@param minInteger
@param minFraction
@param maxFraction | toRawFixed ( x , minInteger , minFraction , maxFraction ) | javascript | polyfillpolyfill/polyfill-service | polyfill-libraries/3.96.0/Intl.PluralRules/raw.js | https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.96.0/Intl.PluralRules/raw.js | MIT |
setFocalLength( focalLength ) {
/** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
this.updateProjectionMatrix();
} | Sets the FOV by focal length in respect to the current .filmGauge.
The default film gauge is 35, so that the focal length can be specified for
a 35mm (full frame) camera.
Values for focal length and film gauge must have the same unit. | setFocalLength ( focalLength ) | javascript | shadowcz007/comfyui-mixlab-nodes | webApp/lib/three/three.module.js | https://github.com/shadowcz007/comfyui-mixlab-nodes/blob/master/webApp/lib/three/three.module.js | MIT |
getFocalLength() {
const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
return 0.5 * this.getFilmHeight() / vExtentSlope;
} | Calculates the focal length from the current .fov and .filmGauge. | getFocalLength ( ) | javascript | shadowcz007/comfyui-mixlab-nodes | webApp/lib/three/three.module.js | https://github.com/shadowcz007/comfyui-mixlab-nodes/blob/master/webApp/lib/three/three.module.js | MIT |
getViewBounds( distance, minTarget, maxTarget ) {
_v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
_v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
} | Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle. | getViewBounds ( distance , minTarget , maxTarget ) | javascript | shadowcz007/comfyui-mixlab-nodes | webApp/lib/three/three.module.js | https://github.com/shadowcz007/comfyui-mixlab-nodes/blob/master/webApp/lib/three/three.module.js | MIT |
getViewSize( distance, target ) {
this.getViewBounds( distance, _minTarget, _maxTarget );
return target.subVectors( _maxTarget, _minTarget );
} | Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
Copies the result into the target Vector2, where x is width and y is height. | getViewSize ( distance , target ) | javascript | shadowcz007/comfyui-mixlab-nodes | webApp/lib/three/three.module.js | https://github.com/shadowcz007/comfyui-mixlab-nodes/blob/master/webApp/lib/three/three.module.js | MIT |
setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
this.aspect = fullWidth / fullHeight;
if ( this.view === null ) {
this.view = {
enabled: true,
fullWidth: 1,
fullHeight: 1,
offsetX: 0,
offsetY: 0,
width: 1,
height: 1
};
}
this.view.enabled = true;
this.view.fullWidth = fullWidth;
this.view.fullHeight = fullHeight;
this.view.offsetX = x;
this.view.offsetY = y;
this.view.width = width;
this.view.height = height;
this.updateProjectionMatrix();
} | Sets an offset in a larger frustum. This is useful for multi-window or
multi-monitor/multi-machine setups.
For example, if you have 3x2 monitors and each monitor is 1920x1080 and
the monitors are in grid like this
+---+---+---+
| A | B | C |
+---+---+---+
| D | E | F |
+---+---+---+
then for each monitor you would call it like this
const w = 1920;
const h = 1080;
const fullWidth = w * 3;
const fullHeight = h * 2;
--A--
camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
--B--
camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
--C--
camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
--D--
camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
--E--
camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
--F--
camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
Note there is no reason monitors have to be the same size or in a grid. | setViewOffset ( fullWidth , fullHeight , x , y , width , height ) | javascript | shadowcz007/comfyui-mixlab-nodes | webApp/lib/three/three.module.js | https://github.com/shadowcz007/comfyui-mixlab-nodes/blob/master/webApp/lib/three/three.module.js | MIT |
fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
_oldTarget = this._renderer.getRenderTarget();
_oldActiveCubeFace = this._renderer.getActiveCubeFace();
_oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
_oldXrEnabled = this._renderer.xr.enabled;
this._renderer.xr.enabled = false;
this._setSize( 256 );
const cubeUVRenderTarget = this._allocateTargets();
cubeUVRenderTarget.depthBuffer = true;
this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
if ( sigma > 0 ) {
this._blur( cubeUVRenderTarget, 0, 0, sigma );
}
this._applyPMREM( cubeUVRenderTarget );
this._cleanup( cubeUVRenderTarget );
return cubeUVRenderTarget;
} | Generates a PMREM from a supplied Scene, which can be faster than using an
image if networking bandwidth is low. Optional sigma specifies a blur radius
in radians to be applied to the scene before PMREM generation. Optional near
and far planes ensure the scene is rendered in its entirety (the cubeCamera
is placed at the origin). | fromScene ( scene , sigma = 0 , near = 0 . 1 , far = 100 ) | javascript | shadowcz007/comfyui-mixlab-nodes | webApp/lib/three/three.module.js | https://github.com/shadowcz007/comfyui-mixlab-nodes/blob/master/webApp/lib/three/three.module.js | MIT |
fromEquirectangular( equirectangular, renderTarget = null ) {
return this._fromTexture( equirectangular, renderTarget );
} | Generates a PMREM from an equirectangular texture, which can be either LDR
or HDR. The ideal input image size is 1k (1024 x 512),
as this matches best with the 256 x 256 cubemap output.
The smallest supported equirectangular image size is 64 x 32. | fromEquirectangular ( equirectangular , renderTarget = null ) | javascript | shadowcz007/comfyui-mixlab-nodes | webApp/lib/three/three.module.js | https://github.com/shadowcz007/comfyui-mixlab-nodes/blob/master/webApp/lib/three/three.module.js | MIT |
fromCubemap( cubemap, renderTarget = null ) {
return this._fromTexture( cubemap, renderTarget );
} | Generates a PMREM from an cubemap texture, which can be either LDR
or HDR. The ideal input cube size is 256 x 256,
as this matches best with the 256 x 256 cubemap output.
The smallest supported cube size is 16 x 16. | fromCubemap ( cubemap , renderTarget = null ) | javascript | shadowcz007/comfyui-mixlab-nodes | webApp/lib/three/three.module.js | https://github.com/shadowcz007/comfyui-mixlab-nodes/blob/master/webApp/lib/three/three.module.js | MIT |
compileCubemapShader() {
if ( this._cubemapMaterial === null ) {
this._cubemapMaterial = _getCubemapMaterial();
this._compileMaterial( this._cubemapMaterial );
}
} | Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
your texture's network fetch for increased concurrency. | compileCubemapShader ( ) | javascript | shadowcz007/comfyui-mixlab-nodes | webApp/lib/three/three.module.js | https://github.com/shadowcz007/comfyui-mixlab-nodes/blob/master/webApp/lib/three/three.module.js | MIT |
compileEquirectangularShader() {
if ( this._equirectMaterial === null ) {
this._equirectMaterial = _getEquirectMaterial();
this._compileMaterial( this._equirectMaterial );
}
} | Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
your texture's network fetch for increased concurrency. | compileEquirectangularShader ( ) | javascript | shadowcz007/comfyui-mixlab-nodes | webApp/lib/three/three.module.js | https://github.com/shadowcz007/comfyui-mixlab-nodes/blob/master/webApp/lib/three/three.module.js | MIT |
dispose() {
this._dispose();
if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
} | Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
one of them will cause any others to also become unusable. | dispose ( ) | javascript | shadowcz007/comfyui-mixlab-nodes | webApp/lib/three/three.module.js | https://github.com/shadowcz007/comfyui-mixlab-nodes/blob/master/webApp/lib/three/three.module.js | MIT |
async getSystemStats() {
const res = await this.fetchApi("/system_stats");
return await res.json();
} | Gets system & device stats
@returns System stats such as python version, OS, per device info | getSystemStats ( ) | javascript | shadowcz007/comfyui-mixlab-nodes | webApp/javascript/api.js | https://github.com/shadowcz007/comfyui-mixlab-nodes/blob/master/webApp/javascript/api.js | MIT |
async getSetting(id) {
return (await this.fetchApi(`/settings/${encodeURIComponent(id)}`)).json();
} | Gets a setting for the current user
@param { string } id The id of the setting to fetch
@returns { Promise<unknown> } The setting value | getSetting ( id ) | javascript | shadowcz007/comfyui-mixlab-nodes | webApp/javascript/api.js | https://github.com/shadowcz007/comfyui-mixlab-nodes/blob/master/webApp/javascript/api.js | MIT |
async getUserData(file, options) {
return this.fetchApi(`/userdata/${encodeURIComponent(file)}`, options);
} | Gets a user data file for the current user
@param { string } file The name of the userdata file to load
@param { RequestInit } [options]
@returns { Promise<Response> } The fetch response object | getUserData ( file , options ) | javascript | shadowcz007/comfyui-mixlab-nodes | webApp/javascript/api.js | https://github.com/shadowcz007/comfyui-mixlab-nodes/blob/master/webApp/javascript/api.js | MIT |
export function createDocument(html) {
const document = /** @type {HTMLDocument} */ (parseDocument(html, {decodeEntities: false}));
defineProperties(document, DocumentExtensions);
// Extend Element.prototype with DOM manipulation methods.
defineProperties(Element.prototype, ElementExtensions);
// Critters container is the viewport to evaluate critical CSS
let crittersContainer = document.querySelector('[data-critters-container]');
if (!crittersContainer) {
document.documentElement.setAttribute('data-critters-container', '');
crittersContainer = document.documentElement;
}
document.crittersContainer = crittersContainer;
buildCache(crittersContainer);
return document;
} | Parse HTML into a mutable, serializable DOM Document.
The DOM implementation is an htmlparser2 DOM enhanced with basic DOM mutation methods.
@param {String} html HTML to parse into a Document instance | createDocument ( html ) | javascript | GoogleChromeLabs/critters | packages/critters/src/dom.js | https://github.com/GoogleChromeLabs/critters/blob/master/packages/critters/src/dom.js | Apache-2.0 |
export function serializeDocument(document) {
return render(document, { decodeEntities: false });
} | Serialize a Document to an HTML String
@param {HTMLDocument} document A Document, such as one created via `createDocument()` | serializeDocument ( document ) | javascript | GoogleChromeLabs/critters | packages/critters/src/dom.js | https://github.com/GoogleChromeLabs/critters/blob/master/packages/critters/src/dom.js | Apache-2.0 |
function reflectedProperty(attributeName) {
return {
get() {
return this.getAttribute(attributeName);
},
set(value) {
this.setAttribute(attributeName, value);
}
};
} | Create a property descriptor defining a getter/setter pair alias for a named attribute.
@private | reflectedProperty ( attributeName ) | javascript | GoogleChromeLabs/critters | packages/critters/src/dom.js | https://github.com/GoogleChromeLabs/critters/blob/master/packages/critters/src/dom.js | Apache-2.0 |
function defineProperties(obj, properties) {
for (const i in properties) {
const value = properties[i];
Object.defineProperty(
obj,
i,
typeof value === 'function' ? { value } : value
);
}
}
/**
* Create a property descriptor defining a getter/setter pair alias for a named attribute.
* @private
*/
function reflectedProperty(attributeName) {
return {
get() {
return this.getAttribute(attributeName);
},
set(value) {
this.setAttribute(attributeName, value);
}
};
}
function cachedQuerySelector(sel, node) { | Essentially `Object.defineProperties()`, except function values are assigned as value descriptors for convenience.
@private | defineProperties ( obj , properties ) | javascript | GoogleChromeLabs/critters | packages/critters/src/dom.js | https://github.com/GoogleChromeLabs/critters/blob/master/packages/critters/src/dom.js | Apache-2.0 |
export function parseStylesheet(stylesheet) {
return parse(stylesheet);
} | Parse a textual CSS Stylesheet into a Stylesheet instance.
Stylesheet is a mutable postcss AST with format similar to CSSOM.
@see https://github.com/postcss/postcss/
@private
@param {String} stylesheet
@returns {css.Stylesheet} ast | parseStylesheet ( stylesheet ) | javascript | GoogleChromeLabs/critters | packages/critters/src/css.js | https://github.com/GoogleChromeLabs/critters/blob/master/packages/critters/src/css.js | Apache-2.0 |
export function serializeStylesheet(ast, options) {
let cssStr = '';
stringify(ast, (result, node, type) => {
if (node?.type === 'decl' && node.value.includes('</style>')) {
return;
}
if (!options.compress) {
cssStr += result;
return;
}
// Simple minification logic
if (node?.type === 'comment') return;
if (node?.type === 'decl') {
const prefix = node.prop + node.raws.between;
cssStr += result.replace(prefix, prefix.trim());
return;
}
if (type === 'start') {
if (node.type === 'rule' && node.selectors) {
cssStr += node.selectors.join(',') + '{';
} else {
cssStr += result.replace(/\s\{$/, '{');
}
return;
}
if (type === 'end' && result === '}' && node?.raws?.semicolon) {
cssStr = cssStr.slice(0, -1);
}
cssStr += result.trim();
});
return cssStr;
} | Serialize a postcss Stylesheet to a String of CSS.
@private
@param {css.Stylesheet} ast A Stylesheet to serialize, such as one returned from `parseStylesheet()`
@param {Object} options Options used by the stringify logic
@param {Boolean} [options.compress] Compress CSS output (removes comments, whitespace, etc) | serializeStylesheet ( ast , options ) | javascript | GoogleChromeLabs/critters | packages/critters/src/css.js | https://github.com/GoogleChromeLabs/critters/blob/master/packages/critters/src/css.js | Apache-2.0 |
export function markOnly(predicate) {
return (rule) => {
const sel = rule.selectors;
if (predicate(rule) === false) {
rule.$$remove = true;
}
rule.$$markedSelectors = rule.selectors;
if (rule._other) {
rule._other.$$markedSelectors = rule._other.selectors;
}
rule.selectors = sel;
};
} | Converts a walkStyleRules() iterator to mark nodes with `.$$remove=true` instead of actually removing them.
This means they can be removed in a second pass, allowing the first pass to be nondestructive (eg: to preserve mirrored sheets).
@private
@param {Function} iterator Invoked on each node in the tree. Return `false` to remove that node.
@returns {(rule) => void} nonDestructiveIterator | markOnly ( predicate ) | javascript | GoogleChromeLabs/critters | packages/critters/src/css.js | https://github.com/GoogleChromeLabs/critters/blob/master/packages/critters/src/css.js | Apache-2.0 |
export function applyMarkedSelectors(rule) {
if (rule.$$markedSelectors) {
rule.selectors = rule.$$markedSelectors;
}
if (rule._other) {
applyMarkedSelectors(rule._other);
}
} | Apply filtered selectors to a rule from a previous markOnly run.
@private
@param {css.Rule} rule The Rule to apply marked selectors to (if they exist). | applyMarkedSelectors ( rule ) | javascript | GoogleChromeLabs/critters | packages/critters/src/css.js | https://github.com/GoogleChromeLabs/critters/blob/master/packages/critters/src/css.js | Apache-2.0 |
export function walkStyleRules(node, iterator) {
node.nodes = node.nodes.filter((rule) => {
if (hasNestedRules(rule)) {
walkStyleRules(rule, iterator);
}
rule._other = undefined;
rule.filterSelectors = filterSelectors;
return iterator(rule) !== false;
});
} | Recursively walk all rules in a stylesheet.
@private
@param {css.Rule} node A Stylesheet or Rule to descend into.
@param {Function} iterator Invoked on each node in the tree. Return `false` to remove that node. | walkStyleRules ( node , iterator ) | javascript | GoogleChromeLabs/critters | packages/critters/src/css.js | https://github.com/GoogleChromeLabs/critters/blob/master/packages/critters/src/css.js | Apache-2.0 |
export function walkStyleRulesWithReverseMirror(node, node2, iterator) {
if (node2 === null) return walkStyleRules(node, iterator);
[node.nodes, node2.nodes] = splitFilter(
node.nodes,
node2.nodes,
(rule, index, rules, rules2) => {
const rule2 = rules2[index];
if (hasNestedRules(rule)) {
walkStyleRulesWithReverseMirror(rule, rule2, iterator);
}
rule._other = rule2;
rule.filterSelectors = filterSelectors;
return iterator(rule) !== false;
}
);
} | Recursively walk all rules in two identical stylesheets, filtering nodes into one or the other based on a predicate.
@private
@param {css.Rule} node A Stylesheet or Rule to descend into.
@param {css.Rule} node2 A second tree identical to `node`
@param {Function} iterator Invoked on each node in the tree. Return `false` to remove that node from the first tree, true to remove it from the second. | walkStyleRulesWithReverseMirror ( node , node2 , iterator ) | javascript | GoogleChromeLabs/critters | packages/critters/src/css.js | https://github.com/GoogleChromeLabs/critters/blob/master/packages/critters/src/css.js | Apache-2.0 |
export function validateMediaQuery(query) {
// The below is needed for consumption with webpack.
const mediaParserFn = 'default' in mediaParser ? mediaParser.default : mediaParser;
const mediaTree = mediaParserFn(query);
const nodeTypes = new Set(['media-type', 'keyword', 'media-feature']);
const stack = [mediaTree];
while (stack.length > 0) {
const node = stack.pop();
if (nodeTypes.has(node.type) && !validateMediaType(node)) {
return false;
}
if (node.nodes) {
stack.push(...node.nodes);
}
}
return true;
} | @param {string} Media query to validate
@returns {boolean}
This function performs a basic media query validation
to ensure the values passed as part of the 'media' config
is HTML safe and does not cause any injection issue | validateMediaQuery ( query ) | javascript | GoogleChromeLabs/critters | packages/critters/src/css.js | https://github.com/GoogleChromeLabs/critters/blob/master/packages/critters/src/css.js | Apache-2.0 |
async process(html) {
const start = Date.now();
// Parse the generated HTML in a DOM we can mutate
const document = createDocument(html);
if (this.options.additionalStylesheets.length > 0) {
this.embedAdditionalStylesheet(document);
}
// `external:false` skips processing of external sheets
if (this.options.external !== false) {
const externalSheets = [].slice.call(
document.querySelectorAll('link[rel="stylesheet"]')
);
await Promise.all(
externalSheets.map((link) => this.embedLinkedStylesheet(link, document))
);
}
// go through all the style tags in the document and reduce them to only critical CSS
const styles = this.getAffectedStyleTags(document);
await Promise.all(
styles.map((style) => this.processStyle(style, document))
);
if (this.options.mergeStylesheets !== false && styles.length !== 0) {
await this.mergeStylesheets(document);
}
// serialize the document back to HTML and we're done
const output = serializeDocument(document);
const end = Date.now();
this.logger.info(`Time ${end - start}ms`);
return output;
} | Apply critical CSS processing to the html | process ( html ) | javascript | GoogleChromeLabs/critters | packages/critters/src/index.js | https://github.com/GoogleChromeLabs/critters/blob/master/packages/critters/src/index.js | Apache-2.0 |
getAffectedStyleTags(document) {
const styles = [...document.querySelectorAll('style')];
// `inline:false` skips processing of inline stylesheets
if (this.options.reduceInlineStyles === false) {
return styles.filter((style) => style.$$external);
}
return styles;
} | Get the style tags that need processing | getAffectedStyleTags ( document ) | javascript | GoogleChromeLabs/critters | packages/critters/src/index.js | https://github.com/GoogleChromeLabs/critters/blob/master/packages/critters/src/index.js | Apache-2.0 |
async embedAdditionalStylesheet(document) {
const styleSheetsIncluded = [];
const sources = await Promise.all(
this.options.additionalStylesheets.map((cssFile) => {
if (styleSheetsIncluded.includes(cssFile)) {
return;
}
styleSheetsIncluded.push(cssFile);
const style = document.createElement('style');
style.$$external = true;
return this.getCssAsset(cssFile, style).then((sheet) => [sheet, style]);
})
);
sources.forEach(([sheet, style]) => {
if (!sheet) return;
style.textContent = sheet;
document.head.appendChild(style);
});
} | Inline the stylesheets from options.additionalStylesheets (assuming it passes `options.filter`) | embedAdditionalStylesheet ( document ) | javascript | GoogleChromeLabs/critters | packages/critters/src/index.js | https://github.com/GoogleChromeLabs/critters/blob/master/packages/critters/src/index.js | Apache-2.0 |
async embedLinkedStylesheet(link, document) {
const href = link.getAttribute('href');
let media = link.getAttribute('media');
if (media && !validateMediaQuery(media)) {
media = undefined;
}
const preloadMode = this.options.preload;
// skip filtered resources, or network resources if no filter is provided
if (this.urlFilter ? this.urlFilter(href) : !href?.endsWith('.css')) {
return undefined;
}
// the reduced critical CSS gets injected into a new <style> tag
const style = document.createElement('style');
style.$$external = true;
const sheet = await this.getCssAsset(href, style);
if (!sheet) {
return;
}
style.textContent = sheet;
style.$$name = href;
style.$$links = [link];
link.parentNode.insertBefore(style, link);
if (this.checkInlineThreshold(link, style, sheet)) {
return;
}
// CSS loader is only injected for the first sheet, then this becomes an empty string
let cssLoaderPreamble =
"function $loadcss(u,m,l){(l=document.createElement('link')).rel='stylesheet';l.href=u;document.head.appendChild(l)}";
const lazy = preloadMode === 'js-lazy';
if (lazy) {
cssLoaderPreamble = cssLoaderPreamble.replace(
'l.href',
"l.media='print';l.onload=function(){l.media=m};l.href"
);
}
// Allow disabling any mutation of the stylesheet link:
if (preloadMode === false) return;
let noscriptFallback = false;
let updateLinkToPreload = false;
const noscriptLink = link.cloneNode(false);
if (preloadMode === 'body') {
document.body.appendChild(link);
} else {
if (preloadMode === 'js' || preloadMode === 'js-lazy') {
const script = document.createElement('script');
script.setAttribute('data-href', href);
script.setAttribute('data-media', media || 'all');
const js = `${cssLoaderPreamble}$loadcss(document.currentScript.dataset.href,document.currentScript.dataset.media)`;
// script.appendChild(document.createTextNode(js));
script.textContent = js;
link.parentNode.insertBefore(script, link.nextSibling);
style.$$links.push(script);
cssLoaderPreamble = '';
noscriptFallback = true;
updateLinkToPreload = true;
} else if (preloadMode === 'media') {
// @see https://github.com/filamentgroup/loadCSS/blob/af1106cfe0bf70147e22185afa7ead96c01dec48/src/loadCSS.js#L26
link.setAttribute('media', 'print');
link.setAttribute('onload', `this.media='${media || 'all'}'`);
noscriptFallback = true;
} else if (preloadMode === 'swap-high') {
// @see http://filamentgroup.github.io/loadCSS/test/new-high.html
link.setAttribute('rel', 'alternate stylesheet preload');
link.setAttribute('title', 'styles');
link.setAttribute('onload', `this.title='';this.rel='stylesheet'`);
noscriptFallback = true;
} else if (preloadMode === 'swap') {
link.setAttribute('onload', "this.rel='stylesheet'");
noscriptFallback = true;
} else {
const bodyLink = link.cloneNode(false);
// If an ID is present, remove it to avoid collisions.
bodyLink.removeAttribute('id');
document.body.appendChild(bodyLink);
updateLinkToPreload = true;
}
}
if (
this.options.noscriptFallback !== false &&
noscriptFallback &&
// Don't parse the URL if it contains </noscript> as it might cause unexpected behavior
!href.includes('</noscript>')
) {
const noscript = document.createElement('noscript');
// If an ID is present, remove it to avoid collisions.
noscriptLink.removeAttribute('id');
noscript.appendChild(noscriptLink);
link.parentNode.insertBefore(noscript, link.nextSibling);
style.$$links.push(noscript);
}
if (updateLinkToPreload) {
// Switch the current link tag to preload
link.setAttribute('rel', 'preload');
link.setAttribute('as', 'style');
}
} | Inline the target stylesheet referred to by a <link rel="stylesheet"> (assuming it passes `options.filter`) | embedLinkedStylesheet ( link , document ) | javascript | GoogleChromeLabs/critters | packages/critters/src/index.js | https://github.com/GoogleChromeLabs/critters/blob/master/packages/critters/src/index.js | Apache-2.0 |
async processStyle(style, document) {
if (style.$$reduce === false) return;
const name = style.$$name ? style.$$name.replace(/^\//, '') : 'inline CSS';
const options = this.options;
const crittersContainer = document.crittersContainer;
let keyframesMode = options.keyframes || 'critical';
// we also accept a boolean value for options.keyframes
if (keyframesMode === true) keyframesMode = 'all';
if (keyframesMode === false) keyframesMode = 'none';
let sheet = style.textContent;
// store a reference to the previous serialized stylesheet for reporting stats
const before = sheet;
// Skip empty stylesheets
if (!sheet) return;
const ast = parseStylesheet(sheet);
const astInverse = options.pruneSource ? parseStylesheet(sheet) : null;
// a string to search for font names (very loose)
let criticalFonts = '';
const failedSelectors = [];
const criticalKeyframeNames = new Set();
let includeNext = false;
let includeAll = false;
let excludeNext = false;
let excludeAll = false;
const shouldPreloadFonts =
options.fonts === true || options.preloadFonts === true;
const shouldInlineFonts =
options.fonts !== false && options.inlineFonts === true;
// Walk all CSS rules, marking unused rules with `.$$remove=true` for removal in the second pass.
// This first pass is also used to collect font and keyframe usage used in the second pass.
walkStyleRules(
ast,
markOnly((rule) => {
if (rule.type === 'comment') {
// we might want to remove a leading ! on comment blocks
// critters can be part of "legal comments" which aren't striped on build
const crittersComment = rule.text.match(/^(?<!\! )critters:(.*)/);
const command = crittersComment && crittersComment[1];
if (command) {
switch (command) {
case 'include':
includeNext = true;
break;
case 'exclude':
excludeNext = true;
break;
case 'include start':
includeAll = true;
break;
case 'include end':
includeAll = false;
break;
case 'exclude start':
excludeAll = true;
break;
case 'exclude end':
excludeAll = false;
break;
}
}
} | Parse the stylesheet within a <style> element, then reduce it to contain only rules used by the document. | processStyle ( style , document ) | javascript | GoogleChromeLabs/critters | packages/critters/src/index.js | https://github.com/GoogleChromeLabs/critters/blob/master/packages/critters/src/index.js | Apache-2.0 |
async function exists(/** @type {string} */ filepath) {
return fs
.stat(filepath)
.then(() => {
return true
})
.catch((/** @type {NodeJS.ErrnoException} */ err) => {
if (err instanceof Error && err.code === 'ENOENT') {
return false
} else {
throw err
}
})
} | @typedef {Object} DataFile
@property {Buffer} buffer
@property {string} text
@property {Record<PropertyKey, unknown>} json
@property {string} name
@property {string} path
@typedef {Object} SchemaFile
@property {Buffer} buffer
@property {string} text
@property {JsonSchema} json
@property {string} name
@property {string} path | exists ( filepath ) | javascript | SchemaStore/schemastore | cli.js | https://github.com/SchemaStore/schemastore/blob/master/cli.js | Apache-2.0 |
function printErrorAndExit(error, messages, extraText) {
if (Array.isArray(messages) && messages.length > 0) {
console.warn('---')
for (const msg of messages) {
console.error(chalk.red('>>') + ' ' + msg)
}
}
if (extraText) {
process.stderr.write(extraText)
process.stderr.write('\n')
}
console.warn('---')
if (error instanceof Error && error?.stack) {
process.stderr.write(error.stack)
}
process.exit(1)
} | @param {unknown} error
@param {string[]} [messages]
@param {string} [extraText]
@returns {never} | printErrorAndExit ( error , messages , extraText ) | javascript | SchemaStore/schemastore | cli.js | https://github.com/SchemaStore/schemastore/blob/master/cli.js | Apache-2.0 |
async function ajvFactory(
/** @type {AjvFactoryOptions} */ {
draftVersion,
fullStrictMode = true,
unknownFormats = [],
unknownKeywords = [],
unknownSchemas = [],
options,
},
) {
let ajvOptions = {}
Object.assign(
ajvOptions,
fullStrictMode
? {
strict: true,
}
: {
strictTypes: false, // recommended: true
strictTuples: false, // recommended: true
allowMatchingProperties: true, // recommended: false
},
)
Object.assign(ajvOptions, options)
let ajv
switch (draftVersion) {
case 'draft-04':
ajv = new AjvDraft04(ajvOptions)
addFormats(ajv)
break
case 'draft-06':
ajv = new AjvDraft06And07(ajvOptions)
ajv.addMetaSchema(AjvDraft06SchemaJson)
addFormats(ajv)
break
case 'draft-07':
/**
* Note that draft-07 defines iri{,-reference}, idn-{hostname,email}, which
* are not available through `addFormats`. So, use `ajvFormatsDraft2019` to
* obtain these. Thus, some draft2019 formats like "duration" are applied.
* See https://ajv.js.org/packages/ajv-formats.html for details.
*/
ajv = new AjvDraft06And07(ajvOptions)
addFormats(ajv)
ajvFormatsDraft2019(ajv)
break
case '2019-09':
ajv = new Ajv2019(ajvOptions)
addFormats(ajv)
ajvFormatsDraft2019(ajv)
break
case '2020-12':
ajv = new Ajv2020(ajvOptions)
addFormats(ajv)
ajvFormatsDraft2019(ajv)
break
default:
throw new Error('No JSON Schema version specified')
}
/**
* In strict mode, Ajv will throw an error if it does not
* recognize any non-standard formats. That is, unrecognized
* values of the "format" field. Supply this information to
* Ajv to prevent errors.
*/
for (const format of unknownFormats) {
ajv.addFormat(format, true)
}
/**
* Ditto, but with keywords (ex. "x-intellij-html-description")..
*/
for (const unknownKeyword of unknownKeywords.concat([
'allowTrailingCommas',
'defaultSnippets',
'markdownDescription',
'enumDescriptions',
'markdownEnumDescriptions',
'x-taplo',
'x-taplo-info',
'x-tombi-toml-version',
'x-tombi-array-values-order',
'x-tombi-table-keys-order',
'x-intellij-language-injection',
'x-intellij-html-description',
'x-intellij-enum-metadata',
])) {
ajv.addKeyword(unknownKeyword)
}
/**
* Ditto, but with "$ref" URIs to external schemas.
*/
for (const schemaPath of unknownSchemas) {
ajv.addSchema(await readJsonFile(schemaPath))
}
return ajv
} | Returns the correct and configured Ajv instance for a particular $schema version | ajvFactory ( { draftVersion , fullStrictMode = true , unknownFormats = [ ] , unknownKeywords = [ ] , unknownSchemas = [ ] , options , } , ) | javascript | SchemaStore/schemastore | cli.js | https://github.com/SchemaStore/schemastore/blob/master/cli.js | Apache-2.0 |
function printSchemaValidationErrorAndExit(
filepath,
schemaFilepath,
ajvErrors,
) {
printErrorAndExit(
null,
[
`Failed to validate file "${filepath}" against schema file "./${schemaFilepath}"`,
`Showing first error out of ${ajvErrors?.length ?? '?'} total error(s)`,
],
util.formatWithOptions({ colors: true }, '%O', ajvErrors?.[0] ?? '???'),
)
} | @param {string} filepath
@param {string} schemaFilepath
@param {unknown[] | null | undefined} ajvErrors
@returns {never} | printSchemaValidationErrorAndExit ( filepath , schemaFilepath , ajvErrors , ) | javascript | SchemaStore/schemastore | cli.js | https://github.com/SchemaStore/schemastore/blob/master/cli.js | Apache-2.0 |
async function onSchemaFile(/** @type {SchemaFile} */ schema) {
const schemaDialectVersionIndex = SchemaDialects.findIndex(
(schemaDialect) => {
return schema.json.$schema === schemaDialect.url
},
)
// Test each schema version in a while loop.
let validates = false
let recommendedIndex = schemaDialectVersionIndex
let versionIndexToBeTested = schemaDialectVersionIndex
do {
// Attempt to use the next lower schema version.
versionIndexToBeTested++
const schemaDialectToBeTested = SchemaDialects[versionIndexToBeTested]
if (!schemaDialectToBeTested.isActive) {
break
}
const options = getSchemaOptions(schema.name)
const ajv = await ajvFactory({
draftVersion: schemaDialectToBeTested.draftVersion,
fullStrictMode: false,
unknownFormats: options.unknownFormats,
unknownKeywords: options.unknownKeywords,
unknownSchemas: options.unknownSchemas,
})
schema.json.$schema = schemaDialectToBeTested.url
try {
ajv.compile(schema.json)
validates = true
} catch {
validates = false
}
// It passes the test. So this is the new recommended index
if (validates) {
recommendedIndex = versionIndexToBeTested
}
// Continue until the validation process fails.
} while (validates)
// If found a different schema version that also works.
if (recommendedIndex !== schemaDialectVersionIndex) {
const original = SchemaDialects[schemaDialectVersionIndex].draftVersion
const recommended = SchemaDialects[recommendedIndex].draftVersion
console.info(
`Schema "${schema.name}" (${original}) can likely be downgraded to "${recommended}"`,
)
}
} | There are no positive or negative test processes here. Only the
schema files are | onSchemaFile ( schema ) | javascript | SchemaStore/schemastore | cli.js | https://github.com/SchemaStore/schemastore/blob/master/cli.js | Apache-2.0 |
loadVariables() {
return new Promise((resolve, reject) => {
const checkpointLoader =
new CheckpointLoader(GOOGLE_CLOUD_STORAGE_DIR + 'squeezenet1_1/');
checkpointLoader.getAllVariables().then(variables => {
this.variables = variables;
resolve();
});
});
} | Loads necessary variables for SqueezeNet. Resolves the promise when the
variables have all been loaded. | loadVariables ( ) | javascript | googlecreativelab/teachable-machine-v1 | src/ai/squeezenet.js | https://github.com/googlecreativelab/teachable-machine-v1/blob/master/src/ai/squeezenet.js | Apache-2.0 |
preprocessColorTextureToArray3D(rgbTexture, imageDimensions) {
const preprocessResultShapeRC =
[imageDimensions[0], imageDimensions[0] * 3];
const preprocessResultTexture =
this.math.getTextureManager().acquireTexture(preprocessResultShapeRC);
imagenet_util.preprocessInput(
this.gpgpu, this.preprocessInputShader, rgbTexture,
preprocessResultTexture, preprocessResultShapeRC);
return NDArray.make([imageDimensions[0], imageDimensions[0], 3], {
texture: preprocessResultTexture,
textureShapeRC: preprocessResultShapeRC
});
} | Preprocess an RGB color texture before inferring through squeezenet.
@param rgbTexture The RGB color texture to process into an Array3D.
@param imageDimensions The 2D dimensions of the image. | preprocessColorTextureToArray3D ( rgbTexture , imageDimensions ) | javascript | googlecreativelab/teachable-machine-v1 | src/ai/squeezenet.js | https://github.com/googlecreativelab/teachable-machine-v1/blob/master/src/ai/squeezenet.js | Apache-2.0 |
infer(preprocessedInput) {
const namedActivations = {};
const avgpool10 = this.math.scope((keep) => {
const conv1 = this.math.conv2d(
preprocessedInput, this.variables['conv1_W:0'],
this.variables['conv1_b:0'], 2, 0);
const conv1relu = keep(this.math.relu(conv1));
namedActivations['conv_1'] = conv1relu;
const pool1 = keep(this.math.maxPool(conv1relu, 3, 2, 0));
namedActivations['maxpool_1'] = pool1;
const fire2 = keep(this.fireModule(pool1, 2));
namedActivations['fire2'] = fire2;
const fire3 = keep(this.fireModule(fire2, 3));
namedActivations['fire3'] = fire3;
// Because we don't have uneven padding yet, manually pad the ndarray on
// the right.
const fire3Reshape2d =
fire3.as2D(fire3.shape[0], fire3.shape[1] * fire3.shape[2]);
const fire3Sliced2d = this.math.slice2D(
fire3Reshape2d, [0, 0],
[fire3.shape[0] - 1, (fire3.shape[1] - 1) * fire3.shape[2]]);
const fire3Sliced = fire3Sliced2d.as3D(
fire3.shape[0] - 1, fire3.shape[1] - 1, fire3.shape[2]);
const pool2 = keep(this.math.maxPool(fire3Sliced, 3, 2, 0));
namedActivations['maxpool_2'] = pool2;
const fire4 = keep(this.fireModule(pool2, 4));
namedActivations['fire4'] = fire4;
const fire5 = keep(this.fireModule(fire4, 5));
namedActivations['fire5'] = fire5;
const pool3 = keep(this.math.maxPool(fire5, 3, 2, 0));
namedActivations['maxpool_3'] = pool3;
const fire6 = keep(this.fireModule(pool3, 6));
namedActivations['fire6'] = fire6;
const fire7 = keep(this.fireModule(fire6, 7));
namedActivations['fire7'] = fire7;
const fire8 = keep(this.fireModule(fire7, 8));
namedActivations['fire8'] = fire8;
const fire9 = keep(this.fireModule(fire8, 9));
namedActivations['fire9'] = fire9;
const conv10 = keep(this.math.conv2d(
fire9, this.variables['conv10_W:0'],
this.variables['conv10_b:0'], 1, 0));
namedActivations['conv10'] = conv10;
return this.math.avgPool(conv10, conv10.shape[0], 1, 0).as1D();
});
return {namedActivations, logits: avgpool10};
} | Infer through SqueezeNet, assumes variables have been loaded. This does
standard ImageNet pre-processing before inferring through the model. This
method returns named activations as well as pre-softmax logits. The user
needs to clean up namedActivations after inferring.
@param preprocessedInput preprocessed input Array.
@return Named activations and the pre-softmax logits. | infer ( preprocessedInput ) | javascript | googlecreativelab/teachable-machine-v1 | src/ai/squeezenet.js | https://github.com/googlecreativelab/teachable-machine-v1/blob/master/src/ai/squeezenet.js | Apache-2.0 |
async predict(image) {
const imgFromPixels = tf.fromPixels(image);
const logits = this.mobilenetModule.infer(imgFromPixels, 'conv_preds');
const response = await this.classifier.predictClass(logits);
const newOutput = {
classIndex: this.mappedButtonIndexes[response.classIndex],
confidences: {
0: 0,
1: 0,
2: 0
}
};
this.mappedButtonIndexes.forEach((index, count) => {
newOutput.confidences[index] = response.confidences[count];
});
return newOutput;
} | There is an issue with mobilenetModule/knnClassifier where
it returns -1 if you don't start with an index of zero
In these train/predict methods, we remap the index of 0-2.
This way you can train the third model and have it retain
the index of 2.
We have these super verbosely named functions
so it's clear what's happening | predict ( image ) | javascript | googlecreativelab/teachable-machine-v1 | src/ai/WebcamClassifier.js | https://github.com/googlecreativelab/teachable-machine-v1/blob/master/src/ai/WebcamClassifier.js | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.