@angular/animations
Version:
Angular - animations integration with web-animations
1,168 lines (1,159 loc) • 240 kB
JavaScript
/**
* @license Angular v10.0.6
* (c) 2010-2020 Google LLC. https://angular.io/
* License: MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/animations'), require('@angular/core')) :
typeof define === 'function' && define.amd ? define('@angular/animations/browser', ['exports', '@angular/animations', '@angular/core'], factory) :
(global = global || self, factory((global.ng = global.ng || {}, global.ng.animations = global.ng.animations || {}, global.ng.animations.browser = {}), global.ng.animations, global.ng.core));
}(this, (function (exports, animations, core) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b)
if (b.hasOwnProperty(p))
d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function () {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); };
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try {
step(generator.next(value));
}
catch (e) {
reject(e);
} }
function rejected(value) { try {
step(generator["throw"](value));
}
catch (e) {
reject(e);
} }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function () { if (t[0] & 1)
throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f)
throw new TypeError("Generator is already executing.");
while (_)
try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
return t;
if (y = 0, t)
op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2])
_.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
}
catch (e) {
op = [6, e];
y = 0;
}
finally {
f = t = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
}
var __createBinding = Object.create ? (function (o, m, k, k2) {
if (k2 === undefined)
k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } });
}) : (function (o, m, k, k2) {
if (k2 === undefined)
k2 = k;
o[k2] = m[k];
});
function __exportStar(m, exports) {
for (var p in m)
if (p !== "default" && !exports.hasOwnProperty(p))
__createBinding(exports, m, p);
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m)
return m.call(o);
if (o && typeof o.length === "number")
return {
next: function () {
if (o && i >= o.length)
o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m)
return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
ar.push(r.value);
}
catch (error) {
e = { error: error };
}
finally {
try {
if (r && !r.done && (m = i["return"]))
m.call(i);
}
finally {
if (e)
throw e.error;
}
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++)
s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
;
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n])
i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try {
step(g[n](v));
}
catch (e) {
settle(q[0][3], e);
} }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length)
resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) {
Object.defineProperty(cooked, "raw", { value: raw });
}
else {
cooked.raw = raw;
}
return cooked;
}
;
var __setModuleDefault = Object.create ? (function (o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function (o, v) {
o["default"] = v;
};
function __importStar(mod) {
if (mod && mod.__esModule)
return mod;
var result = {};
if (mod != null)
for (var k in mod)
if (Object.hasOwnProperty.call(mod, k))
__createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to set private field on non-instance");
}
privateMap.set(receiver, value);
return value;
}
function isBrowser() {
return (typeof window !== 'undefined' && typeof window.document !== 'undefined');
}
function isNode() {
// Checking only for `process` isn't enough to identify whether or not we're in a Node
// environment, because Webpack by default will polyfill the `process`. While we can discern
// that Webpack polyfilled it by looking at `process.browser`, it's very Webpack-specific and
// might not be future-proof. Instead we look at the stringified version of `process` which
// is `[object process]` in Node and `[object Object]` when polyfilled.
return typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
}
function optimizeGroupPlayer(players) {
switch (players.length) {
case 0:
return new animations.NoopAnimationPlayer();
case 1:
return players[0];
default:
return new animations.ɵAnimationGroupPlayer(players);
}
}
function normalizeKeyframes(driver, normalizer, element, keyframes, preStyles, postStyles) {
if (preStyles === void 0) { preStyles = {}; }
if (postStyles === void 0) { postStyles = {}; }
var errors = [];
var normalizedKeyframes = [];
var previousOffset = -1;
var previousKeyframe = null;
keyframes.forEach(function (kf) {
var offset = kf['offset'];
var isSameOffset = offset == previousOffset;
var normalizedKeyframe = (isSameOffset && previousKeyframe) || {};
Object.keys(kf).forEach(function (prop) {
var normalizedProp = prop;
var normalizedValue = kf[prop];
if (prop !== 'offset') {
normalizedProp = normalizer.normalizePropertyName(normalizedProp, errors);
switch (normalizedValue) {
case animations.ɵPRE_STYLE:
normalizedValue = preStyles[prop];
break;
case animations.AUTO_STYLE:
normalizedValue = postStyles[prop];
break;
default:
normalizedValue =
normalizer.normalizeStyleValue(prop, normalizedProp, normalizedValue, errors);
break;
}
}
normalizedKeyframe[normalizedProp] = normalizedValue;
});
if (!isSameOffset) {
normalizedKeyframes.push(normalizedKeyframe);
}
previousKeyframe = normalizedKeyframe;
previousOffset = offset;
});
if (errors.length) {
var LINE_START = '\n - ';
throw new Error("Unable to animate due to the following errors:" + LINE_START + errors.join(LINE_START));
}
return normalizedKeyframes;
}
function listenOnPlayer(player, eventName, event, callback) {
switch (eventName) {
case 'start':
player.onStart(function () { return callback(event && copyAnimationEvent(event, 'start', player)); });
break;
case 'done':
player.onDone(function () { return callback(event && copyAnimationEvent(event, 'done', player)); });
break;
case 'destroy':
player.onDestroy(function () { return callback(event && copyAnimationEvent(event, 'destroy', player)); });
break;
}
}
function copyAnimationEvent(e, phaseName, player) {
var totalTime = player.totalTime;
var disabled = player.disabled ? true : false;
var event = makeAnimationEvent(e.element, e.triggerName, e.fromState, e.toState, phaseName || e.phaseName, totalTime == undefined ? e.totalTime : totalTime, disabled);
var data = e['_data'];
if (data != null) {
event['_data'] = data;
}
return event;
}
function makeAnimationEvent(element, triggerName, fromState, toState, phaseName, totalTime, disabled) {
if (phaseName === void 0) { phaseName = ''; }
if (totalTime === void 0) { totalTime = 0; }
return { element: element, triggerName: triggerName, fromState: fromState, toState: toState, phaseName: phaseName, totalTime: totalTime, disabled: !!disabled };
}
function getOrSetAsInMap(map, key, defaultValue) {
var value;
if (map instanceof Map) {
value = map.get(key);
if (!value) {
map.set(key, value = defaultValue);
}
}
else {
value = map[key];
if (!value) {
value = map[key] = defaultValue;
}
}
return value;
}
function parseTimelineCommand(command) {
var separatorPos = command.indexOf(':');
var id = command.substring(1, separatorPos);
var action = command.substr(separatorPos + 1);
return [id, action];
}
var _contains = function (elm1, elm2) { return false; };
var ɵ0 = _contains;
var _matches = function (element, selector) { return false; };
var ɵ1 = _matches;
var _query = function (element, selector, multi) {
return [];
};
var ɵ2 = _query;
// Define utility methods for browsers and platform-server(domino) where Element
// and utility methods exist.
var _isNode = isNode();
if (_isNode || typeof Element !== 'undefined') {
// this is well supported in all browsers
_contains = function (elm1, elm2) {
return elm1.contains(elm2);
};
_matches = (function () {
if (_isNode || Element.prototype.matches) {
return function (element, selector) { return element.matches(selector); };
}
else {
var proto = Element.prototype;
var fn_1 = proto.matchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector ||
proto.oMatchesSelector || proto.webkitMatchesSelector;
if (fn_1) {
return function (element, selector) { return fn_1.apply(element, [selector]); };
}
else {
return _matches;
}
}
})();
_query = function (element, selector, multi) {
var results = [];
if (multi) {
results.push.apply(results, __spread(element.querySelectorAll(selector)));
}
else {
var elm = element.querySelector(selector);
if (elm) {
results.push(elm);
}
}
return results;
};
}
function containsVendorPrefix(prop) {
// Webkit is the only real popular vendor prefix nowadays
// cc: http://shouldiprefix.com/
return prop.substring(1, 6) == 'ebkit'; // webkit or Webkit
}
var _CACHED_BODY = null;
var _IS_WEBKIT = false;
function validateStyleProperty(prop) {
if (!_CACHED_BODY) {
_CACHED_BODY = getBodyNode() || {};
_IS_WEBKIT = _CACHED_BODY.style ? ('WebkitAppearance' in _CACHED_BODY.style) : false;
}
var result = true;
if (_CACHED_BODY.style && !containsVendorPrefix(prop)) {
result = prop in _CACHED_BODY.style;
if (!result && _IS_WEBKIT) {
var camelProp = 'Webkit' + prop.charAt(0).toUpperCase() + prop.substr(1);
result = camelProp in _CACHED_BODY.style;
}
}
return result;
}
function getBodyNode() {
if (typeof document != 'undefined') {
return document.body;
}
return null;
}
var matchesElement = _matches;
var containsElement = _contains;
var invokeQuery = _query;
function hypenatePropsObject(object) {
var newObj = {};
Object.keys(object).forEach(function (prop) {
var newProp = prop.replace(/([a-z])([A-Z])/g, '$1-$2');
newObj[newProp] = object[prop];
});
return newObj;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @publicApi
*/
var NoopAnimationDriver = /** @class */ (function () {
function NoopAnimationDriver() {
}
NoopAnimationDriver.prototype.validateStyleProperty = function (prop) {
return validateStyleProperty(prop);
};
NoopAnimationDriver.prototype.matchesElement = function (element, selector) {
return matchesElement(element, selector);
};
NoopAnimationDriver.prototype.containsElement = function (elm1, elm2) {
return containsElement(elm1, elm2);
};
NoopAnimationDriver.prototype.query = function (element, selector, multi) {
return invokeQuery(element, selector, multi);
};
NoopAnimationDriver.prototype.computeStyle = function (element, prop, defaultValue) {
return defaultValue || '';
};
NoopAnimationDriver.prototype.animate = function (element, keyframes, duration, delay, easing, previousPlayers, scrubberAccessRequested) {
if (previousPlayers === void 0) { previousPlayers = []; }
return new animations.NoopAnimationPlayer(duration, delay);
};
return NoopAnimationDriver;
}());
NoopAnimationDriver.decorators = [
{ type: core.Injectable }
];
/**
* @publicApi
*/
var AnimationDriver = /** @class */ (function () {
function AnimationDriver() {
}
return AnimationDriver;
}());
AnimationDriver.NOOP = new NoopAnimationDriver();
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var ONE_SECOND = 1000;
var SUBSTITUTION_EXPR_START = '{{';
var SUBSTITUTION_EXPR_END = '}}';
var ENTER_CLASSNAME = 'ng-enter';
var LEAVE_CLASSNAME = 'ng-leave';
var ENTER_SELECTOR = '.ng-enter';
var LEAVE_SELECTOR = '.ng-leave';
var NG_TRIGGER_CLASSNAME = 'ng-trigger';
var NG_TRIGGER_SELECTOR = '.ng-trigger';
var NG_ANIMATING_CLASSNAME = 'ng-animating';
var NG_ANIMATING_SELECTOR = '.ng-animating';
function resolveTimingValue(value) {
if (typeof value == 'number')
return value;
var matches = value.match(/^(-?[\.\d]+)(m?s)/);
if (!matches || matches.length < 2)
return 0;
return _convertTimeValueToMS(parseFloat(matches[1]), matches[2]);
}
function _convertTimeValueToMS(value, unit) {
switch (unit) {
case 's':
return value * ONE_SECOND;
default: // ms or something else
return value;
}
}
function resolveTiming(timings, errors, allowNegativeValues) {
return timings.hasOwnProperty('duration') ?
timings :
parseTimeExpression(timings, errors, allowNegativeValues);
}
function parseTimeExpression(exp, errors, allowNegativeValues) {
var regex = /^(-?[\.\d]+)(m?s)(?:\s+(-?[\.\d]+)(m?s))?(?:\s+([-a-z]+(?:\(.+?\))?))?$/i;
var duration;
var delay = 0;
var easing = '';
if (typeof exp === 'string') {
var matches = exp.match(regex);
if (matches === null) {
errors.push("The provided timing value \"" + exp + "\" is invalid.");
return { duration: 0, delay: 0, easing: '' };
}
duration = _convertTimeValueToMS(parseFloat(matches[1]), matches[2]);
var delayMatch = matches[3];
if (delayMatch != null) {
delay = _convertTimeValueToMS(parseFloat(delayMatch), matches[4]);
}
var easingVal = matches[5];
if (easingVal) {
easing = easingVal;
}
}
else {
duration = exp;
}
if (!allowNegativeValues) {
var containsErrors = false;
var startIndex = errors.length;
if (duration < 0) {
errors.push("Duration values below 0 are not allowed for this animation step.");
containsErrors = true;
}
if (delay < 0) {
errors.push("Delay values below 0 are not allowed for this animation step.");
containsErrors = true;
}
if (containsErrors) {
errors.splice(startIndex, 0, "The provided timing value \"" + exp + "\" is invalid.");
}
}
return { duration: duration, delay: delay, easing: easing };
}
function copyObj(obj, destination) {
if (destination === void 0) { destination = {}; }
Object.keys(obj).forEach(function (prop) {
destination[prop] = obj[prop];
});
return destination;
}
function normalizeStyles(styles) {
var normalizedStyles = {};
if (Array.isArray(styles)) {
styles.forEach(function (data) { return copyStyles(data, false, normalizedStyles); });
}
else {
copyStyles(styles, false, normalizedStyles);
}
return normalizedStyles;
}
function copyStyles(styles, readPrototype, destination) {
if (destination === void 0) { destination = {}; }
if (readPrototype) {
// we make use of a for-in loop so that the
// prototypically inherited properties are
// revealed from the backFill map
for (var prop in styles) {
destination[prop] = styles[prop];
}
}
else {
copyObj(styles, destination);
}
return destination;
}
function getStyleAttributeString(element, key, value) {
// Return the key-value pair string to be added to the style attribute for the
// given CSS style key.
if (value) {
return key + ':' + value + ';';
}
else {
return '';
}
}
function writeStyleAttribute(element) {
// Read the style property of the element and manually reflect it to the
// style attribute. This is needed because Domino on platform-server doesn't
// understand the full set of allowed CSS properties and doesn't reflect some
// of them automatically.
var styleAttrValue = '';
for (var i = 0; i < element.style.length; i++) {
var key = element.style.item(i);
styleAttrValue += getStyleAttributeString(element, key, element.style.getPropertyValue(key));
}
for (var key in element.style) {
// Skip internal Domino properties that don't need to be reflected.
if (!element.style.hasOwnProperty(key) || key.startsWith('_')) {
continue;
}
var dashKey = camelCaseToDashCase(key);
styleAttrValue += getStyleAttributeString(element, dashKey, element.style[key]);
}
element.setAttribute('style', styleAttrValue);
}
function setStyles(element, styles, formerStyles) {
if (element['style']) {
Object.keys(styles).forEach(function (prop) {
var camelProp = dashCaseToCamelCase(prop);
if (formerStyles && !formerStyles.hasOwnProperty(prop)) {
formerStyles[prop] = element.style[camelProp];
}
element.style[camelProp] = styles[prop];
});
// On the server set the 'style' attribute since it's not automatically reflected.
if (isNode()) {
writeStyleAttribute(element);
}
}
}
function eraseStyles(element, styles) {
if (element['style']) {
Object.keys(styles).forEach(function (prop) {
var camelProp = dashCaseToCamelCase(prop);
element.style[camelProp] = '';
});
// On the server set the 'style' attribute since it's not automatically reflected.
if (isNode()) {
writeStyleAttribute(element);
}
}
}
function normalizeAnimationEntry(steps) {
if (Array.isArray(steps)) {
if (steps.length == 1)
return steps[0];
return animations.sequence(steps);
}
return steps;
}
function validateStyleParams(value, options, errors) {
var params = options.params || {};
var matches = extractStyleParams(value);
if (matches.length) {
matches.forEach(function (varName) {
if (!params.hasOwnProperty(varName)) {
errors.push("Unable to resolve the local animation param " + varName + " in the given list of values");
}
});
}
}
var PARAM_REGEX = new RegExp(SUBSTITUTION_EXPR_START + "\\s*(.+?)\\s*" + SUBSTITUTION_EXPR_END, 'g');
function extractStyleParams(value) {
var params = [];
if (typeof value === 'string') {
var match = void 0;
while (match = PARAM_REGEX.exec(value)) {
params.push(match[1]);
}
PARAM_REGEX.lastIndex = 0;
}
return params;
}
function interpolateParams(value, params, errors) {
var original = value.toString();
var str = original.replace(PARAM_REGEX, function (_, varName) {
var localVal = params[varName];
// this means that the value was never overridden by the data passed in by the user
if (!params.hasOwnProperty(varName)) {
errors.push("Please provide a value for the animation param " + varName);
localVal = '';
}
return localVal.toString();
});
// we do this to assert that numeric values stay as they are
return str == original ? value : str;
}
function iteratorToArray(iterator) {
var arr = [];
var item = iterator.next();
while (!item.done) {
arr.push(item.value);
item = iterator.next();
}
return arr;
}
function mergeAnimationOptions(source, destination) {
if (source.params) {
var p0_1 = source.params;
if (!destination.params) {
destination.params = {};
}
var p1_1 = destination.params;
Object.keys(p0_1).forEach(function (param) {
if (!p1_1.hasOwnProperty(param)) {
p1_1[param] = p0_1[param];
}
});
}
return destination;
}
var DASH_CASE_REGEXP = /-+([a-z0-9])/g;
function dashCaseToCamelCase(input) {
return input.replace(DASH_CASE_REGEXP, function () {
var m = [];
for (var _i = 0; _i < arguments.length; _i++) {
m[_i] = arguments[_i];
}
return m[1].toUpperCase();
});
}
function camelCaseToDashCase(input) {
return input.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}
function allowPreviousPlayerStylesMerge(duration, delay) {
return duration === 0 || delay === 0;
}
function balancePreviousStylesIntoKeyframes(element, keyframes, previousStyles) {
var previousStyleProps = Object.keys(previousStyles);
if (previousStyleProps.length && keyframes.length) {
var startingKeyframe_1 = keyframes[0];
var missingStyleProps_1 = [];
previousStyleProps.forEach(function (prop) {
if (!startingKeyframe_1.hasOwnProperty(prop)) {
missingStyleProps_1.push(prop);
}
startingKeyframe_1[prop] = previousStyles[prop];
});
if (missingStyleProps_1.length) {
var _loop_1 = function () {
var kf = keyframes[i];
missingStyleProps_1.forEach(function (prop) {
kf[prop] = computeStyle(element, prop);
});
};
// tslint:disable-next-line
for (var i = 1; i < keyframes.length; i++) {
_loop_1();
}
}
}
return keyframes;
}
function visitDslNode(visitor, node, context) {
switch (node.type) {
case 7 /* Trigger */:
return visitor.visitTrigger(node, context);
case 0 /* State */:
return visitor.visitState(node, context);
case 1 /* Transition */:
return visitor.visitTransition(node, context);
case 2 /* Sequence */:
return visitor.visitSequence(node, context);
case 3 /* Group */:
return visitor.visitGroup(node, context);
case 4 /* Animate */:
return visitor.visitAnimate(node, context);
case 5 /* Keyframes */:
return visitor.visitKeyframes(node, context);
case 6 /* Style */:
return visitor.visitStyle(node, context);
case 8 /* Reference */:
return visitor.visitReference(node, context);
case 9 /* AnimateChild */:
return visitor.visitAnimateChild(node, context);
case 10 /* AnimateRef */:
return visitor.visitAnimateRef(node, context);
case 11 /* Query */:
return visitor.visitQuery(node, context);
case 12 /* Stagger */:
return visitor.visitStagger(node, context);
default:
throw new Error("Unable to resolve animation metadata node #" + node.type);
}
}
function computeStyle(element, prop) {
return window.getComputedStyle(element)[prop];
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var ANY_STATE = '*';
function parseTransitionExpr(transitionValue, errors) {
var expressions = [];
if (typeof transitionValue == 'string') {
transitionValue.split(/\s*,\s*/).forEach(function (str) { return parseInnerTransitionStr(str, expressions, errors); });
}
else {
expressions.push(transitionValue);
}
return expressions;
}
function parseInnerTransitionStr(eventStr, expressions, errors) {
if (eventStr[0] == ':') {
var result = parseAnimationAlias(eventStr, errors);
if (typeof result == 'function') {
expressions.push(result);
return;
}
eventStr = result;
}
var match = eventStr.match(/^(\*|[-\w]+)\s*(<?[=-]>)\s*(\*|[-\w]+)$/);
if (match == null || match.length < 4) {
errors.push("The provided transition expression \"" + eventStr + "\" is not supported");
return expressions;
}
var fromState = match[1];
var separator = match[2];
var toState = match[3];
expressions.push(makeLambdaFromStates(fromState, toState));
var isFullAnyStateExpr = fromState == ANY_STATE && toState == ANY_STATE;
if (separator[0] == '<' && !isFullAnyStateExpr) {
expressions.push(makeLambdaFromStates(toState, fromState));
}
}
function parseAnimationAlias(alias, errors) {
switch (alias) {
case ':enter':
return 'void => *';
case ':leave':
return '* => void';
case ':increment':
return function (fromState, toState) { return parseFloat(toState) > parseFloat(fromState); };
case ':decrement':
return function (fromState, toState) { return parseFloat(toState) < parseFloat(fromState); };
default:
errors.push("The transition alias value \"" + alias + "\" is not supported");
return '* => *';
}
}
// DO NOT REFACTOR ... keep the follow set instantiations
// with the values intact (closure compiler for some reason
// removes follow-up lines that add the values outside of
// the constructor...
var TRUE_BOOLEAN_VALUES = new Set(['true', '1']);
var FALSE_BOOLEAN_VALUES = new Set(['false', '0']);
function makeLambdaFromStates(lhs, rhs) {
var LHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(lhs) || FALSE_BOOLEAN_VALUES.has(lhs);
var RHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(rhs) || FALSE_BOOLEAN_VALUES.has(rhs);
return function (fromState, toState) {
var lhsMatch = lhs == ANY_STATE || lhs == fromState;
var rhsMatch = rhs == ANY_STATE || rhs == toState;
if (!lhsMatch && LHS_MATCH_BOOLEAN && typeof fromState === 'boolean') {
lhsMatch = fromState ? TRUE_BOOLEAN_VALUES.has(lhs) : FALSE_BOOLEAN_VALUES.has(lhs);
}
if (!rhsMatch && RHS_MATCH_BOOLEAN && typeof toState === 'boolean') {
rhsMatch = toState ? TRUE_BOOLEAN_VALUES.has(rhs) : FALSE_BOOLEAN_VALUES.has(rhs);
}
return lhsMatch && rhsMatch;
};
}
var SELF_TOKEN = ':self';
var SELF_TOKEN_REGEX = new RegExp("s*" + SELF_TOKEN + "s*,?", 'g');
/*
* [Validation]
* The visitor code below will traverse the animation AST generated by the animation verb functions
* (the output is a tree of objects) and attempt to perform a series of validations on the data. The
* following corner-cases will be validated:
*
* 1. Overlap of animations
* Given that a CSS property cannot be animated in more than one place at the same time, it's
* important that this behavior is detected and validated. The way in which this occurs is that
* each time a style property is examined, a string-map containing the property will be updated with
* the start and end times for when the property is used within an animation step.
*
* If there are two or more parallel animations that are currently running (these are invoked by the
* group()) on the same element then the validator will throw an error. Since the start/end timing
* values are collected for each property then if the current animation step is animating the same
* property and its timing values fall anywhere into the window of time that the property is
* currently being animated within then this is what causes an error.
*
* 2. Timing values
* The validator will validate to see if a timing value of `duration delay easing` or
* `durationNumber` is valid or not.
*
* (note that upon validation the code below will replace the timing data with an object containing
* {duration,delay,easing}.
*
* 3. Offset Validation
* Each of the style() calls are allowed to have an offset value when placed inside of keyframes().
* Offsets within keyframes() are considered valid when:
*
* - No offsets are used at all
* - Each style() entry contains an offset value
* - Each offset is between 0 and 1
* - Each offset is greater to or equal than the previous one
*
* Otherwise an error will be thrown.
*/
function buildAnimationAst(driver, metadata, errors) {
return new AnimationAstBuilderVisitor(driver).build(metadata, errors);
}
var ROOT_SELECTOR = '';
var AnimationAstBuilderVisitor = /** @class */ (function () {
function AnimationAstBuilderVisitor(_driver) {
this._driver = _driver;
}
AnimationAstBuilderVisitor.prototype.build = function (metadata, errors) {
var context = new AnimationAstBuilderContext(errors);
this._resetContextStyleTimingState(context);
return visitDslNode(this, normalizeAnimationEntry(metadata), context);
};
AnimationAstBuilderVisitor.prototype._resetContextStyleTimingState = function (context) {
context.currentQuerySelector = ROOT_SELECTOR;
context.collectedStyles = {};
context.collectedStyles[ROOT_SELECTOR] = {};
context.currentTime = 0;
};
AnimationAstBuilderVisitor.prototype.visitTrigger = function (metadata, context) {
var _this = this;
var queryCount = context.queryCount = 0;
var depCount = context.depCount = 0;
var states = [];
var transitions = [];
if (metadata.name.charAt(0) == '@') {
context.errors.push('animation triggers cannot be prefixed with an `@` sign (e.g. trigger(\'@foo\', [...]))');
}
metadata.definitions.forEach(function (def) {
_this._resetContextStyleTimingState(context);
if (def.type == 0 /* State */) {
var stateDef_1 = def;
var name = stateDef_1.name;
name.toString().split(/\s*,\s*/).forEach(function (n) {
stateDef_1.name = n;
states.push(_this.visitState(stateDef_1, context));
});
stateDef_1.name = name;
}
else if (def.type == 1 /* Transition */) {
var transition = _this.visitTransition(def, context);
queryCount += transition.queryCount;
depCount += transition.depCount;
transitions.push(transition);
}
else {
context.errors.push('only state() and transition() definitions can sit inside of a trigger()');
}
});
return {
type: 7 /* Trigger */,
name: metadata.name,
states: states,
transitions: transitions,
queryCount: queryCount,
depCount: depCount,
options: null
};
};
AnimationAstBuilderVisitor.prototype.visitState = function (metadata, context) {
var styleAst = this.visitStyle(metadata.styles, context);
var astParams = (metadata.options && metadata.options.params) || null;
if (styleAst.containsDynamicStyles) {
var missingSubs_1 = new Set();
var params_1 = astParams || {};
styleAst.styles.forEach(function (value) {
if (isObject(value)) {
var stylesObj_1 = value;
Object.keys(stylesObj_1).forEach(function (prop) {
extractStyleParams(stylesObj_1[prop]).forEach(function (sub) {
if (!params_1.hasOwnProperty(sub)) {
missingSubs_1.add(sub);
}
});
});
}
});
if (missingSubs_1.size) {
var missingSubsArr = iteratorToArray(missingSubs_1.values());
context.errors.push("state(\"" + metadata
.name + "\", ...) must define default values for all the following style substitutions: " + missingSubsArr.join(', '));
}
}
return {
type: 0 /* State */,
name: metadata.name,
style: styleAst,
options: astParams ? { params: astParams } : null
};
};
AnimationAstBuilderVisitor.prototype.visitTransition = function (metadata, context) {
context.queryCount = 0;
context.depCount = 0;
var animation = visitDslNode(this, normalizeAnimationEntry(metadata.animation), context);
var matchers = parseTransitionExpr(metadata.expr, context.errors);
return {
type: 1 /* Transition */,
matchers: matchers,
animation: animation,
queryCount: context.queryCount,
depCount: context.depCount,
options: normalizeAnimationOptions(metadata.options)
};
};
AnimationAstBuilderVisitor.prototype.visitSequence = function (metadata, context) {
var _this = this;
return {
type: 2 /* Sequence */,
steps: metadata.steps.map(function (s) { return visitDslNode(_this, s, context); }),
options: normalizeAnimationOptions(metadata.options)
};
};
AnimationAstBuilderVisitor.prototype.visitGroup = function (metadata, context) {
var _this = this;
var currentTime = context.currentTime;
var furthestTime = 0;
var steps = metadata.steps.map(function (step) {
context.currentTime = currentTime;
var innerAst = visitDslNode(_this, step, context);
furthestTime = Math.max(furthestTime, context.currentTime);
return innerAst;
});
context.currentTime = furthestTime;
return {
type: 3 /* Group */,
steps: steps,
options: normalizeAnimationOptions(metadata.options)
};
};
AnimationAstBuilderVisitor.prototype.visitAnimate = function (metadata, context) {
var timingAst = constructTimingAst(metadata.timings, context.errors);
context.currentAnimateTimings = timingAst;
var styleAst;
var styleMetadata = metadata.styles ? metadata.styles : animations.style({});
if (styleMetadata.type == 5 /* Keyframes */) {
styleAst = this.visitKeyframes(styleMetadata, context);
}
else {
var styleMetadata_1 = metadata.styles;
var isEmpty = false;
if (!styleMetadata_1) {
isEmpty = true;
var newStyleData = {};
if (timingAst.easing) {
newStyleData['easing'] = timingAst.easing;
}
styleMetadata_1 = animations.style(newStyleData);
}
context.currentTime += timingAst.duration + timingAst.delay;
var _styleAst = this.visitStyle(styleMetadata_1, context);
_styleAst.isEmptyStep = isEmpty;
styleAst = _styleAst;
}
context.currentAnimateTimings = null;
return {
type: 4 /* Animate */,
timings: timingAst,
style: styleAst,
options: null
};
};
AnimationAstBuilderVisitor.prototype.visitStyle = function (metadata, context) {
var ast = this._makeStyleAst(metadata, context);
this._validateStyleAst(ast, context);
return ast;
};
AnimationAstBuilderVisitor.prototype._makeStyleAst = function (metadata, context) {
var styles = [];
if (Array.isArray(metadata.styles)) {
metadata.styles.forEach(function (styleTuple) {
if (typeof styleTuple == 'string') {
if (styleTuple == animations.AUTO_STYLE) {
styles.push(styleTuple);
}
else {
context.errors.push("The provided style string value " + styleTup