@angular/animations
Version:
Angular - animations integration with web-animations
1,295 lines (1,286 loc) • 186 kB
JavaScript
/**
* @license Angular v16.1.7
* (c) 2010-2022 Google LLC. https://angular.io/
* License: MIT
*/
import { ɵAnimationGroupPlayer, NoopAnimationPlayer, AUTO_STYLE, ɵPRE_STYLE, sequence, style } from '@angular/animations';
import * as i0 from '@angular/core';
import { ɵRuntimeError, Injectable } from '@angular/core';
const LINE_START = '\n - ';
function invalidTimingValue(exp) {
return new ɵRuntimeError(3000 /* RuntimeErrorCode.INVALID_TIMING_VALUE */, ngDevMode && `The provided timing value "${exp}" is invalid.`);
}
function negativeStepValue() {
return new ɵRuntimeError(3100 /* RuntimeErrorCode.NEGATIVE_STEP_VALUE */, ngDevMode && 'Duration values below 0 are not allowed for this animation step.');
}
function negativeDelayValue() {
return new ɵRuntimeError(3101 /* RuntimeErrorCode.NEGATIVE_DELAY_VALUE */, ngDevMode && 'Delay values below 0 are not allowed for this animation step.');
}
function invalidStyleParams(varName) {
return new ɵRuntimeError(3001 /* RuntimeErrorCode.INVALID_STYLE_PARAMS */, ngDevMode &&
`Unable to resolve the local animation param ${varName} in the given list of values`);
}
function invalidParamValue(varName) {
return new ɵRuntimeError(3003 /* RuntimeErrorCode.INVALID_PARAM_VALUE */, ngDevMode && `Please provide a value for the animation param ${varName}`);
}
function invalidNodeType(nodeType) {
return new ɵRuntimeError(3004 /* RuntimeErrorCode.INVALID_NODE_TYPE */, ngDevMode && `Unable to resolve animation metadata node #${nodeType}`);
}
function invalidCssUnitValue(userProvidedProperty, value) {
return new ɵRuntimeError(3005 /* RuntimeErrorCode.INVALID_CSS_UNIT_VALUE */, ngDevMode && `Please provide a CSS unit value for ${userProvidedProperty}:${value}`);
}
function invalidTrigger() {
return new ɵRuntimeError(3006 /* RuntimeErrorCode.INVALID_TRIGGER */, ngDevMode &&
'animation triggers cannot be prefixed with an `@` sign (e.g. trigger(\'@foo\', [...]))');
}
function invalidDefinition() {
return new ɵRuntimeError(3007 /* RuntimeErrorCode.INVALID_DEFINITION */, ngDevMode && 'only state() and transition() definitions can sit inside of a trigger()');
}
function invalidState(metadataName, missingSubs) {
return new ɵRuntimeError(3008 /* RuntimeErrorCode.INVALID_STATE */, ngDevMode &&
`state("${metadataName}", ...) must define default values for all the following style substitutions: ${missingSubs.join(', ')}`);
}
function invalidStyleValue(value) {
return new ɵRuntimeError(3002 /* RuntimeErrorCode.INVALID_STYLE_VALUE */, ngDevMode && `The provided style string value ${value} is not allowed.`);
}
function invalidProperty(prop) {
return new ɵRuntimeError(3009 /* RuntimeErrorCode.INVALID_PROPERTY */, ngDevMode &&
`The provided animation property "${prop}" is not a supported CSS property for animations`);
}
function invalidParallelAnimation(prop, firstStart, firstEnd, secondStart, secondEnd) {
return new ɵRuntimeError(3010 /* RuntimeErrorCode.INVALID_PARALLEL_ANIMATION */, ngDevMode &&
`The CSS property "${prop}" that exists between the times of "${firstStart}ms" and "${firstEnd}ms" is also being animated in a parallel animation between the times of "${secondStart}ms" and "${secondEnd}ms"`);
}
function invalidKeyframes() {
return new ɵRuntimeError(3011 /* RuntimeErrorCode.INVALID_KEYFRAMES */, ngDevMode && `keyframes() must be placed inside of a call to animate()`);
}
function invalidOffset() {
return new ɵRuntimeError(3012 /* RuntimeErrorCode.INVALID_OFFSET */, ngDevMode && `Please ensure that all keyframe offsets are between 0 and 1`);
}
function keyframeOffsetsOutOfOrder() {
return new ɵRuntimeError(3200 /* RuntimeErrorCode.KEYFRAME_OFFSETS_OUT_OF_ORDER */, ngDevMode && `Please ensure that all keyframe offsets are in order`);
}
function keyframesMissingOffsets() {
return new ɵRuntimeError(3202 /* RuntimeErrorCode.KEYFRAMES_MISSING_OFFSETS */, ngDevMode && `Not all style() steps within the declared keyframes() contain offsets`);
}
function invalidStagger() {
return new ɵRuntimeError(3013 /* RuntimeErrorCode.INVALID_STAGGER */, ngDevMode && `stagger() can only be used inside of query()`);
}
function invalidQuery(selector) {
return new ɵRuntimeError(3014 /* RuntimeErrorCode.INVALID_QUERY */, ngDevMode &&
`\`query("${selector}")\` returned zero elements. (Use \`query("${selector}", { optional: true })\` if you wish to allow this.)`);
}
function invalidExpression(expr) {
return new ɵRuntimeError(3015 /* RuntimeErrorCode.INVALID_EXPRESSION */, ngDevMode && `The provided transition expression "${expr}" is not supported`);
}
function invalidTransitionAlias(alias) {
return new ɵRuntimeError(3016 /* RuntimeErrorCode.INVALID_TRANSITION_ALIAS */, ngDevMode && `The transition alias value "${alias}" is not supported`);
}
function validationFailed(errors) {
return new ɵRuntimeError(3500 /* RuntimeErrorCode.VALIDATION_FAILED */, ngDevMode && `animation validation failed:\n${errors.map(err => err.message).join('\n')}`);
}
function buildingFailed(errors) {
return new ɵRuntimeError(3501 /* RuntimeErrorCode.BUILDING_FAILED */, ngDevMode && `animation building failed:\n${errors.map(err => err.message).join('\n')}`);
}
function triggerBuildFailed(name, errors) {
return new ɵRuntimeError(3404 /* RuntimeErrorCode.TRIGGER_BUILD_FAILED */, ngDevMode &&
`The animation trigger "${name}" has failed to build due to the following errors:\n - ${errors.map(err => err.message).join('\n - ')}`);
}
function animationFailed(errors) {
return new ɵRuntimeError(3502 /* RuntimeErrorCode.ANIMATION_FAILED */, ngDevMode &&
`Unable to animate due to the following errors:${LINE_START}${errors.map(err => err.message).join(LINE_START)}`);
}
function registerFailed(errors) {
return new ɵRuntimeError(3503 /* RuntimeErrorCode.REGISTRATION_FAILED */, ngDevMode &&
`Unable to build the animation due to the following errors: ${errors.map(err => err.message).join('\n')}`);
}
function missingOrDestroyedAnimation() {
return new ɵRuntimeError(3300 /* RuntimeErrorCode.MISSING_OR_DESTROYED_ANIMATION */, ngDevMode && 'The requested animation doesn\'t exist or has already been destroyed');
}
function createAnimationFailed(errors) {
return new ɵRuntimeError(3504 /* RuntimeErrorCode.CREATE_ANIMATION_FAILED */, ngDevMode &&
`Unable to create the animation due to the following errors:${errors.map(err => err.message).join('\n')}`);
}
function missingPlayer(id) {
return new ɵRuntimeError(3301 /* RuntimeErrorCode.MISSING_PLAYER */, ngDevMode && `Unable to find the timeline player referenced by ${id}`);
}
function missingTrigger(phase, name) {
return new ɵRuntimeError(3302 /* RuntimeErrorCode.MISSING_TRIGGER */, ngDevMode &&
`Unable to listen on the animation trigger event "${phase}" because the animation trigger "${name}" doesn\'t exist!`);
}
function missingEvent(name) {
return new ɵRuntimeError(3303 /* RuntimeErrorCode.MISSING_EVENT */, ngDevMode &&
`Unable to listen on the animation trigger "${name}" because the provided event is undefined!`);
}
function unsupportedTriggerEvent(phase, name) {
return new ɵRuntimeError(3400 /* RuntimeErrorCode.UNSUPPORTED_TRIGGER_EVENT */, ngDevMode &&
`The provided animation trigger event "${phase}" for the animation trigger "${name}" is not supported!`);
}
function unregisteredTrigger(name) {
return new ɵRuntimeError(3401 /* RuntimeErrorCode.UNREGISTERED_TRIGGER */, ngDevMode && `The provided animation trigger "${name}" has not been registered!`);
}
function triggerTransitionsFailed(errors) {
return new ɵRuntimeError(3402 /* RuntimeErrorCode.TRIGGER_TRANSITIONS_FAILED */, ngDevMode &&
`Unable to process animations due to the following failed trigger transitions\n ${errors.map(err => err.message).join('\n')}`);
}
function triggerParsingFailed(name, errors) {
return new ɵRuntimeError(3403 /* RuntimeErrorCode.TRIGGER_PARSING_FAILED */, ngDevMode &&
`Animation parsing for the ${name} trigger have failed:${LINE_START}${errors.map(err => err.message).join(LINE_START)}`);
}
function transitionFailed(name, errors) {
return new ɵRuntimeError(3505 /* RuntimeErrorCode.TRANSITION_FAILED */, ngDevMode && `@${name} has failed due to:\n ${errors.map(err => err.message).join('\n- ')}`);
}
/**
* Set of all animatable CSS properties
*
* @see https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties
*/
const ANIMATABLE_PROP_SET = new Set([
'-moz-outline-radius',
'-moz-outline-radius-bottomleft',
'-moz-outline-radius-bottomright',
'-moz-outline-radius-topleft',
'-moz-outline-radius-topright',
'-ms-grid-columns',
'-ms-grid-rows',
'-webkit-line-clamp',
'-webkit-text-fill-color',
'-webkit-text-stroke',
'-webkit-text-stroke-color',
'accent-color',
'all',
'backdrop-filter',
'background',
'background-color',
'background-position',
'background-size',
'block-size',
'border',
'border-block-end',
'border-block-end-color',
'border-block-end-width',
'border-block-start',
'border-block-start-color',
'border-block-start-width',
'border-bottom',
'border-bottom-color',
'border-bottom-left-radius',
'border-bottom-right-radius',
'border-bottom-width',
'border-color',
'border-end-end-radius',
'border-end-start-radius',
'border-image-outset',
'border-image-slice',
'border-image-width',
'border-inline-end',
'border-inline-end-color',
'border-inline-end-width',
'border-inline-start',
'border-inline-start-color',
'border-inline-start-width',
'border-left',
'border-left-color',
'border-left-width',
'border-radius',
'border-right',
'border-right-color',
'border-right-width',
'border-start-end-radius',
'border-start-start-radius',
'border-top',
'border-top-color',
'border-top-left-radius',
'border-top-right-radius',
'border-top-width',
'border-width',
'bottom',
'box-shadow',
'caret-color',
'clip',
'clip-path',
'color',
'column-count',
'column-gap',
'column-rule',
'column-rule-color',
'column-rule-width',
'column-width',
'columns',
'filter',
'flex',
'flex-basis',
'flex-grow',
'flex-shrink',
'font',
'font-size',
'font-size-adjust',
'font-stretch',
'font-variation-settings',
'font-weight',
'gap',
'grid-column-gap',
'grid-gap',
'grid-row-gap',
'grid-template-columns',
'grid-template-rows',
'height',
'inline-size',
'input-security',
'inset',
'inset-block',
'inset-block-end',
'inset-block-start',
'inset-inline',
'inset-inline-end',
'inset-inline-start',
'left',
'letter-spacing',
'line-clamp',
'line-height',
'margin',
'margin-block-end',
'margin-block-start',
'margin-bottom',
'margin-inline-end',
'margin-inline-start',
'margin-left',
'margin-right',
'margin-top',
'mask',
'mask-border',
'mask-position',
'mask-size',
'max-block-size',
'max-height',
'max-inline-size',
'max-lines',
'max-width',
'min-block-size',
'min-height',
'min-inline-size',
'min-width',
'object-position',
'offset',
'offset-anchor',
'offset-distance',
'offset-path',
'offset-position',
'offset-rotate',
'opacity',
'order',
'outline',
'outline-color',
'outline-offset',
'outline-width',
'padding',
'padding-block-end',
'padding-block-start',
'padding-bottom',
'padding-inline-end',
'padding-inline-start',
'padding-left',
'padding-right',
'padding-top',
'perspective',
'perspective-origin',
'right',
'rotate',
'row-gap',
'scale',
'scroll-margin',
'scroll-margin-block',
'scroll-margin-block-end',
'scroll-margin-block-start',
'scroll-margin-bottom',
'scroll-margin-inline',
'scroll-margin-inline-end',
'scroll-margin-inline-start',
'scroll-margin-left',
'scroll-margin-right',
'scroll-margin-top',
'scroll-padding',
'scroll-padding-block',
'scroll-padding-block-end',
'scroll-padding-block-start',
'scroll-padding-bottom',
'scroll-padding-inline',
'scroll-padding-inline-end',
'scroll-padding-inline-start',
'scroll-padding-left',
'scroll-padding-right',
'scroll-padding-top',
'scroll-snap-coordinate',
'scroll-snap-destination',
'scrollbar-color',
'shape-image-threshold',
'shape-margin',
'shape-outside',
'tab-size',
'text-decoration',
'text-decoration-color',
'text-decoration-thickness',
'text-emphasis',
'text-emphasis-color',
'text-indent',
'text-shadow',
'text-underline-offset',
'top',
'transform',
'transform-origin',
'translate',
'vertical-align',
'visibility',
'width',
'word-spacing',
'z-index',
'zoom',
]);
function optimizeGroupPlayer(players) {
switch (players.length) {
case 0:
return new NoopAnimationPlayer();
case 1:
return players[0];
default:
return new ɵAnimationGroupPlayer(players);
}
}
function normalizeKeyframes$1(normalizer, keyframes, preStyles = new Map(), postStyles = new Map()) {
const errors = [];
const normalizedKeyframes = [];
let previousOffset = -1;
let previousKeyframe = null;
keyframes.forEach(kf => {
const offset = kf.get('offset');
const isSameOffset = offset == previousOffset;
const normalizedKeyframe = (isSameOffset && previousKeyframe) || new Map();
kf.forEach((val, prop) => {
let normalizedProp = prop;
let normalizedValue = val;
if (prop !== 'offset') {
normalizedProp = normalizer.normalizePropertyName(normalizedProp, errors);
switch (normalizedValue) {
case ɵPRE_STYLE:
normalizedValue = preStyles.get(prop);
break;
case AUTO_STYLE:
normalizedValue = postStyles.get(prop);
break;
default:
normalizedValue =
normalizer.normalizeStyleValue(prop, normalizedProp, normalizedValue, errors);
break;
}
}
normalizedKeyframe.set(normalizedProp, normalizedValue);
});
if (!isSameOffset) {
normalizedKeyframes.push(normalizedKeyframe);
}
previousKeyframe = normalizedKeyframe;
previousOffset = offset;
});
if (errors.length) {
throw animationFailed(errors);
}
return normalizedKeyframes;
}
function listenOnPlayer(player, eventName, event, callback) {
switch (eventName) {
case 'start':
player.onStart(() => callback(event && copyAnimationEvent(event, 'start', player)));
break;
case 'done':
player.onDone(() => callback(event && copyAnimationEvent(event, 'done', player)));
break;
case 'destroy':
player.onDestroy(() => callback(event && copyAnimationEvent(event, 'destroy', player)));
break;
}
}
function copyAnimationEvent(e, phaseName, player) {
const totalTime = player.totalTime;
const disabled = player.disabled ? true : false;
const event = makeAnimationEvent(e.element, e.triggerName, e.fromState, e.toState, phaseName || e.phaseName, totalTime == undefined ? e.totalTime : totalTime, disabled);
const data = e['_data'];
if (data != null) {
event['_data'] = data;
}
return event;
}
function makeAnimationEvent(element, triggerName, fromState, toState, phaseName = '', totalTime = 0, disabled) {
return { element, triggerName, fromState, toState, phaseName, totalTime, disabled: !!disabled };
}
function getOrSetDefaultValue(map, key, defaultValue) {
let value = map.get(key);
if (!value) {
map.set(key, value = defaultValue);
}
return value;
}
function parseTimelineCommand(command) {
const separatorPos = command.indexOf(':');
const id = command.substring(1, separatorPos);
const action = command.slice(separatorPos + 1);
return [id, action];
}
const documentElement =
/* @__PURE__ */ (() => typeof document === 'undefined' ? null : document.documentElement)();
function getParentElement(element) {
const parent = element.parentNode || element.host || null; // consider host to support shadow DOM
if (parent === documentElement) {
return null;
}
return parent;
}
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
}
let _CACHED_BODY = null;
let _IS_WEBKIT = false;
function validateStyleProperty(prop) {
if (!_CACHED_BODY) {
_CACHED_BODY = getBodyNode() || {};
_IS_WEBKIT = _CACHED_BODY.style ? ('WebkitAppearance' in _CACHED_BODY.style) : false;
}
let result = true;
if (_CACHED_BODY.style && !containsVendorPrefix(prop)) {
result = prop in _CACHED_BODY.style;
if (!result && _IS_WEBKIT) {
const camelProp = 'Webkit' + prop.charAt(0).toUpperCase() + prop.slice(1);
result = camelProp in _CACHED_BODY.style;
}
}
return result;
}
function validateWebAnimatableStyleProperty(prop) {
return ANIMATABLE_PROP_SET.has(prop);
}
function getBodyNode() {
if (typeof document != 'undefined') {
return document.body;
}
return null;
}
function containsElement(elm1, elm2) {
while (elm2) {
if (elm2 === elm1) {
return true;
}
elm2 = getParentElement(elm2);
}
return false;
}
function invokeQuery(element, selector, multi) {
if (multi) {
return Array.from(element.querySelectorAll(selector));
}
const elem = element.querySelector(selector);
return elem ? [elem] : [];
}
function hypenatePropsKeys(original) {
const newMap = new Map();
original.forEach((val, prop) => {
const newProp = prop.replace(/([a-z])([A-Z])/g, '$1-$2');
newMap.set(newProp, val);
});
return newMap;
}
/**
* @publicApi
*/
class NoopAnimationDriver {
validateStyleProperty(prop) {
return validateStyleProperty(prop);
}
matchesElement(_element, _selector) {
// This method is deprecated and no longer in use so we return false.
return false;
}
containsElement(elm1, elm2) {
return containsElement(elm1, elm2);
}
getParentElement(element) {
return getParentElement(element);
}
query(element, selector, multi) {
return invokeQuery(element, selector, multi);
}
computeStyle(element, prop, defaultValue) {
return defaultValue || '';
}
animate(element, keyframes, duration, delay, easing, previousPlayers = [], scrubberAccessRequested) {
return new NoopAnimationPlayer(duration, delay);
}
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.1.7", ngImport: i0, type: NoopAnimationDriver, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.1.7", ngImport: i0, type: NoopAnimationDriver }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.1.7", ngImport: i0, type: NoopAnimationDriver, decorators: [{
type: Injectable
}] });
/**
* @publicApi
*/
class AnimationDriver {
static { this.NOOP = ( /* @__PURE__ */new NoopAnimationDriver()); }
}
const ONE_SECOND = 1000;
const SUBSTITUTION_EXPR_START = '{{';
const SUBSTITUTION_EXPR_END = '}}';
const ENTER_CLASSNAME = 'ng-enter';
const LEAVE_CLASSNAME = 'ng-leave';
const NG_TRIGGER_CLASSNAME = 'ng-trigger';
const NG_TRIGGER_SELECTOR = '.ng-trigger';
const NG_ANIMATING_CLASSNAME = 'ng-animating';
const NG_ANIMATING_SELECTOR = '.ng-animating';
function resolveTimingValue(value) {
if (typeof value == 'number')
return value;
const 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) {
const regex = /^(-?[\.\d]+)(m?s)(?:\s+(-?[\.\d]+)(m?s))?(?:\s+([-a-z]+(?:\(.+?\))?))?$/i;
let duration;
let delay = 0;
let easing = '';
if (typeof exp === 'string') {
const matches = exp.match(regex);
if (matches === null) {
errors.push(invalidTimingValue(exp));
return { duration: 0, delay: 0, easing: '' };
}
duration = _convertTimeValueToMS(parseFloat(matches[1]), matches[2]);
const delayMatch = matches[3];
if (delayMatch != null) {
delay = _convertTimeValueToMS(parseFloat(delayMatch), matches[4]);
}
const easingVal = matches[5];
if (easingVal) {
easing = easingVal;
}
}
else {
duration = exp;
}
if (!allowNegativeValues) {
let containsErrors = false;
let startIndex = errors.length;
if (duration < 0) {
errors.push(negativeStepValue());
containsErrors = true;
}
if (delay < 0) {
errors.push(negativeDelayValue());
containsErrors = true;
}
if (containsErrors) {
errors.splice(startIndex, 0, invalidTimingValue(exp));
}
}
return { duration, delay, easing };
}
function copyObj(obj, destination = {}) {
Object.keys(obj).forEach(prop => {
destination[prop] = obj[prop];
});
return destination;
}
function convertToMap(obj) {
const styleMap = new Map();
Object.keys(obj).forEach(prop => {
const val = obj[prop];
styleMap.set(prop, val);
});
return styleMap;
}
function normalizeKeyframes(keyframes) {
if (!keyframes.length) {
return [];
}
if (keyframes[0] instanceof Map) {
return keyframes;
}
return keyframes.map(kf => convertToMap(kf));
}
function normalizeStyles(styles) {
const normalizedStyles = new Map();
if (Array.isArray(styles)) {
styles.forEach(data => copyStyles(data, normalizedStyles));
}
else {
copyStyles(styles, normalizedStyles);
}
return normalizedStyles;
}
function copyStyles(styles, destination = new Map(), backfill) {
if (backfill) {
for (let [prop, val] of backfill) {
destination.set(prop, val);
}
}
for (let [prop, val] of styles) {
destination.set(prop, val);
}
return destination;
}
function setStyles(element, styles, formerStyles) {
styles.forEach((val, prop) => {
const camelProp = dashCaseToCamelCase(prop);
if (formerStyles && !formerStyles.has(prop)) {
formerStyles.set(prop, element.style[camelProp]);
}
element.style[camelProp] = val;
});
}
function eraseStyles(element, styles) {
styles.forEach((_, prop) => {
const camelProp = dashCaseToCamelCase(prop);
element.style[camelProp] = '';
});
}
function normalizeAnimationEntry(steps) {
if (Array.isArray(steps)) {
if (steps.length == 1)
return steps[0];
return sequence(steps);
}
return steps;
}
function validateStyleParams(value, options, errors) {
const params = options.params || {};
const matches = extractStyleParams(value);
if (matches.length) {
matches.forEach(varName => {
if (!params.hasOwnProperty(varName)) {
errors.push(invalidStyleParams(varName));
}
});
}
}
const PARAM_REGEX = new RegExp(`${SUBSTITUTION_EXPR_START}\\s*(.+?)\\s*${SUBSTITUTION_EXPR_END}`, 'g');
function extractStyleParams(value) {
let params = [];
if (typeof value === 'string') {
let match;
while (match = PARAM_REGEX.exec(value)) {
params.push(match[1]);
}
PARAM_REGEX.lastIndex = 0;
}
return params;
}
function interpolateParams(value, params, errors) {
const original = value.toString();
const str = original.replace(PARAM_REGEX, (_, varName) => {
let localVal = params[varName];
// this means that the value was never overridden by the data passed in by the user
if (localVal == null) {
errors.push(invalidParamValue(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) {
const arr = [];
let item = iterator.next();
while (!item.done) {
arr.push(item.value);
item = iterator.next();
}
return arr;
}
const DASH_CASE_REGEXP = /-+([a-z0-9])/g;
function dashCaseToCamelCase(input) {
return input.replace(DASH_CASE_REGEXP, (...m) => 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) {
if (previousStyles.size && keyframes.length) {
let startingKeyframe = keyframes[0];
let missingStyleProps = [];
previousStyles.forEach((val, prop) => {
if (!startingKeyframe.has(prop)) {
missingStyleProps.push(prop);
}
startingKeyframe.set(prop, val);
});
if (missingStyleProps.length) {
for (let i = 1; i < keyframes.length; i++) {
let kf = keyframes[i];
missingStyleProps.forEach(prop => kf.set(prop, computeStyle(element, prop)));
}
}
}
return keyframes;
}
function visitDslNode(visitor, node, context) {
switch (node.type) {
case 7 /* AnimationMetadataType.Trigger */:
return visitor.visitTrigger(node, context);
case 0 /* AnimationMetadataType.State */:
return visitor.visitState(node, context);
case 1 /* AnimationMetadataType.Transition */:
return visitor.visitTransition(node, context);
case 2 /* AnimationMetadataType.Sequence */:
return visitor.visitSequence(node, context);
case 3 /* AnimationMetadataType.Group */:
return visitor.visitGroup(node, context);
case 4 /* AnimationMetadataType.Animate */:
return visitor.visitAnimate(node, context);
case 5 /* AnimationMetadataType.Keyframes */:
return visitor.visitKeyframes(node, context);
case 6 /* AnimationMetadataType.Style */:
return visitor.visitStyle(node, context);
case 8 /* AnimationMetadataType.Reference */:
return visitor.visitReference(node, context);
case 9 /* AnimationMetadataType.AnimateChild */:
return visitor.visitAnimateChild(node, context);
case 10 /* AnimationMetadataType.AnimateRef */:
return visitor.visitAnimateRef(node, context);
case 11 /* AnimationMetadataType.Query */:
return visitor.visitQuery(node, context);
case 12 /* AnimationMetadataType.Stagger */:
return visitor.visitStagger(node, context);
default:
throw invalidNodeType(node.type);
}
}
function computeStyle(element, prop) {
return window.getComputedStyle(element)[prop];
}
function createListOfWarnings(warnings) {
const LINE_START = '\n - ';
return `${LINE_START}${warnings.filter(Boolean).map(warning => warning).join(LINE_START)}`;
}
function warnValidation(warnings) {
(typeof ngDevMode === 'undefined' || ngDevMode) &&
console.warn(`animation validation warnings:${createListOfWarnings(warnings)}`);
}
function warnTriggerBuild(name, warnings) {
(typeof ngDevMode === 'undefined' || ngDevMode) &&
console.warn(`The animation trigger "${name}" has built with the following warnings:${createListOfWarnings(warnings)}`);
}
function warnRegister(warnings) {
(typeof ngDevMode === 'undefined' || ngDevMode) &&
console.warn(`Animation built with the following warnings:${createListOfWarnings(warnings)}`);
}
function triggerParsingWarnings(name, warnings) {
(typeof ngDevMode === 'undefined' || ngDevMode) &&
console.warn(`Animation parsing for the ${name} trigger presents the following warnings:${createListOfWarnings(warnings)}`);
}
function pushUnrecognizedPropertiesWarning(warnings, props) {
if (props.length) {
warnings.push(`The following provided properties are not recognized: ${props.join(', ')}`);
}
}
const ANY_STATE = '*';
function parseTransitionExpr(transitionValue, errors) {
const expressions = [];
if (typeof transitionValue == 'string') {
transitionValue.split(/\s*,\s*/).forEach(str => parseInnerTransitionStr(str, expressions, errors));
}
else {
expressions.push(transitionValue);
}
return expressions;
}
function parseInnerTransitionStr(eventStr, expressions, errors) {
if (eventStr[0] == ':') {
const result = parseAnimationAlias(eventStr, errors);
if (typeof result == 'function') {
expressions.push(result);
return;
}
eventStr = result;
}
const match = eventStr.match(/^(\*|[-\w]+)\s*(<?[=-]>)\s*(\*|[-\w]+)$/);
if (match == null || match.length < 4) {
errors.push(invalidExpression(eventStr));
return expressions;
}
const fromState = match[1];
const separator = match[2];
const toState = match[3];
expressions.push(makeLambdaFromStates(fromState, toState));
const 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 (fromState, toState) => parseFloat(toState) > parseFloat(fromState);
case ':decrement':
return (fromState, toState) => parseFloat(toState) < parseFloat(fromState);
default:
errors.push(invalidTransitionAlias(alias));
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...
const TRUE_BOOLEAN_VALUES = new Set(['true', '1']);
const FALSE_BOOLEAN_VALUES = new Set(['false', '0']);
function makeLambdaFromStates(lhs, rhs) {
const LHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(lhs) || FALSE_BOOLEAN_VALUES.has(lhs);
const RHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(rhs) || FALSE_BOOLEAN_VALUES.has(rhs);
return (fromState, toState) => {
let lhsMatch = lhs == ANY_STATE || lhs == fromState;
let 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;
};
}
const SELF_TOKEN = ':self';
const 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, warnings) {
return new AnimationAstBuilderVisitor(driver).build(metadata, errors, warnings);
}
const ROOT_SELECTOR = '';
class AnimationAstBuilderVisitor {
constructor(_driver) {
this._driver = _driver;
}
build(metadata, errors, warnings) {
const context = new AnimationAstBuilderContext(errors);
this._resetContextStyleTimingState(context);
const ast = visitDslNode(this, normalizeAnimationEntry(metadata), context);
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (context.unsupportedCSSPropertiesFound.size) {
pushUnrecognizedPropertiesWarning(warnings, [...context.unsupportedCSSPropertiesFound.keys()]);
}
}
return ast;
}
_resetContextStyleTimingState(context) {
context.currentQuerySelector = ROOT_SELECTOR;
context.collectedStyles = new Map();
context.collectedStyles.set(ROOT_SELECTOR, new Map());
context.currentTime = 0;
}
visitTrigger(metadata, context) {
let queryCount = context.queryCount = 0;
let depCount = context.depCount = 0;
const states = [];
const transitions = [];
if (metadata.name.charAt(0) == '@') {
context.errors.push(invalidTrigger());
}
metadata.definitions.forEach(def => {
this._resetContextStyleTimingState(context);
if (def.type == 0 /* AnimationMetadataType.State */) {
const stateDef = def;
const name = stateDef.name;
name.toString().split(/\s*,\s*/).forEach(n => {
stateDef.name = n;
states.push(this.visitState(stateDef, context));
});
stateDef.name = name;
}
else if (def.type == 1 /* AnimationMetadataType.Transition */) {
const transition = this.visitTransition(def, context);
queryCount += transition.queryCount;
depCount += transition.depCount;
transitions.push(transition);
}
else {
context.errors.push(invalidDefinition());
}
});
return {
type: 7 /* AnimationMetadataType.Trigger */,
name: metadata.name,
states,
transitions,
queryCount,
depCount,
options: null
};
}
visitState(metadata, context) {
const styleAst = this.visitStyle(metadata.styles, context);
const astParams = (metadata.options && metadata.options.params) || null;
if (styleAst.containsDynamicStyles) {
const missingSubs = new Set();
const params = astParams || {};
styleAst.styles.forEach(style => {
if (style instanceof Map) {
style.forEach(value => {
extractStyleParams(value).forEach(sub => {
if (!params.hasOwnProperty(sub)) {
missingSubs.add(sub);
}
});
});
}
});
if (missingSubs.size) {
const missingSubsArr = iteratorToArray(missingSubs.values());
context.errors.push(invalidState(metadata.name, missingSubsArr));
}
}
return {
type: 0 /* AnimationMetadataType.State */,
name: metadata.name,
style: styleAst,
options: astParams ? { params: astParams } : null
};
}
visitTransition(metadata, context) {
context.queryCount = 0;
context.depCount = 0;
const animation = visitDslNode(this, normalizeAnimationEntry(metadata.animation), context);
const matchers = parseTransitionExpr(metadata.expr, context.errors);
return {
type: 1 /* AnimationMetadataType.Transition */,
matchers,
animation,
queryCount: context.queryCount,
depCount: context.depCount,
options: normalizeAnimationOptions(metadata.options)
};
}
visitSequence(metadata, context) {
return {
type: 2 /* AnimationMetadataType.Sequence */,
steps: metadata.steps.map(s => visitDslNode(this, s, context)),
options: normalizeAnimationOptions(metadata.options)
};
}
visitGroup(metadata, context) {
const currentTime = context.currentTime;
let furthestTime = 0;
const steps = metadata.steps.map(step => {
context.currentTime = currentTime;
const innerAst = visitDslNode(this, step, context);
furthestTime = Math.max(furthestTime, context.currentTime);
return innerAst;
});
context.currentTime = furthestTime;
return {
type: 3 /* AnimationMetadataType.Group */,
steps,
options: normalizeAnimationOptions(metadata.options)
};
}
visitAnimate(metadata, context) {
const timingAst = constructTimingAst(metadata.timings, context.errors);
context.currentAnimateTimings = timingAst;
let styleAst;
let styleMetadata = metadata.styles ? metadata.styles : style({});
if (styleMetadata.type == 5 /* AnimationMetadataType.Keyframes */) {
styleAst = this.visitKeyframes(styleMetadata, context);
}
else {
let styleMetadata = metadata.styles;
let isEmpty = false;
if (!styleMetadata) {
isEmpty = true;
const newStyleData = {};
if (timingAst.easing) {
newStyleData['easing'] = timingAst.easing;
}
styleMetadata = style(newStyleData);
}
context.currentTime += timingAst.duration + timingAst.delay;
const _styleAst = this.visitStyle(styleMetadata, context);
_styleAst.isEmptyStep = isEmpty;
styleAst = _styleAst;
}
context.currentAnimateTimings = null;
return {
type: 4 /* AnimationMetadataType.Animate */,
timings: timingAst,
style: styleAst,
options: null
};
}
visitStyle(metadata, context) {
const ast = this._makeStyleAst(metadata, context);
this._validateStyleAst(ast, context);
return ast;
}
_makeStyleAst(metadata, context) {
const styles = [];
const metadataStyles = Array.isArray(metadata.styles) ? metadata.styles : [metadata.styles];
for (let styleTuple of metadataStyles) {
if (typeof styleTuple === 'string') {
if (styleTuple === AUTO_STYLE) {
styles.push(styleTuple);
}
else {
context.errors.push(invalidStyleValue(styleTuple));
}
}
else {
styles.push(convertToMap(styleTuple));
}
}
let containsDynamicStyles = false;
let collectedEasing = null;
styles.forEach(styleData => {
if (styleData instanceof Map) {
if (styleData.has('easing')) {
collectedEasing = styleData.get('easing');
styleData.delete('easing');
}
if (!containsDynamicStyles) {
for (let value of styleData.values()) {
if (value.toString().indexOf(SUBSTITUTION_EXPR_START) >= 0) {
containsDynamicStyles = true;
break;
}
}
}
}
});
return {
type: 6 /* AnimationMetadataType.Style */,
styles,
easing: collectedEasing,
offset: metadata.offset,
containsDynamicStyles,
options: null
};
}
_validateStyleAst(ast, context) {
const timings = context.currentAnimateTimings;
let endTime = context.currentTime;
let startTime = context.currentTime;
if (timings && startTime > 0) {
startTime -= timings.duration + timings.delay;
}
ast.styles.forEach(tuple => {
if (typeof tuple === 'string')
return;
tuple.forEach((value, prop) => {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this._driver.validateStyleProperty(prop)) {
tuple.delete(prop);
context.unsupportedCSSPropertiesFound.add(prop);
return;
}
}
// This is guaranteed to have a defined Map at this querySelector location making it
// safe to add the assertion here. It is set as a default empty map in prior methods.
const collectedStyles = context.collectedStyles.get(context.currentQuerySelector);
const collectedEntry = collectedStyles.get(prop);
let updateCollectedStyle = true;
if (collectedEntry) {
if (startTime != endTime && startTime >= collectedEntry.startTime &&
endTime <= collectedEntry.endTime) {
context.errors.push(invalidParallelAnimation(prop, collectedEntry.startTime, collectedEntry.endTime, startTime, endTime));
updateCollectedStyle = false;
}
// we always choose the smaller start time value since we
// want to have a record of the entire animation window where
// the style property is being animated in between
startTime = collectedEntry.startTime;
}
if (updateCollectedStyle) {
collectedStyles.set(prop, { startTime, endTime });
}
if (context.options) {
validateStyleParams(value, context.options, context.errors);
}
});
});
}
visitKeyframes(metadata, context) {
const ast = { type: 5 /* AnimationMetadataType.Keyframes */, styles: [], options: null };
if (!context.currentAnimateTimings) {
context.errors.push(invalidKeyframes());
return ast;
}
const MAX_KEYFRAME_OFFSET = 1;
let totalKeyframesWithOffsets = 0;
const offsets = [];
let offsetsOutOfOrder = false;
let keyframesOutOfRange = false;
let previousOffset = 0;
const keyframes = metadata.steps.map(styles => {
const style = this._makeStyleAst(styles, context);
let offsetVal = style.offset != null ? style.offset : consumeOffset(style.styles);
let offset = 0;
if (offsetVal != null) {
totalKeyframesWithOffsets++;
offset = style.offset = offsetVal;
}
keyframesOutOfRange = keyframesOutOfRange || offset < 0 || offset > 1;
offsetsOutOfOrder = offsetsOutOfOrder || offset < previousOffset;
previousOffset = offset;
offsets.push(offset);
return style;
});
if (keyframesOutOfRange) {
context.errors.push(invalidOffset());
}
if (offsetsOutOfOrder) {
context.errors.push(keyframeOffsetsOutOfOrder());
}
const length = metadata.steps.length;
let generatedOffset = 0;
if (totalKeyframesWithOffsets > 0 && totalKeyframesWithOffsets < length) {
context.errors.push(keyframesMissingOffsets());
}
else if (totalKeyframesWithOffsets == 0) {
generatedOffset = MAX_KEYFRAME_OFFSET / (length - 1);
}
const limit = length - 1;
const currentTime = context.currentTime;
const currentAnimateTimings = context.currentAnimateTimings;
const animateDuration = currentAnimateTimings.duration;
keyframes.forEach((kf, i) => {
const offset = generatedOffset > 0 ? (i == limit ? 1 : (generatedOffset * i)) : offsets[i];
const durationUpToThisFrame = offset * animateDuration;
context.currentTime = currentTime + currentAnimateTimings.delay + durationUpToThisFrame;
currentAnimateTimings.duration = durationUpToThisFrame;
this._validateStyleAst(kf, context);
kf.offset = offset;
ast.styles.push(kf);
});
return ast;
}
visitReference(metadata, context) {
return {
type: 8 /* AnimationMetadataType.Reference */,
animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context),
options: normalizeAnimationOptions(metadata.options)
};
}
visitAnimateChild(metadata, context) {
context.depCount++;
return {
type: 9 /* AnimationMetadataType.AnimateChild */,
options: normalizeAnimationOptions(metadata.options)
};
}
visitAnimateRef(metadata, context) {
return {
type: 10 /* AnimationMetadataType.AnimateRef */,
animation: this.visitReference(metadata.animation, context),
options: normalizeAnimationOptions(metadata.options)
};
}
visitQuery(metadata, context) {
const parentSelector = context.currentQuerySelector;
const options = (metadata.options || {});
context.queryCount++;
context.currentQuery = metadata;
const [selector, includeSelf] = normalizeSelector(metadata.selector);
context.currentQuerySelector =
parentSelector.length ? (parentSelector + ' ' + selector) : selector;
getOrSetDefaultValue(context.collectedStyles, context.currentQuerySelector, new Map());
const animation = visitDslNode(this, normalizeAnimationEntry(metadata.animation), context);
context.currentQuery = null;
context.currentQuerySelector = parentSelector;
return {
type: 11 /* AnimationMetadataType.Query */,
selector,
limit: options.limit || 0,
optional: !!options.optional,
includeSelf,
animation,
originalSelector: metadata.selector,
options: normalizeAnimationOptions(metadata.options)
};
}
visitStagger(metadata, context) {
if (!context.currentQuery) {
context.errors.push(invalidStagger());
}
const timings = metadata.timings === 'full' ?
{ duration: 0, delay: 0, easing: 'full' } :
resolveTiming(metadata.timings, context.errors, true);
return {
type: 12 /* AnimationMetadataType.Stagger */,
animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context),
timings,
options: null
};
}
}
function normalizeSelector(selector) {
const hasAmpersand = selector.split(/\s*,\s*/).find(token => token == SELF_TOKEN) ? true : false;
if (hasAmpersand) {
selector = selector.replace(SELF_TOKEN_REGEX, '');
}
// Note: the :enter and :leave aren't normalized here since those
// selectors are filled in at runtime during timeline building
selector = selector.replace(/@\*/g, NG_TRIGGER_SELECTOR)
.replace(/@\w+/g, match =>