From c11cb1221f02bf3d0bd8612b8910c0a6c9448953 Mon Sep 17 00:00:00 2001 From: Mehdi Kazemi Date: Wed, 12 Oct 2022 13:58:03 -0400 Subject: [PATCH 1/5] Support anonymous scroll timeline in animation shorthand --- ...s-scroll-timeline-animation-shorthand.html | 52 +++++++++++++ dist/scroll-timeline.js.map | 2 +- dist/scroll-timeline.modern.js | 2 + dist/scroll-timeline.modern.js.map | 1 + index.html | 5 +- src/scroll-timeline-css-parser.js | 75 ++++++++++++------- src/scroll-timeline-css.js | 4 + 7 files changed, 111 insertions(+), 30 deletions(-) create mode 100644 demo/basic/anonymous-scroll-timeline-animation-shorthand.html create mode 100644 dist/scroll-timeline.modern.js create mode 100644 dist/scroll-timeline.modern.js.map diff --git a/demo/basic/anonymous-scroll-timeline-animation-shorthand.html b/demo/basic/anonymous-scroll-timeline-animation-shorthand.html new file mode 100644 index 00000000..f58d4097 --- /dev/null +++ b/demo/basic/anonymous-scroll-timeline-animation-shorthand.html @@ -0,0 +1,52 @@ + +Anonymous Scroll Progress Timeline + + + + + +
+
+
+
+ + + diff --git a/dist/scroll-timeline.js.map b/dist/scroll-timeline.js.map index ad93cac2..52f712a0 100644 --- a/dist/scroll-timeline.js.map +++ b/dist/scroll-timeline.js.map @@ -1 +1 @@ -{"version":3,"file":"scroll-timeline.js","sources":["../src/proxy-cssom.js","../src/scroll-timeline-base.js","../src/proxy-animation.js","../src/scroll-timeline-css-parser.js","../src/scroll-timeline-css.js","../src/index.js"],"sourcesContent":["// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nexport function installCSSOM() {\n // Object for storing details associated with an object which are to be kept\n // private. This approach allows the constructed objects to more closely\n // resemble their native counterparts when inspected.\n let privateDetails = new WeakMap();\n\n function displayUnit(unit) {\n switch(unit) {\n case 'percent':\n return '%';\n case 'number':\n return '';\n default:\n return unit.toLowerCase();\n }\n }\n\n function toCssUnitValue(v) {\n if (typeof v === 'number')\n return new CSSUnitValue(v, 'number');\n return v;\n }\n\n function toCssNumericArray(values) {\n const result = [];\n for (let i = 0; i < values.length; i++) {\n result[i] = toCssUnitValue(values[i]);\n }\n return result;\n }\n\n class MathOperation {\n constructor(values, operator, opt_name, opt_delimiter) {\n privateDetails.set(this, {\n values: toCssNumericArray(values),\n operator: operator,\n name: opt_name || operator,\n delimiter: opt_delimiter || ', '\n });\n }\n\n get operator() {\n return privateDetails.get(this).operator;\n }\n\n get values() {\n return privateDetails.get(this).values;\n }\n\n toString() {\n const details = privateDetails.get(this);\n return `${details.name}(${details.values.join(details.delimiter)})`;\n }\n }\n\n const cssOMTypes = {\n 'CSSUnitValue': class {\n constructor(value, unit) {\n privateDetails.set(this, {\n value: value,\n unit: unit\n });\n }\n\n get value() {\n return privateDetails.get(this).value;\n }\n\n set value(value) {\n privateDetails.get(this).value = value;\n }\n\n get unit() {\n return privateDetails.get(this).unit;\n }\n\n toString() {\n const details = privateDetails.get(this);\n return `${details.value}${displayUnit(details.unit)}`;\n }\n },\n\n 'CSSKeywordValue': class {\n constructor(value) {\n this.value = value;\n }\n\n toString() {\n return this.value.toString();\n }\n },\n\n 'CSSMathSum': class extends MathOperation {\n constructor(values) {\n super(arguments, 'sum', 'calc', ' + ');\n }\n },\n\n 'CSSMathProduct': class extends MathOperation {\n constructor(values) {\n super(arguments, 'product', 'calc', ' * ');\n }\n },\n\n 'CSSMathNegate': class extends MathOperation {\n constructor(values) {\n super([arguments[0]], 'negate', '-');\n }\n },\n\n 'CSSMathNegate': class extends MathOperation {\n constructor(values) {\n super([1, arguments[0]], 'invert', 'calc', ' / ');\n }\n },\n\n 'CSSMathMax': class extends MathOperation {\n constructor() {\n super(arguments, 'max');\n }\n },\n\n 'CSSMathMin': class extends MathOperation {\n constructor() {\n super(arguments, 'min');\n }\n }\n };\n\n if (!window.CSS) {\n if (!Reflect.defineProperty(window, 'CSS', { value: {} }))\n throw Error(`Error installing CSSOM support`);\n }\n\n if (!window.CSSUnitValue) {\n [\n 'number',\n 'percent',\n // Length units\n 'em',\n 'ex',\n 'px',\n 'cm',\n 'mm',\n 'in',\n 'pt',\n 'pc', // Picas\n 'Q', // Quarter millimeter\n 'vw',\n 'vh',\n 'vmin',\n 'vmax',\n 'rems',\n \"ch\",\n // Angle units\n 'deg',\n 'rad',\n 'grad',\n 'turn',\n // Time units\n 'ms',\n 's',\n 'Hz',\n 'kHz',\n // Resolution\n 'dppx',\n 'dpi',\n 'dpcm',\n // Other units\n \"fr\"\n ].forEach((name) => {\n const fn = (value) => {\n return new CSSUnitValue(value, name);\n };\n if (!Reflect.defineProperty(CSS, name, { value: fn }))\n throw Error(`Error installing CSS.${name}`);\n });\n }\n\n for (let type in cssOMTypes) {\n if (type in window)\n continue;\n if (!Reflect.defineProperty(window, type, { value: cssOMTypes[type] }))\n throw Error(`Error installing CSSOM support for ${type}`);\n }\n}\n","// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { parseLength } from \"./utils\";\n\nimport { installCSSOM } from \"./proxy-cssom.js\";\ninstallCSSOM();\n\nconst AUTO = new CSSKeywordValue(\"auto\");\n\nlet scrollTimelineOptions = new WeakMap();\nlet extensionScrollOffsetFunctions = [];\n\nfunction scrollEventSource(source) {\n if (source === document.scrollingElement) return document;\n return source;\n}\n\n/**\n * Updates the currentTime for all Web Animation instanced attached to a ScrollTimeline instance\n * @param scrollTimelineInstance {ScrollTimeline}\n */\nfunction updateInternal(scrollTimelineInstance) {\n validateSource(scrollTimelineInstance);\n const details = scrollTimelineOptions.get(scrollTimelineInstance);\n let animations = details.animations;\n if (animations.length === 0) return;\n let timelineTime = scrollTimelineInstance.currentTime;\n for (let i = 0; i < animations.length; i++) {\n animations[i].tickAnimation(timelineTime);\n }\n}\n\n/**\n * Calculates a scroll offset that corrects for writing modes, text direction\n * and a logical orientation.\n * @param scrollTimeline {ScrollTimeline}\n * @param orientation {String}\n * @returns {Number}\n */\nfunction directionAwareScrollOffset(source, orientation) {\n if (!source)\n return null;\n\n const style = getComputedStyle(source);\n // All writing modes are vertical except for horizontal-tb.\n // TODO: sideways-lr should flow bottom to top, but is currently unsupported\n // in Chrome.\n // http://drafts.csswg.org/css-writing-modes-4/#block-flow\n const horizontalWritingMode = style.writingMode == 'horizontal-tb';\n let currentScrollOffset = source.scrollTop;\n if (orientation == 'horizontal' ||\n (orientation == 'inline' && horizontalWritingMode) ||\n (orientation == 'block' && !horizontalWritingMode)) {\n // Negative values are reported for scrollLeft when the inline text\n // direction is right to left or for vertical text with a right to left\n // block flow. This is a consequence of shifting the scroll origin due to\n // changes in the overflow direction.\n // http://drafts.csswg.org/cssom-view/#overflow-directions.\n currentScrollOffset = Math.abs(source.scrollLeft);\n }\n return currentScrollOffset;\n}\n\n/**\n * Determines target effect end based on animation duration, iterations count and start and end delays\n * returned value should always be positive\n * @param options {Animation} animation\n * @returns {number}\n */\nexport function calculateTargetEffectEnd(animation) {\n return animation.effect.getComputedTiming().activeDuration;\n}\n\n/**\n * Calculates scroll offset based on orientation and source geometry\n * @param source {DOMElement}\n * @param orientation {String}\n * @returns {number}\n */\nexport function calculateMaxScrollOffset(source, orientation) {\n // Only one horizontal writing mode: horizontal-tb. All other writing modes\n // flow vertically.\n const horizontalWritingMode =\n getComputedStyle(source).writingMode == 'horizontal-tb';\n if (orientation === \"block\")\n orientation = horizontalWritingMode ? \"vertical\" : \"horizontal\";\n else if (orientation === \"inline\")\n orientation = horizontalWritingMode ? \"horizontal\" : \"vertical\";\n if (orientation === \"vertical\")\n return source.scrollHeight - source.clientHeight;\n else if (orientation === \"horizontal\")\n return source.scrollWidth - source.clientWidth;\n}\n\nfunction resolvePx(cssValue, resolvedLength) {\n if (cssValue instanceof CSSUnitValue) {\n if (cssValue.unit == \"percent\")\n return cssValue.value * resolvedLength / 100;\n else if (cssValue.unit == \"px\")\n return cssValue.value;\n else\n throw TypeError(\"Unhandled unit type \" + cssValue.unit);\n } else if (cssValue instanceof CSSMathSum) {\n let total = 0;\n for (let value of cssValue.values) {\n total += resolvePx(value, resolvedLength);\n }\n return total;\n }\n throw TypeError(\"Unsupported value type: \" + typeof(cssValue));\n}\n\n// Detects if the cached source is obsolete, and updates if required\n// to ensure the new source has a scroll listener.\nfunction validateSource(timeline) {\n if (!(timeline instanceof ViewTimeline)) {\n validateAnonymousSource(timeline);\n return;\n }\n\n const node = timeline.subject;\n if (!node) {\n updateSource(timeline, null);\n return;\n }\n\n const display = getComputedStyle(node).display;\n if (display == 'none') {\n updateSource(timeline, null);\n return;\n }\n\n const source = getScrollParent(node);\n updateSource(timeline, source);\n}\n\nfunction validateAnonymousSource(timeline) {\n const details = scrollTimelineOptions.get(timeline);\n if(!details.anonymousSource)\n return;\n\n const source = getAnonymousSourceElement(details.anonymousSource, details.anonymousTarget);\n updateSource(timeline, source);\n}\n\nfunction updateSource(timeline, source) {\n const details = scrollTimelineOptions.get(timeline);\n const oldSource = details.source;\n const oldScrollListener = details.scrollListener;\n if (oldSource == source)\n return;\n\n if (oldSource && oldScrollListener) {\n scrollEventSource(oldSource).removeEventListener(\"scroll\",\n oldScrollListener);\n }\n scrollTimelineOptions.get(timeline).source = source;\n if (source) {\n const listener = () => {\n updateInternal(timeline);\n };\n scrollEventSource(source).addEventListener(\"scroll\", listener);\n details.scrollListener = listener;\n }\n}\n\n/**\n * Removes a Web Animation instance from ScrollTimeline\n * @param scrollTimeline {ScrollTimeline}\n * @param animation {Animation}\n * @param options {Object}\n */\nexport function removeAnimation(scrollTimeline, animation) {\n let animations = scrollTimelineOptions.get(scrollTimeline).animations;\n for (let i = 0; i < animations.length; i++) {\n if (animations[i].animation == animation) {\n animations.splice(i, 1);\n }\n }\n}\n\n/**\n * Attaches a Web Animation instance to ScrollTimeline.\n * @param scrollTimeline {ScrollTimeline}\n * @param animation {Animation}\n * @param tickAnimation {function(number)}\n */\nexport function addAnimation(scrollTimeline, animation, tickAnimation) {\n let animations = scrollTimelineOptions.get(scrollTimeline).animations;\n for (let i = 0; i < animations.length; i++) {\n if (animations[i].animation == animation)\n return;\n }\n\n animations.push({\n animation: animation,\n tickAnimation: tickAnimation\n });\n updateInternal(scrollTimeline);\n}\n\n// TODO: this is a private function used for unit testing add function\nexport function _getStlOptions(scrollTimeline) {\n return scrollTimelineOptions.get(scrollTimeline);\n}\n\nexport class ScrollTimeline {\n constructor(options) {\n scrollTimelineOptions.set(this, {\n source: null,\n orientation: \"block\",\n anonymousSource: (options ? options.anonymousSource : null),\n anonymousTarget: (options ? options.anonymousTarget : null),\n\n // View timeline\n subject: null,\n inset: (options ? options.inset : null),\n\n // Internal members\n animations: [],\n scrollListener: null\n });\n const source =\n options && options.source !== undefined ? options.source\n : document.scrollingElement;\n updateSource(this, source);\n this.orientation = (options && options.orientation) || \"block\";\n updateInternal(this);\n }\n\n set source(element) {\n updateSource(this, element);\n updateInternal(this);\n }\n\n get source() {\n return scrollTimelineOptions.get(this).source;\n }\n\n set orientation(orientation) {\n if (\n [\"block\", \"inline\", \"horizontal\", \"vertical\"].indexOf(orientation) === -1\n ) {\n throw TypeError(\"Invalid orientation\");\n }\n scrollTimelineOptions.get(this).orientation = orientation;\n updateInternal(this);\n }\n\n get orientation() {\n return scrollTimelineOptions.get(this).orientation;\n }\n\n get duration() {\n return CSS.percent(100);\n }\n\n get phase() {\n // Per https://drafts.csswg.org/scroll-animations-1/#phase-algorithm\n // Step 1\n const unresolved = null;\n // if source is null\n const container = this.source;\n if (!container) return \"inactive\";\n let scrollerStyle = getComputedStyle(container);\n\n // if source does not currently have a CSS layout box\n if (scrollerStyle.display == \"none\")\n return \"inactive\";\n\n // if source's layout box is not a scroll container\"\n if (container != document.scrollingElement &&\n (scrollerStyle.overflow == 'visible' ||\n scrollerStyle.overflow == \"clip\")) {\n return \"inactive\";\n }\n\n return \"active\"\n }\n\n get currentTime() {\n const unresolved = null;\n const container = this.source;\n if (!container) return unresolved;\n if (this.phase == 'inactive')\n return unresolved;\n\n const orientation = this.orientation;\n const scrollPos = directionAwareScrollOffset(container, orientation);\n const maxScrollPos = calculateMaxScrollOffset(container, orientation);\n\n return maxScrollPos > 0 ? CSS.percent(100 * scrollPos / maxScrollPos)\n : CSS.percent(100);\n }\n\n get __polyfill() {\n return true;\n }\n}\n\n// Methods for calculation of the containing block.\n// See https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block.\n\nfunction findClosestAncestor(element, matcher) {\n let candidate = element.parentElement;\n while(candidate != null) {\n if (matcher(candidate))\n return candidate;\n candidate = candidate.parentElement;\n }\n}\n\nexport function getAnonymousSourceElement(sourceType, node) {\n return sourceType == 'root' ? document.scrollingElement : getScrollParent(node);\n}\n\nfunction isBlockContainer(element) {\n const style = getComputedStyle(element);\n switch (style.display) {\n case 'block':\n case 'inline-block':\n case 'list-item':\n case 'table':\n case 'table-caption':\n case 'flow-root':\n case 'flex':\n case 'grid':\n return true;\n }\n\n return false;\n}\n\nfunction isFixedElementContainer(element) {\n const style = getComputedStyle(element);\n if (style.transform != 'none' || style.perspective != 'none')\n return true;\n\n if (style.willChange == 'transform' || style.willChange == 'perspective')\n return true;\n\n if (style.filter != 'none' || style.willChange == 'filter')\n return true;\n\n if (style.backdropFilter != 'none')\n return true;\n\n return false;\n}\n\nfunction isAbsoluteElementContainer(element) {\n const style = getComputedStyle(element);\n if (style.position != 'static')\n return true;\n\n return isFixedElementContainer(element);\n}\n\nfunction getContainingBlock(element) {\n switch (getComputedStyle(element).position) {\n case 'static':\n case 'relative':\n case 'sticky':\n return findClosestAncestor(element, isBlockContainer);\n\n case 'absolute':\n return findClosestAncestor(element, isAbsoluteElementContainer);\n\n case 'fixed':\n return findClosestAncestor(element, isFixedElementContainer);\n }\n}\n\nexport function getScrollParent(node) {\n if (!node)\n return undefined;\n\n while (node = getContainingBlock(node)) {\n const style = getComputedStyle(node);\n switch(style['overflow-x']) {\n case 'auto':\n case 'scroll':\n case 'hidden':\n // https://drafts.csswg.org/css-overflow-3/#overflow-propagation\n // The UA must apply the overflow from the root element to the viewport;\n // however, if the overflow is visible in both axis, then the overflow\n // of the first visible child body is applied instead.\n if (node == document.body &&\n getComputedStyle(document.scrollingElement).overflow == \"visible\")\n return document.scrollingElement;\n\n return node;\n }\n }\n return document.scrollingElement;\n}\n\n// ---- View timelines -----\n\n// Computes the scroll offsets corresponding to the [0, 100]% range for a\n// specific phase on a view timeline.\n// TODO: Track changes to determine when associated animations require their\n// timing to be renormalized.\nfunction range(timeline, phase) {\n const details = scrollTimelineOptions.get(timeline);\n\n const unresolved = null;\n if (timeline.phase === 'inactive')\n return unresolved;\n\n if (!(timeline instanceof ViewTimeline))\n return unresolved;\n\n // Compute the offset of the top-left corner of subject relative to\n // top-left corner of the container.\n const container = timeline.source;\n const target = timeline.subject;\n\n return calculateRange(phase, container, target, details.orientation, details.inset);\n}\n\nexport function calculateRange(phase, container, target, orientation, optionsInset) {\n let top = 0;\n let left = 0;\n let node = target;\n const ancestor = container.offsetParent;\n while (node && node != ancestor) {\n left += node.offsetLeft;\n top += node.offsetTop;\n node = node.offsetParent;\n }\n left -= container.offsetLeft + container.clientLeft;\n top -= container.offsetTop + container.clientTop;\n\n // Determine the view and container size based on the scroll direction.\n // The view position is the scroll position of the logical starting edge\n // of the view.\n const style = getComputedStyle(container);\n const horizontalWritingMode = style.writingMode == 'horizontal-tb';\n const rtl = style.direction == 'rtl' || style.writingMode == 'vertical-rl';\n let viewSize = undefined;\n let viewPos = undefined;\n let containerSize = undefined;\n if (orientation == 'horizontal' ||\n (orientation == 'inline' && horizontalWritingMode) ||\n (orientation == 'block' && !horizontalWritingMode)) {\n viewSize = target.clientWidth;\n viewPos = left;\n if (rtl)\n viewPos += container.scrollWidth - container.clientWidth;\n containerSize = container.clientWidth;\n } else {\n // TODO: support sideways-lr\n viewSize = target.clientHeight;\n viewPos = top;\n containerSize = container.clientHeight;\n }\n\n const inset = parseInset(optionsInset, containerSize);\n\n // Cover:\n // 0% progress represents the position at which the start border edge of the\n // element’s principal box coincides with the end edge of its view progress\n // visibility range.\n // 100% progress represents the position at which the end border edge of the\n // element’s principal box coincides with the start edge of its view progress\n // visibility range.\n const coverStartOffset = viewPos - containerSize + inset.end;\n const coverEndOffset = viewPos + viewSize - inset.start;\n\n // Contain:\n // The 0% progress represents the earlier of the following positions:\n // 1. The start border edge of the element’s principal box coincides with\n // the start edge of its view progress visibility range.\n // 2. The end border edge of the element’s principal box coincides with\n // the end edge of its view progress visibility range.\n // The 100% progress represents the greater of the following positions:\n // 1. The start border edge of the element’s principal box coincides with\n // the start edge of its view progress visibility range.\n // 2. The end border edge of the element’s principal box coincides with\n // the end edge of its view progress visibility range.\n const alignStartOffset = coverStartOffset + viewSize;\n const alignEndOffset = coverEndOffset - viewSize;\n const containStartOffset = Math.min(alignStartOffset, alignEndOffset);\n const containEndOffset = Math.max(alignStartOffset, alignEndOffset);\n\n // Enter and Exit bounds align with cover and contains bounds.\n\n let startOffset = undefined;\n let endOffset = undefined;\n\n switch(phase) {\n case 'cover':\n startOffset = coverStartOffset;\n endOffset = coverEndOffset;\n break;\n\n case 'contain':\n startOffset = containStartOffset;\n endOffset = containEndOffset;\n break;\n\n case 'enter':\n startOffset = coverStartOffset;\n endOffset = containStartOffset;\n break;\n\n case 'exit':\n startOffset = containEndOffset;\n endOffset = coverEndOffset;\n break;\n }\n\n return { start: startOffset, end: endOffset };\n}\n\nfunction parseInset(value, containerSize) {\n const inset = { start: 0, end: 0 };\n\n if(!value)\n return inset;\n\n const parts = value.split(' ');\n const insetParts = [];\n parts.forEach(part => {\n // TODO: Add support for relative lengths (e.g. em)\n if(part.endsWith(\"%\"))\n insetParts.push(containerSize / 100 * parseFloat(part));\n else if(part.endsWith(\"px\"))\n insetParts.push(parseFloat(part));\n else if(part === \"auto\")\n insetParts.push(0);\n });\n\n if (insetParts.length > 2) {\n throw TypeError(\"Invalid inset\");\n }\n\n if(insetParts.length == 1) {\n inset.start = insetParts[0];\n inset.end = insetParts[0];\n } else if(insetParts.length == 2) {\n inset.start = insetParts[0];\n inset.end = insetParts[1];\n }\n\n return inset;\n}\n\n// Calculate the fractional offset of a (phase, percent) pair relative to the\n// full cover range.\nexport function relativePosition(timeline, phase, percent) {\n const phaseRange = range(timeline, phase);\n const coverRange = range(timeline, 'cover');\n return calculateRelativePosition(phaseRange, percent, coverRange);\n}\n\nexport function calculateRelativePosition(phaseRange, percent, coverRange) {\n if (!phaseRange || !coverRange)\n return 0;\n\n const fraction = percent.value / 100;\n const offset =\n (phaseRange.end - phaseRange.start) * fraction + phaseRange.start;\n return (offset - coverRange.start) / (coverRange.end - coverRange.start);\n}\n\n// https://drafts.csswg.org/scroll-animations-1/rewrite#view-progress-timelines\nexport class ViewTimeline extends ScrollTimeline {\n // As specced, ViewTimeline has a subject and a source, but\n // ViewTimelineOptions only has source. Furthermore, there is a strict\n // relationship between subject and source (source is nearest scrollable\n // ancestor of subject).\n\n // Proceeding under the assumption that subject will be added to\n // ViewTimelineOptions. Inferring the source from the subject if not\n // explicitly set.\n constructor(options) {\n if (options.axis) {\n // Orientation called axis for a view timeline. Internally we can still\n // call this orientation, since the internal naming is not exposed.\n options.orientation = options.axis;\n }\n super(options);\n const details = scrollTimelineOptions.get(this);\n details.subject = options && options.subject ? options.subject : undefined;\n // TODO: Handle insets.\n\n validateSource(this);\n updateInternal(this);\n }\n\n get source() {\n validateSource(this);\n return scrollTimelineOptions.get(this).source;\n }\n\n set source(source) {\n throw new Error(\"Cannot set the source of a view timeline\");\n }\n\n get subject() {\n return scrollTimelineOptions.get(this).subject;\n }\n\n // The orientation is called \"axis\" for a view timeline.\n // Internally we still call it orientation.\n get axis() {\n return scrollTimelineOptions.get(this).orientation;\n }\n\n get currentTime() {\n const unresolved = null;\n const scrollPos = directionAwareScrollOffset(this.source, this.orientation);\n if (scrollPos == unresolved)\n return unresolved;\n\n const offsets = range(this, 'cover');\n if (!offsets)\n return unresolved;\n const progress =\n (scrollPos - offsets.start) / (offsets.end - offsets.start);\n\n return CSS.percent(100 * progress);\n }\n\n}\n","import {\n ScrollTimeline,\n addAnimation,\n removeAnimation,\n relativePosition\n} from \"./scroll-timeline-base\";\n\nconst nativeElementAnimate = window.Element.prototype.animate;\nconst nativeAnimation = window.Animation;\n\nexport const ANIMATION_DELAY_NAMES = ['enter', 'exit', 'cover', 'contain'];\n\nclass PromiseWrapper {\n constructor() {\n this.state = 'pending';\n this.nativeResolve = this.nativeReject = null;\n this.promise = new Promise((resolve, reject) => {\n this.nativeResolve = resolve;\n this.nativeReject = reject;\n });\n }\n resolve(value) {\n this.state = 'resolved';\n this.nativeResolve(value);\n }\n reject(reason) {\n this.state = 'rejected';\n // Do not report unhandled promise rejections.\n this.promise.catch(() => {});\n this.nativeReject(reason);\n }\n}\n\nfunction createReadyPromise(details) {\n details.readyPromise = new PromiseWrapper();\n // Trigger the pending task on the next animation frame.\n requestAnimationFrame(() => {\n const timelineTime = details.timeline.currentTime;\n if (timelineTime !== null)\n notifyReady(details);\n });\n}\n\nfunction createAbortError() {\n return new DOMException(\"The user aborted a request\", \"AbortError\");\n}\n\n// Converts a time from its internal representation to a percent. For a\n// monotonic timeline, time is reported as a double with implicit units of\n// milliseconds. For progress-based animations, times are reported as\n// percentages.\nfunction toCssNumberish(details, value) {\n if (value === null)\n return value;\n\n if (typeof value !== 'number') {\n throw new DOMException(\n `Unexpected value: ${value}. Cannot convert to CssNumberish`,\n \"InvalidStateError\");\n }\n\n const limit = effectEnd(details);\n const percent = limit ? 100 * value / limit : 0;\n return CSS.percent(percent);\n}\n\n// Covnerts a time to its internal representation. Progress-based animations\n// use times expressed as percentages. Each progress-based animation is backed\n// by a native animation with a document timeline in the polyfill. Thus, we\n// need to convert the timing from percent to milliseconds with implicit units.\nfunction fromCssNumberish(details, value) {\n if (!details.timeline) {\n // Document timeline\n if (value == null || typeof value === 'number')\n return value;\n\n const convertedTime = value.to('ms');\n if (convertTime)\n return convertedTime.value;\n\n throw new DOMException(\n \"CSSNumericValue must be either a number or a time value for \" +\n \"time based animations.\",\n \"InvalidStateError\");\n } else {\n // Scroll timeline.\n if (value === null)\n return value;\n\n if (value.unit === 'percent') {\n const duration = effectEnd(details);\n return value.value * duration / 100;\n }\n\n throw new DOMException(\n \"CSSNumericValue must be a percentage for progress based animations.\",\n \"NotSupportedError\");\n }\n}\n\nfunction normalizedTiming(details) {\n // Used normalized timing in the case of a progress-based animation or\n // specified timing with a document timeline. The normalizedTiming property\n // is initialized and cached when fetching the timing information.\n const timing = details.proxy.effect.getTiming();\n return details.normalizedTiming || timing;\n}\n\nfunction commitPendingPlay(details) {\n // https://drafts4.csswg.org/web-animations-2/#playing-an-animation-section\n // Refer to steps listed under \"Schedule a task to run ...\"\n\n const timelineTime = fromCssNumberish(details, details.timeline.currentTime);\n if (details.holdTime != null) {\n // A: If animation’s hold time is resolved,\n // A.1. Apply any pending playback rate on animation.\n // A.2. Let new start time be the result of evaluating:\n // ready time - hold time / playback rate for animation.\n // If the playback rate is zero, let new start time be simply ready\n // time.\n // A.3. Set the start time of animation to new start time.\n // A.4. If animation’s playback rate is not 0, make animation’s hold\n // time unresolved.\n applyPendingPlaybackRate(details);\n if (details.animation.playbackRate == 0) {\n details.startTime = timelineTime;\n } else {\n details.startTime\n = timelineTime -\n details.holdTime / details.animation.playbackRate;\n details.holdTime = null;\n }\n } else if (details.startTime !== null &&\n details.pendingPlaybackRate !== null) {\n // B: If animation’s start time is resolved and animation has a pending\n // playback rate,\n // B.1. Let current time to match be the result of evaluating:\n // (ready time - start time) × playback rate for animation.\n // B.2 Apply any pending playback rate on animation.\n // B.3 If animation’s playback rate is zero, let animation’s hold time\n // be current time to match.\n // B.4 Let new start time be the result of evaluating:\n // ready time - current time to match / playback rate\n // for animation.\n // If the playback rate is zero, let new start time be simply ready\n // time.\n // B.5 Set the start time of animation to new start time.\n const currentTimeToMatch =\n (timelineTime - details.startTime) * details.animation.playbackRate;\n applyPendingPlaybackRate(details);\n const playbackRate = details.animation.playbackRate;\n if (playbackRate == 0) {\n details.holdTime = null;\n details.startTime = timelineTime;\n } else {\n details.startTime = timelineTime - currentTimeToMatch / playbackRate;\n }\n }\n\n // 8.4 Resolve animation’s current ready promise with animation.\n if (details.readyPromise && details.readyPromise.state == 'pending')\n details.readyPromise.resolve(details.proxy);\n\n // 8.5 Run the procedure to update an animation’s finished state for\n // animation with the did seek flag set to false, and the\n // synchronously notify flag set to false.\n updateFinishedState(details, false, false);\n\n // Additional polyfill step to update the native animation's current time.\n syncCurrentTime(details);\n details.pendingTask = null;\n};\n\nfunction commitPendingPause(details) {\n // https://www.w3.org/TR/web-animations-1/#pausing-an-animation-section\n // Refer to steps listed under \"Schedule a task to run ...\"\n\n // 1. Let ready time be the time value of the timeline associated with\n // animation at the moment when the user agent completed processing\n // necessary to suspend playback of animation’s target effect.\n const readyTime = fromCssNumberish(details, details.timeline.currentTime);\n\n // 2. If animation’s start time is resolved and its hold time is not\n // resolved, let animation’s hold time be the result of evaluating\n // (ready time - start time) × playback rate.\n if (details.startTime != null && details.holdTime == null) {\n details.holdTime =\n (readyTime - details.startTime) * details.animation.playbackRate;\n }\n\n // 3. Apply any pending playback rate on animation.\n applyPendingPlaybackRate(details);\n\n // 4. Make animation’s start time unresolved.\n details.startTime = null;\n\n // 5. Resolve animation’s current ready promise with animation.\n details.readyPromise.resolve(details.proxy);\n\n // 6. Run the procedure to update an animation’s finished state for\n // animation with the did seek flag set to false, and the synchronously\n // notify flag set to false.\n updateFinishedState(details, false, false);\n\n // Additional polyfill step to update the native animation's current time.\n syncCurrentTime(details);\n details.pendingTask = null;\n};\n\nfunction commitFinishedNotification(details) {\n if (!details.finishedPromise || details.finishedPromise.state != 'pending')\n return;\n\n if (details.proxy.playState != 'finished')\n return;\n\n details.finishedPromise.resolve(details.proxy);\n\n details.animation.pause();\n\n // Event times are speced as doubles in web-animations-1.\n // Cannot dispatch a proxy to an event since the proxy is not a fully\n // transparent replacement. As a workaround, use a custom event and inject\n // the necessary getters.\n const finishedEvent =\n new CustomEvent('finish',\n { detail: {\n currentTime: details.proxy.currentTime,\n timelineTime: details.proxy.timeline.currentTime\n }});\n Object.defineProperty(finishedEvent, 'currentTime', {\n get: function() { return this.detail.currentTime; }\n });\n Object.defineProperty(finishedEvent, 'timelineTime', {\n get: function() { return this.detail.timelineTime; }\n });\n\n requestAnimationFrame(() => {\n queueMicrotask(() => {\n details.animation.dispatchEvent(finishedEvent);\n });\n });\n}\n\nfunction effectivePlaybackRate(details) {\n if (details.pendingPlaybackRate !== null)\n return details.pendingPlaybackRate;\n return details.animation.playbackRate;\n}\n\nfunction applyPendingPlaybackRate(details) {\n if (details.pendingPlaybackRate !== null) {\n details.animation.playbackRate = details.pendingPlaybackRate;\n details.pendingPlaybackRate = null;\n }\n}\n\nfunction calculateCurrentTime(details) {\n if (!details.timeline)\n return null;\n\n const timelineTime = fromCssNumberish(details, details.timeline.currentTime);\n if (timelineTime === null)\n return null;\n\n if (details.startTime === null)\n return null;\n\n let currentTime =\n (timelineTime - details.startTime) * details.animation.playbackRate;\n\n // Handle special case.\n if (currentTime == -0)\n currentTime = 0;\n\n return currentTime;\n}\n\nfunction calculateStartTime(details, currentTime) {\n if (!details.timeline)\n return null;\n\n const timelineTime = fromCssNumberish(details, details.timeline.currentTime);\n if (timelineTime == null)\n return null;\n\n return timelineTime - currentTime / details.animation.playbackRate;\n}\n\nfunction updateFinishedState(details, didSeek, synchronouslyNotify) {\n if (!details.timeline)\n return;\n\n // https://www.w3.org/TR/web-animations-1/#updating-the-finished-state\n // 1. Calculate the unconstrained current time. The dependency on did_seek is\n // required to accommodate timelines that may change direction. Without this\n // distinction, a once-finished animation would remain finished even when its\n // timeline progresses in the opposite direction.\n let unconstrainedCurrentTime =\n didSeek ? fromCssNumberish(details, details.proxy.currentTime)\n : calculateCurrentTime(details);\n\n // 2. Conditionally update the hold time.\n if (unconstrainedCurrentTime && details.startTime != null &&\n !details.proxy.pending) {\n // Can seek outside the bounds of the active effect. Set the hold time to\n // the unconstrained value of the current time in the event that this update\n // is the result of explicitly setting the current time and the new time\n // is out of bounds. An update due to a time tick should not snap the hold\n // value back to the boundary if previously set outside the normal effect\n // boundary. The value of previous current time is used to retain this\n // value.\n const playbackRate = effectivePlaybackRate(details);\n const upperBound = effectEnd(details);\n let boundary = details.previousCurrentTime;\n if (playbackRate > 0 && unconstrainedCurrentTime >= upperBound) {\n if (boundary === null || boundary < upperBound)\n boundary = upperBound;\n details.holdTime = didSeek ? unconstrainedCurrentTime : boundary;\n } else if (playbackRate < 0 && unconstrainedCurrentTime <= 0) {\n if (boundary == null || boundary > 0)\n boundary = 0;\n details.holdTime = didSeek ? unconstrainedCurrentTime : boundary;\n } else if (playbackRate != 0) {\n // Update start time and reset hold time.\n if (didSeek && details.holdTime !== null)\n details.startTime = calculateStartTime(details, details.holdTime);\n details.holdTime = null;\n }\n }\n\n // Additional step to ensure that the native animation has the same value for\n // current time as the proxy.\n syncCurrentTime(details);\n\n // 3. Set the previous current time.\n details.previousCurrentTime = fromCssNumberish(details,\n details.proxy.currentTime);\n\n // 4. Set the current finished state.\n const playState = details.proxy.playState;\n\n if (playState == 'finished') {\n if (!details.finishedPromise)\n details.finishedPromise = new PromiseWrapper();\n if (details.finishedPromise.state == 'pending') {\n // 5. Setup finished notification.\n if (synchronouslyNotify) {\n commitFinishedNotification(details);\n } else {\n Promise.resolve().then(() => {\n commitFinishedNotification(details);\n });\n }\n }\n } else {\n // 6. If not finished but the current finished promise is already resolved,\n // create a new promise.\n if (details.finishedPromise &&\n details.finishedPromise.state == 'resolved') {\n details.finishedPromise = new PromiseWrapper();\n }\n if (details.animation.playState != 'paused')\n details.animation.pause();\n }\n}\n\nfunction effectEnd(details) {\n // https://www.w3.org/TR/web-animations-1/#end-time\n const timing = normalizedTiming(details);\n const totalDuration =\n timing.delay + timing.endDelay + timing.iterations * timing.duration;\n\n return Math.max(0, totalDuration);\n}\n\nfunction hasActiveTimeline(details) {\n return !details.timeline || details.timeline.phase != 'inactive';\n}\n\nfunction syncCurrentTime(details) {\n if (!details.timeline)\n return;\n\n if (details.startTime !== null) {\n const timelineTime = details.timeline.currentTime;\n if (timelineTime == null)\n return;\n\n const timelineTimeMs = fromCssNumberish(details, timelineTime);\n\n setNativeCurrentTime(details,\n (timelineTimeMs - details.startTime) *\n details.animation.playbackRate);\n } else if (details.holdTime !== null) {\n setNativeCurrentTime(details, details.holdTime);\n }\n}\n\n// Sets the time of the underlying animation, nudging the time slightly if at\n// a scroll-timeline boundary to remain in the active phase.\nfunction setNativeCurrentTime(details, time) {\n const timeline = details.timeline;\n const playbackRate = details.animation.playbackRate;\n const atScrollTimelineBoundary =\n timeline.currentTime &&\n timeline.currentTime.value == (playbackRate < 0 ? 0 : 100);\n const delta =\n atScrollTimelineBoundary ? (playbackRate < 0 ? 0.001 : -0.001) : 0;\n\n details.animation.currentTime = time + delta;\n}\n\nfunction resetPendingTasks(details) {\n // https://www.w3.org/TR/web-animations-1/#reset-an-animations-pending-tasks\n\n // 1. If animation does not have a pending play task or a pending pause task,\n // abort this procedure.\n if (!details.pendingTask)\n return;\n\n // 2. If animation has a pending play task, cancel that task.\n // 3. If animation has a pending pause task, cancel that task.\n details.pendingTask = null;\n\n // 4. Apply any pending playback rate on animation.\n applyPendingPlaybackRate(details);\n\n // 5. Reject animation’s current ready promise with a DOMException named\n // \"AbortError\".\n details.readyPromise.reject(createAbortError());\n\n // 6. Let animation’s current ready promise be the result of creating a new\n // resolved Promise object.\n createReadyPromise(details);\n details.readyPromise.resolve(details.proxy);\n}\n\nfunction playInternal(details, autoRewind) {\n if (!details.timeline)\n return;\n\n // https://drafts.csswg.org/web-animations/#playing-an-animation-section.\n // 1. Let aborted pause be a boolean flag that is true if animation has a\n // pending pause task, and false otherwise.\n const abortedPause =\n details.proxy.playState == 'paused' && details.proxy.pending;\n\n // 2. Let has pending ready promise be a boolean flag that is initially\n // false.\n let hasPendingReadyPromise = false;\n\n // 3. Let seek time be a time value that is initially unresolved.\n let seekTime = null;\n\n // 4. Let has finite timeline be true if animation has an associated\n // timeline that is not monotonically increasing.\n // Note: this value will always true at this point in the polyfill.\n // Following steps are pruned based on the procedure for scroll\n // timelines.\n\n // 5. Perform the steps corresponding to the first matching condition from\n // the following, if any:\n //\n // 5a If animation’s effective playback rate > 0, the auto-rewind flag is\n // true and either animation’s:\n // current time is unresolved, or\n // current time < zero, or\n // current time >= target effect end,\n // 5a1. Set seek time to zero.\n //\n // 5b If animation’s effective playback rate < 0, the auto-rewind flag is\n // true and either animation’s:\n // current time is unresolved, or\n // current time ≤ zero, or\n // current time > target effect end,\n // 5b1. If associated effect end is positive infinity,\n // throw an \"InvalidStateError\" DOMException and abort these steps.\n // 5b2. Otherwise,\n // 5b2a Set seek time to animation's associated effect end.\n //\n // 5c If animation’s effective playback rate = 0 and animation’s current time\n // is unresolved,\n // 5c1. Set seek time to zero.\n let previousCurrentTime = fromCssNumberish(details,\n details.proxy.currentTime);\n\n // Resume of a paused animation after a timeline change snaps to the scroll\n // position.\n if (details.resetCurrentTimeOnResume) {\n previousCurrentTime = null;\n details.resetCurrentTimeOnResume = false;\n }\n\n const playbackRate = effectivePlaybackRate(details);\n const upperBound = effectEnd(details);\n if (playbackRate > 0 && autoRewind && (previousCurrentTime == null ||\n previousCurrentTime < 0 ||\n previousCurrentTime >= upperBound)) {\n seekTime = 0;\n } else if (playbackRate < 0 && autoRewind &&\n (previousCurrentTime == null || previousCurrentTime <= 0 ||\n previousCurrentTime > upperBound)) {\n if (upperBound == Infinity) {\n // Defer to native implementation to handle throwing the exception.\n details.animation.play();\n return;\n }\n seekTime = upperBound;\n } else if (playbackRate == 0 && previousCurrentTime == null) {\n seekTime = 0;\n }\n\n // 6. If seek time is resolved,\n // 6a1. Set animation's start time to seek time.\n // 6a2. Let animation's hold time be unresolved.\n // 6a3. Apply any pending playback rate on animation.\n if (seekTime != null) {\n details.startTime = seekTime;\n details.holdTime = null;\n applyPendingPlaybackRate(details);\n }\n\n // Additional step for the polyfill.\n addAnimation(details.timeline, details.animation,\n tickAnimation.bind(details.proxy));\n\n // 7. If animation's hold time is resolved, let its start time be\n // unresolved.\n if (details.holdTime) {\n details.startTime = null;\n }\n\n // 8. If animation has a pending play task or a pending pause task,\n // 8.1 Cancel that task.\n // 8.2 Set has pending ready promise to true.\n if (details.pendingTask) {\n details.pendingTask = null;\n hasPendingReadyPromise = true;\n }\n\n // 9. If the following three conditions are all satisfied:\n // animation’s hold time is unresolved, and\n // seek time is unresolved, and\n // aborted pause is false, and\n // animation does not have a pending playback rate,\n // abort this procedure.\n if (details.holdTime === null && seekTime === null &&\n !abortedPause && details.pendingPlaybackRate === null)\n return;\n\n // 10. If has pending ready promise is false, let animation’s current ready\n // promise be a new promise in the relevant Realm of animation.\n if (details.readyPromise && !hasPendingReadyPromise)\n details.readyPromise = null;\n\n // Additional polyfill step to ensure that the native animation has the\n // correct value for current time.\n syncCurrentTime(details);\n\n // 11. Schedule a task to run as soon as animation is ready.\n if (!details.readyPromise)\n createReadyPromise(details);\n details.pendingTask = 'play';\n\n // 12. Run the procedure to update an animation’s finished state for animation\n // with the did seek flag set to false, and the synchronously notify flag\n // set to false.\n updateFinishedState(details, /* seek */ false, /* synchronous */ false);\n}\n\nfunction tickAnimation(timelineTime) {\n const details = proxyAnimations.get(this);\n if (timelineTime == null) {\n // While the timeline is inactive, it's effect should not be applied.\n // To polyfill this behavior, we cancel the underlying animation.\n if (details.animation.playState != 'idle')\n details.animation.cancel();\n return;\n }\n\n if (details.pendingTask) {\n notifyReady(details);\n }\n\n const playState = this.playState;\n if (playState == 'running' || playState == 'finished') {\n const timelineTimeMs = fromCssNumberish(details, timelineTime);\n\n setNativeCurrentTime(\n details,\n (timelineTimeMs - fromCssNumberish(details, this.startTime)) *\n this.playbackRate);\n\n // Conditionally reset the hold time so that the finished state can be\n // properly recomputed.\n if (playState == 'finished' && effectivePlaybackRate(details) != 0)\n details.holdTime = null;\n updateFinishedState(details, false, false);\n }\n}\n\nfunction notifyReady(details) {\n if (details.pendingTask == 'pause') {\n commitPendingPause(details);\n } else if (details.pendingTask == 'play') {\n commitPendingPlay(details);\n }\n}\n\nfunction createProxyEffect(details) {\n const effect = details.animation.effect;\n const nativeUpdateTiming = effect.updateTiming;\n\n // Generic pass-through handler for any method or attribute that is not\n // explicitly overridden.\n const handler = {\n get: function(obj, prop) {\n const result = obj[prop];\n if (typeof result === 'function')\n return result.bind(effect);\n return result;\n },\n\n set: function(obj, prop, value) {\n obj[prop] = value;\n return true;\n }\n };\n // Override getComputedTiming to convert to percentages when using a\n // progress-based timeline.\n const getComputedTimingHandler = {\n apply: function(target) {\n // Ensure that the native animation is using normalized values.\n effect.getTiming();\n\n const timing = target.apply(effect);\n\n if (details.timeline) {\n const preConvertLocalTime = timing.localTime;\n timing.localTime = toCssNumberish(details, timing.localTime);\n timing.endTime = toCssNumberish(details, timing.endTime);\n timing.activeDuration =\n toCssNumberish(details, timing.activeDuration);\n const limit = effectEnd(details);\n const iteration_duration = timing.iterations ?\n (limit - timing.delay - timing.endDelay) / timing.iterations : 0;\n timing.duration = limit ?\n CSS.percent(100 * iteration_duration / limit) :\n CSS.percent(0);\n\n // Correct for inactive timeline.\n if (details.timeline.currentTime === undefined) {\n timing.localTime = null;\n }\n }\n return timing;\n }\n };\n // Override getTiming to normalize the timing. EffectEnd for the animation\n // align with the timeline duration.\n const getTimingHandler = {\n apply: function(target, thisArg) {\n // Arbitrary conversion of 100% to ms.\n const INTERNAL_DURATION_MS = 100000;\n\n if (details.specifiedTiming)\n return details.specifiedTiming;\n\n details.specifiedTiming = target.apply(effect);\n let timing = Object.assign({}, details.specifiedTiming);\n\n const timeline = details.timeline;\n let computedDelays = false;\n let startDelay;\n let endDelay;\n if (timeline instanceof ViewTimeline) {\n // Compute start and end delay to align with start and end times.\n // If times not specified use cover 0% to cover 100%.\n startDelay = fractionalStartDelay(details);\n endDelay = fractionalEndDelay(details);\n computedDelays = true;\n }\n\n let totalDuration;\n\n // Duration 'auto' case.\n if (timing.duration === null || timing.duration === 'auto' ||\n computedDelays) {\n if (details.timeline) {\n if (computedDelays) {\n timing.delay = startDelay * INTERNAL_DURATION_MS;\n timing.endDelay = endDelay * INTERNAL_DURATION_MS;\n } else {\n // TODO: start and end delay are specced as doubles and currently\n // ignored for a progress based animation. Support delay and endDelay\n // once CSSNumberish.\n timing.delay = 0;\n timing.endDelay = 0;\n }\n totalDuration = timing.iterations ? INTERNAL_DURATION_MS : 0;\n timing.duration = timing.iterations\n ? (totalDuration - timing.delay - timing.endDelay) /\n timing.iterations\n : 0;\n // Set the timing on the native animation to the normalized values\n // while preserving the specified timing.\n nativeUpdateTiming.apply(effect, [timing]);\n }\n }\n details.normalizedTiming = timing;\n return details.specifiedTiming;\n }\n };\n const updateTimingHandler = {\n apply: function(target, thisArg, argumentsList) {\n // Additional validation that is specific to scroll timelines.\n if (details.timeline) {\n const options = argumentsList[0];\n const duration = options.duration;\n if (duration === Infinity) {\n throw TypeError(\n \"Effect duration cannot be Infinity when used with Scroll \" +\n \"Timelines\");\n }\n const iterations = options.iterations;\n if (iterations === Infinity) {\n throw TypeError(\n \"Effect iterations cannot be Infinity when used with Scroll \" +\n \"Timelines\");\n }\n }\n\n // Apply updates on top of the original specified timing.\n if (details.specifiedTiming) {\n target.apply(effect, [details.specifiedTiming]);\n }\n target.apply(effect, argumentsList);\n // Force renormalization.\n details.specifiedTiming = null;\n }\n };\n const proxy = new Proxy(effect, handler);\n proxy.getComputedTiming = new Proxy(effect.getComputedTiming,\n getComputedTimingHandler);\n proxy.getTiming = new Proxy(effect.getTiming, getTimingHandler);\n proxy.updateTiming = new Proxy(effect.updateTiming, updateTimingHandler);\n return proxy;\n}\n\n// Computes the start delay as a fraction of the active cover range.\nfunction fractionalStartDelay(details) {\n if (!(details.timeline instanceof ViewTimeline))\n return 0;\n\n const startTime = details.timeRange.start;\n return relativePosition(details.timeline, startTime.name, startTime.offset);\n}\n\n// Computes the ends delay as a fraction of the active cover range.\nfunction fractionalEndDelay(details) {\n if (!(details.timeline instanceof ViewTimeline))\n return 0;\n\n const endTime = details.timeRange.end;\n return 1 - relativePosition(details.timeline, endTime.name, endTime.offset);\n}\n\n// Create an alternate Animation class which proxies API requests.\n// TODO: Create a full-fledged proxy so missing methods are automatically\n// fetched from Animation.\nlet proxyAnimations = new WeakMap();\n\nexport class ProxyAnimation {\n constructor(effect, timeline, animOptions={}) {\n const animation =\n (effect instanceof nativeAnimation) ?\n effect : new nativeAnimation(effect, animationTimeline);\n const isScrollAnimation = timeline instanceof ScrollTimeline;\n const animationTimeline = isScrollAnimation ? undefined : timeline;\n proxyAnimations.set(this, {\n animation: animation,\n timeline: isScrollAnimation ? timeline : undefined,\n playState: isScrollAnimation ? \"idle\" : null,\n readyPromise: null,\n finishedPromise: null,\n // Start and hold times are directly tracked in the proxy despite being\n // accessible via the animation so that direct manipulation of these\n // properties does not affect the play state of the underlying animation.\n // Note that any changes to these values require an update of current\n // time for the underlying animation to ensure that its hold time is set\n // to the correct position. These values are represented as floating point\n // numbers in milliseconds.\n startTime: null,\n holdTime: null,\n previousCurrentTime: null,\n // When changing the timeline on a paused animation, we defer updating the\n // start time until the animation resumes playing.\n resetCurrentTimeOnResume: false,\n // Calls to reverse and updatePlaybackRate set a pending rate that does\n // not immediately take effect. The value of this property is\n // inaccessible via the web animations API and therefore explicitly\n // tracked.\n pendingPlaybackRate: null,\n pendingTask: null,\n // Record the specified timing since it may be different than the timing\n // actually used for the animation. When fetching the timing, this value\n // will be returned, however, the native animation will use normalized\n // values.\n specifiedTiming: null,\n // The normalized timing has the corrected timing with the intrinsic\n // iteration duration resolved.\n normalizedTiming: null,\n // Effect proxy that performs the necessary time conversions when using a\n // progress-based timelines.\n effect: null,\n // Range when using a view-timeline. The default range is cover 0% to\n // 100%.\n timeRange: timeline instanceof ViewTimeline ? parseAnimationDelays(animOptions) : null,\n proxy: this\n });\n }\n\n // -----------------------------------------\n // Web animation API\n // -----------------------------------------\n\n get effect() {\n const details = proxyAnimations.get(this);\n if (!details.timeline)\n return details.animation.effect;\n\n // Proxy the effect to support timing conversions for progress based\n // animations.\n if (!details.effect)\n details.effect = createProxyEffect(details);\n\n return details.effect;\n }\n set effect(newEffect) {\n proxyAnimations.get(this).animation.effect = newEffect;\n // Reset proxy to force re-initialization the next time it is accessed.\n details.effect = null;\n }\n\n get timeline() {\n const details = proxyAnimations.get(this);\n // If we explicitly set a null timeline we will return the underlying\n // animation's timeline.\n return details.timeline || details.animation.timeline;\n }\n set timeline(newTimeline) {\n // https://drafts4.csswg.org/web-animations-2/#setting-the-timeline\n\n // 1. Let old timeline be the current timeline of animation, if any.\n // 2. If new timeline is the same object as old timeline, abort this\n // procedure.\n const oldTimeline = this.timeline;\n if (oldTimeline == newTimeline)\n return;\n\n // 3. Let previous play state be animation’s play state.\n const previousPlayState = this.playState;\n\n // 4. Let previous current time be the animation’s current time.\n const previousCurrentTime = this.currentTime;\n\n const details = proxyAnimations.get(this);\n const end = effectEnd(details);\n const progress =\n end > 0 ? fromCssNumberish(details, previousCurrentTime) / end : 0;\n\n // 5. Let from finite timeline be true if old timeline is not null and not\n // monotonically increasing.\n const fromScrollTimeline = (oldTimeline instanceof ScrollTimeline);\n\n // 6. Let to finite timeline be true if timeline is not null and not\n // monotonically increasing.\n const toScrollTimeline = (newTimeline instanceof ScrollTimeline);\n\n // 7. Let the timeline of animation be new timeline.\n // Cannot assume that the native implementation has mutable timeline\n // support. Deferring this step until we know that we are either\n // polyfilling, supporting natively, or throwing an error.\n\n // 8. Set the flag reset current time on resume to false.\n details.resetCurrentTimeOnResume = false;\n\n // Additional step required to track whether the animation was pending in\n // order to set up a new ready promise if needed.\n const pending = this.pending;\n\n if (fromScrollTimeline) {\n removeAnimation(details.timeline, details.animation);\n }\n\n // 9. Perform the steps corresponding to the first matching condition from\n // the following, if any:\n\n // If to finite timeline,\n if (toScrollTimeline) {\n // Deferred step 7.\n details.timeline = newTimeline;\n\n // 1. Apply any pending playback rate on animation\n applyPendingPlaybackRate(details);\n\n // 2. Let seek time be zero if playback rate >= 0, and animation’s\n // associated effect end otherwise.\n const seekTime =\n details.animation.playbackRate >= 0 ? 0 : effectEnd(details);\n\n // 3. Update the animation based on the first matching condition if any:\n switch (previousPlayState) {\n // If either of the following conditions are true:\n // * previous play state is running or,\n // * previous play state is finished\n // Set animation’s start time to seek time.\n case 'running':\n case 'finished':\n details.startTime = seekTime;\n // Additional polyfill step needed to associate the animation with\n // the scroll timeline.\n addAnimation(details.timeline, details.animation,\n tickAnimation.bind(this));\n break;\n\n // If previous play state is paused:\n // If previous current time is resolved:\n // * Set the flag reset current time on resume to true.\n // * Set start time to unresolved.\n // * Set hold time to previous current time.\n case 'paused':\n details.resetCurrentTimeOnResume = true;\n details.startTime = null;\n details.holdTime =\n fromCssNumberish(details, CSS.percent(100 * progress));\n break;\n\n // Oterwise\n default:\n details.holdTime = null;\n details.startTime = null;\n }\n\n // Additional steps required if the animation is pending as we need to\n // associate the pending promise with proxy animation.\n // Note: if the native promise already has an associated \"then\", we will\n // lose this association.\n if (pending) {\n if (!details.readyPromise ||\n details.readyPromise.state == 'resolved') {\n createReadyPromise(details);\n }\n if (previousPlayState == 'paused')\n details.pendingTask = 'pause';\n else\n details.pendingTask = 'play';\n }\n\n // Note that the following steps should apply when transitioning to\n // a monotonic timeline as well; however, we do not have a direct means\n // of applying the steps to the native animation.\n\n // 10. If the start time of animation is resolved, make animation’s hold\n // time unresolved. This step ensures that the finished play state of\n // animation is not “sticky” but is re-evaluated based on its updated\n // current time.\n if (details.startTime !== null)\n details.holdTime = null;\n\n // 11. Run the procedure to update an animation’s finished state for\n // animation with the did seek flag set to false, and the\n // synchronously notify flag set to false.\n updateFinishedState(details, false, false);\n return;\n }\n\n // To monotonic timeline.\n if (details.animation.timeline == newTimeline) {\n // Deferred step 7 from above. Clearing the proxy's timeline will\n // re-associate the proxy with the native animation.\n removeAnimation(details.timeline, details.animation);\n details.timeline = null;\n\n // If from finite timeline and previous current time is resolved,\n // Run the procedure to set the current time to previous current time.\n if (fromScrollTimeline) {\n if (previousCurrentTime !== null)\n details.animation.currentTime = progress * effectEnd(details);\n\n switch (previousPlayState) {\n case 'paused':\n details.animation.pause();\n break;\n\n case 'running':\n case 'finished':\n details.animation.play();\n }\n }\n } else {\n throw TypeError(\"Unsupported timeline: \" + newTimeline);\n }\n }\n\n get startTime() {\n const details = proxyAnimations.get(this);\n if (details.timeline)\n return toCssNumberish(details, details.startTime);\n\n return details.animation.startTime;\n }\n set startTime(value) {\n // https://drafts.csswg.org/web-animations/#setting-the-start-time-of-an-animation\n const details = proxyAnimations.get(this);\n value = fromCssNumberish(details, value);\n if (!details.timeline) {\n details.animation.startTime = value;\n return;\n }\n\n // 1. Let timeline time be the current time value of the timeline that\n // animation is associated with. If there is no timeline associated with\n // animation or the associated timeline is inactive, let the timeline\n // time be unresolved.\n const timelineTime = fromCssNumberish(details,\n details.timeline.currentTime);\n\n // 2. If timeline time is unresolved and new start time is resolved, make\n // animation’s hold time unresolved.\n if (timelineTime == null && details.startTime != null) {\n details.holdTime = null;\n // Clearing the hold time may have altered the value of current time.\n // Ensure that the underlying animations has the correct value.\n syncCurrentTime(details);\n }\n\n // 3. Let previous current time be animation’s current time.\n // Note: This is the current time after applying the changes from the\n // previous step which may cause the current time to become unresolved.\n const previousCurrentTime = fromCssNumberish(details, this.currentTime);\n\n // 4. Apply any pending playback rate on animation.\n applyPendingPlaybackRate(details);\n\n // 5. Set animation’s start time to new start time.\n details.startTime = value;\n\n // 6. Set the reset current time on resume flag to false.\n details.resetCurrentTimeOnResume = false;\n\n // 7. Update animation’s hold time based on the first matching condition\n // from the following,\n\n // If new start time is resolved,\n // If animation’s playback rate is not zero,\n // make animation’s hold time unresolved.\n\n // Otherwise (new start time is unresolved),\n // Set animation’s hold time to previous current time even if\n // previous current time is unresolved.\n\n if (details.startTime !== null && details.animation.playbackRate != 0)\n details.holdTime = null;\n else\n details.holdTime = previousCurrentTime;\n\n // 7. If animation has a pending play task or a pending pause task, cancel\n // that task and resolve animation’s current ready promise with\n // animation.\n if (details.pendingTask) {\n details.pendingTask = null;\n details.readyPromise.resolve(this);\n }\n\n // 8. Run the procedure to update an animation’s finished state for animation\n // with the did seek flag set to true, and the synchronously notify flag\n // set to false.\n updateFinishedState(details, true, false);\n\n // Ensure that currentTime is updated for the native animation.\n syncCurrentTime(details);\n }\n\n get currentTime() {\n const details = proxyAnimations.get(this);\n if (!details.timeline)\n return details.animation.currentTime;\n\n if (details.holdTime != null)\n return toCssNumberish(details, details.holdTime);\n\n return toCssNumberish(details, calculateCurrentTime(details));\n }\n set currentTime(value) {\n const details = proxyAnimations.get(this);\n value = fromCssNumberish(details, value);\n if (!details.timeline || value == null) {\n details.animation.currentTime = value;\n return;\n }\n\n // https://drafts.csswg.org/web-animations/#setting-the-current-time-of-an-animation\n const previouStartTime = details.startTime;\n const previousHoldTime = details.holdTime;\n const timelinePhase = details.timeline.phase;\n\n // Update either the hold time or the start time.\n if (details.holdTime !== null || details.startTime === null ||\n timelinePhase == 'inactive' || details.animation.playbackRate == 0) {\n // TODO: Support hold phase.\n details.holdTime = value;\n } else {\n details.startTime = calculateStartTime(details, value);\n }\n details.resetCurrentTimeOnResume = false;\n\n // Preserve invariant that we can only set a start time or a hold time in\n // the absence of an active timeline.\n if (timelinePhase == 'inactive')\n details.startTime = null;\n\n // Reset the previous current time.\n details.previousCurrentTime = null;\n\n // Synchronously resolve pending pause task.\n if (details.pendingTask == 'pause') {\n details.holdTime = value;\n applyPendingPlaybackRate(details);\n details.startTime = null;\n details.pendingTask = null;\n details.readyPromise.resolve(this);\n }\n\n // Update the finished state.\n updateFinishedState(details, true, false);\n }\n\n get playbackRate() {\n return proxyAnimations.get(this).animation.playbackRate;\n }\n set playbackRate(value) {\n const details = proxyAnimations.get(this);\n\n if (!details.timeline) {\n details.animation.playbackRate = value;\n return;\n }\n\n // 1. Clear any pending playback rate on animation.\n details.pendingPlaybackRate = null;\n\n // 2. Let previous time be the value of the current time of animation before\n // changing the playback rate.\n const previousCurrentTime = this.currentTime;\n\n // 3. Set the playback rate to new playback rate.\n details.animation.playbackRate = value;\n\n // 4. If previous time is resolved, set the current time of animation to\n // previous time\n if (previousCurrentTime !== null)\n this.currentTime = previousCurrentTime;\n }\n\n get playState() {\n const details = proxyAnimations.get(this);\n if (!details.timeline)\n return details.animation.playState;\n\n const currentTime = fromCssNumberish(details, this.currentTime);\n\n // 1. All of the following conditions are true:\n // * The current time of animation is unresolved, and\n // * the start time of animation is unresolved, and\n // * animation does not have either a pending play task or a pending pause\n // task,\n // then idle.\n if (currentTime === null && details.startTime === null &&\n details.pendingTask == null)\n return 'idle';\n\n // 2. Either of the following conditions are true:\n // * animation has a pending pause task, or\n // * both the start time of animation is unresolved and it does not have a\n // pending play task,\n // then paused.\n if (details.pendingTask == 'pause' ||\n (details.startTime === null && details.pendingTask != 'play'))\n return 'paused';\n\n // 3. For animation, current time is resolved and either of the following\n // conditions are true:\n // * animation’s effective playback rate > 0 and current time >= target\n // effect end; or\n // * animation’s effective playback rate < 0 and current time <= 0,\n // then finished.\n if (currentTime != null) {\n if (details.animation.playbackRate > 0 &&\n currentTime >= effectEnd(details))\n return 'finished';\n if (details.animation.playbackRate < 0 && currentTime <= 0)\n return 'finished';\n }\n\n // 4. Otherwise\n return 'running';\n }\n get replaceState() {\n // TODO: Fix me. Replace state is not a boolean.\n return proxyAnimations.get(this).animation.pending;\n }\n\n get pending() {\n const details = proxyAnimations.get(this);\n if (details.timeline) {\n return !!details.readyPromise &&\n details.readyPromise.state == 'pending';\n }\n\n return details.animation.pending;\n }\n\n finish() {\n const details = proxyAnimations.get(this);\n if (!details.timeline) {\n details.animation.finish();\n return;\n }\n\n // 1. If animation’s effective playback rate is zero, or if animation’s\n // effective playback rate > 0 and target effect end is infinity, throw\n // an InvalidStateError and abort these steps.\n const playbackRate = effectivePlaybackRate(details);\n const duration = effectEnd(details);\n if (playbackRate == 0) {\n throw new DOMException(\n \"Cannot finish Animation with a playbackRate of 0.\",\n \"InvalidStateError\");\n }\n if (playbackRate > 0 && duration == Infinity) {\n throw new DOMException(\n \"Cannot finish Animation with an infinite target effect end.\",\n \"InvalidStateError\");\n }\n\n // 2. Apply any pending playback rate to animation.\n applyPendingPlaybackRate(details);\n\n // 3. Set limit as follows:\n // If playback rate > 0,\n // Let limit be target effect end.\n // Otherwise,\n // Let limit be zero.\n const limit = playbackRate < 0 ? 0 : duration;\n\n // 4. Silently set the current time to limit.\n this.currentTime = toCssNumberish(details, limit);\n\n // 5. If animation’s start time is unresolved and animation has an\n // associated active timeline, let the start time be the result of\n // evaluating\n // timeline time - (limit / playback rate)\n // where timeline time is the current time value of the associated\n // timeline.\n const timelineTime = fromCssNumberish(details,\n details.timeline.currentTime);\n\n if (details.startTime === null && timelineTime !== null) {\n details.startTime =\n timelineTime - (limit / details.animation.playbackRate);\n }\n\n // 6. If there is a pending pause task and start time is resolved,\n // 6.1 Let the hold time be unresolved.\n // 6.2 Cancel the pending pause task.\n // 6.3 Resolve the current ready promise of animation with animation.\n if (details.pendingTask == 'pause' && details.startTime !== null) {\n details.holdTime = null;\n details.pendingTask = null;\n details.readyPromise.resolve(this);\n }\n\n // 7. If there is a pending play task and start time is resolved, cancel\n // that task and resolve the current ready promise of animation with\n // animation.\n if (details.pendingTask == 'play' && details.startTime !== null) {\n details.pendingTask = null;\n details.readyPromise.resolve(this);\n }\n\n // 8. Run the procedure to update an animation’s finished state for\n // animation with the did seek flag set to true, and the synchronously\n // notify flag set to true.\n updateFinishedState(details, true, true);\n }\n\n play() {\n const details = proxyAnimations.get(this);\n if (!details.timeline) {\n details.animation.play();\n return;\n }\n\n playInternal(details, /* autoRewind */ true);\n }\n\n pause() {\n const details = proxyAnimations.get(this);\n if (!details.timeline) {\n details.animation.pause();\n return;\n }\n\n // https://www.w3.org/TR/web-animations-1/#pausing-an-animation-section\n\n // 1. If animation has a pending pause task, abort these steps.\n // 2. If the play state of animation is paused, abort these steps.\n if (this.playState == \"paused\")\n return;\n\n // 3. Let seek time be a time value that is initially unresolved.\n // 4. Let has finite timeline be true if animation has an associated\n // timeline that is not monotonically increasing.\n // Note: always true if we have reached this point in the polyfill.\n // Pruning following steps to be specific to scroll timelines.\n let seekTime = null;\n\n // 5. If the animation’s current time is unresolved, perform the steps\n // according to the first matching condition from below:\n // 5a. If animation’s playback rate is ≥ 0,\n // Set seek time to zero.\n // 5b. Otherwise,\n // If associated effect end for animation is positive infinity,\n // throw an \"InvalidStateError\" DOMException and abort these\n // steps.\n // Otherwise,\n // Set seek time to animation's associated effect end.\n\n const playbackRate = details.animation.playbackRate;\n const duration = effectEnd(details);\n\n if (details.animation.currentTime === null) {\n if (playbackRate >= 0) {\n seekTime = 0;\n } else if (duration == Infinity) {\n // Let native implementation take care of throwing the exception.\n details.animation.pause();\n return;\n } else {\n seekTime = duration;\n }\n }\n\n // 6. If seek time is resolved,\n // If has finite timeline is true,\n // Set animation's start time to seek time.\n if (seekTime !== null)\n details.startTime = seekTime;\n\n // 7. Let has pending ready promise be a boolean flag that is initially\n // false.\n // 8. If animation has a pending play task, cancel that task and let has\n // pending ready promise be true.\n // 9. If has pending ready promise is false, set animation’s current ready\n // promise to a new promise in the relevant Realm of animation.\n if (details.pendingTask == 'play')\n details.pendingTask = null;\n else\n details.readyPromise = null;\n\n // 10. Schedule a task to be executed at the first possible moment after the\n // user agent has performed any processing necessary to suspend the\n // playback of animation’s target effect, if any.\n if (!details.readyPromise)\n createReadyPromise(details);\n details.pendingTask ='pause';\n }\n\n reverse() {\n const details = proxyAnimations.get(this);\n const playbackRate = effectivePlaybackRate(details);\n const previousCurrentTime =\n details.resetCurrentTimeOnResume ?\n null : fromCssNumberish(details, this.currentTime);\n const inifiniteDuration = effectEnd(details) == Infinity;\n\n // Let the native implementation handle throwing the exception in cases\n // where reversal is not possible. Error cases will not change the state\n // of the native animation.\n const reversable =\n (playbackRate != 0) &&\n (playbackRate < 0 || previousCurrentTime > 0 || !inifiniteDuration);\n if (!details.timeline || !reversable) {\n if (reversable)\n details.pendingPlaybackRate = -effectivePlaybackRate(details);\n details.animation.reverse();\n return;\n }\n\n if (details.timeline.phase == 'inactive') {\n throw new DOMException(\n \"Cannot reverse an animation with no active timeline\",\n \"InvalidStateError\");\n }\n\n this.updatePlaybackRate(-playbackRate);\n playInternal(details, /* autoRewind */ true);\n }\n\n updatePlaybackRate(rate) {\n const details = proxyAnimations.get(this);\n details.pendingPlaybackRate = rate;\n if (!details.timeline) {\n details.animation.updatePlaybackRate(rate);\n return;\n }\n\n // https://drafts.csswg.org/web-animations/#setting-the-playback-rate-of-an-animation\n\n // 1. Let previous play state be animation’s play state.\n // 2. Let animation’s pending playback rate be new playback rate.\n // Step 2 already performed as we need to record it even when using a\n // monotonic timeline.\n const previousPlayState = this.playState;\n\n // 3. Perform the steps corresponding to the first matching condition from\n // below:\n //\n // 3a If animation has a pending play task or a pending pause task,\n // Abort these steps.\n if (details.readyPromise && details.readyPromise.state == 'pending')\n return;\n\n switch(previousPlayState) {\n // 3b If previous play state is idle or paused,\n // Apply any pending playback rate on animation.\n case 'idle':\n case 'paused':\n applyPendingPlaybackRate(details);\n break;\n\n // 3c If previous play state is finished,\n // 3c.1 Let the unconstrained current time be the result of calculating\n // the current time of animation substituting an unresolved time\n // value for the hold time.\n // 3c.2 Let animation’s start time be the result of evaluating the\n // following expression:\n // timeline time - (unconstrained current time / pending playback rate)\n // Where timeline time is the current time value of the timeline\n // associated with animation.\n // 3c.3 If pending playback rate is zero, let animation’s start time be\n // timeline time.\n // 3c.4 Apply any pending playback rate on animation.\n // 3c.5 Run the procedure to update an animation’s finished state for\n // animation with the did seek flag set to false, and the\n // synchronously notify flag set to false.\n\n case 'finished':\n const timelineTime = fromCssNumberish(details,\n details.timeline.currentTime);\n const unconstrainedCurrentTime = timelineTime !== null ?\n (timelineTime - details.startTime) * details.animation.playbackRate\n : null;\n if (rate == 0) {\n details.startTime = timelineTime;\n } else {\n details.startTime =\n timelineTime != null && unconstrainedCurrentTime != null ?\n (timelineTime - unconstrainedCurrentTime) / rate : null;\n }\n applyPendingPlaybackRate(details);\n updateFinishedState(details, false, false);\n syncCurrentTime(details);\n break;\n\n // 3d Otherwise,\n // Run the procedure to play an animation for animation with the\n // auto-rewind flag set to false.\n default:\n playInternal(details, false);\n }\n }\n\n persist() {\n proxyAnimations.get(this).animation.persist();\n }\n\n get id() {\n return proxyAnimations.get(this).animation.id;\n }\n\n cancel() {\n const details = proxyAnimations.get(this);\n if (!details.timeline) {\n details.animation.cancel();\n return;\n }\n\n // https://www.w3.org/TR/web-animations-1/#canceling-an-animation-section\n // 1. If animation’s play state is not idle, perform the following steps:\n // 1.1 Run the procedure to reset an animation’s pending tasks on\n // animation.\n // 1.2 Reject the current finished promise with a DOMException named\n // \"AbortError\"\n // 1.3 Let current finished promise be a new (pending) Promise object.\n // 1.4+ Deferred to native implementation.\n // TODO: polyfill since timelineTime will be incorrect for the\n // cancel event. Also, should avoid sending a cancel event if\n // the native animation is canceled due to the scroll timeline\n // becoming inactive. This can likely be done by associating\n // the cancel event with the proxy and not the underlying\n // animation.\n if (this.playState != 'idle') {\n resetPendingTasks(details);\n if (details.finishedPromise &&\n details.finishedPromise.state == 'pending') {\n details.finishedPromise.reject(createAbortError());\n }\n details.finishedPromise = new PromiseWrapper();\n details.animation.cancel();\n }\n\n // 2. Make animation’s hold time unresolved.\n // 3. Make animation’s start time unresolved.\n details.startTime = null;\n details.holdTime = null;\n\n // Extra step in the polyfill the ensure the animation stops ticking.\n removeAnimation(details.timeline, details.animation);\n }\n\n get onfinish() {\n return proxyAnimations.get(this).animation.onfinish;\n }\n set onfinish(value) {\n proxyAnimations.get(this).animation.onfinish = value;\n }\n get oncancel() {\n return proxyAnimations.get(this).animation.oncancel;\n }\n set oncancel(value) {\n proxyAnimations.get(this).animation.oncancel = value;\n }\n get onremove() {\n return proxyAnimations.get(this).animation.onremove;\n }\n set onremove(value) {\n proxyAnimations.get(this).animation.onremove = value;\n }\n\n get finished() {\n const details = proxyAnimations.get(this);\n if (!details.timeline)\n return details.animation.finished;\n\n if (!details.finishedPromise) {\n details.finishedPromise = new PromiseWrapper();\n }\n return details.finishedPromise.promise;\n }\n\n get ready() {\n const details = proxyAnimations.get(this);\n if (!details.timeline)\n return details.animation.ready;\n\n if (!details.readyPromise) {\n details.readyPromise = new PromiseWrapper();\n details.readyPromise.resolve(this);\n }\n return details.readyPromise.promise;\n }\n\n // --------------------------------------------------\n // Event target API\n // --------------------------------------------------\n\n addEventListener(type, callback, options) {\n proxyAnimations.get(this).animation.addEventListener(type, callback,\n options);\n }\n\n removeEventListener(type, callback, options) {\n proxyAnimations.get(this).animation.removeEventListener(type, callback,\n options);\n }\n\n dispatchEvent(event) {\n proxyAnimations.get(this).animation.dispatchEvent(event);\n }\n};\n\n// animation-delay or animation-end-delay should be in the form of a name and an optional percentage\nfunction parseOneAnimationDelay(delay, defaultOffset) {\n if(!delay) return null;\n\n const parts = delay.split(' ');\n\n if(!ANIMATION_DELAY_NAMES.includes(parts[0]) ||\n (parts.length == 2 && !parts[1].endsWith('%')))\n throw TypeError(\"Invalid animation delay\");\n\n let offset = defaultOffset;\n if(parts.length == 2) {\n const percentage = parseFloat(parts[1]);\n if(Number.isNaN(percentage))\n throw TypeError(`\\\"${parts[1]}\\\" is not a valid percentage for animation delay`);\n\n offset = CSS.percent(percentage);\n }\n\n return { name: parts[0], offset: offset };\n}\n\nfunction defaultAnimationDelay() { return { name: 'cover', offset: CSS.percent(0) }; }\n\nfunction defaultAnimationEndDelay() { return { name: 'cover', offset: CSS.percent(100) }; }\n\nfunction parseAnimationDelays(animOptions) {\n const timeRange = parseTimeRange(animOptions['animation-time-range']);\n\n if(animOptions['animation-delay'])\n timeRange.start = parseOneAnimationDelay(animOptions['animation-delay'], defaultAnimationDelay().offset);\n\n if(animOptions['animation-end-delay'])\n timeRange.end = parseOneAnimationDelay(animOptions['animation-end-delay'], defaultAnimationEndDelay().offset);\n\n return timeRange;\n}\n\nfunction parseTimeRange(value) {\n const timeRange = {\n start: defaultAnimationDelay(),\n end: defaultAnimationEndDelay()\n };\n\n if (!value)\n return timeRange;\n\n // Format:\n // \n // --> 0% 100%\n // --> \n // \n // --> cover cover \n // TODO: Support all formatting options once ratified in the spec.\n const parts = value.split(' ');\n const names = [];\n const offsets = [];\n\n parts.forEach(part => {\n if (part.endsWith('%'))\n offsets.push(parseFloat(part));\n else\n names.push(part);\n });\n\n if (names.length > 2 || offsets.length > 2 || offsets.length == 1) {\n throw TypeError(\"Invalid time range\");\n }\n\n if (names.length) {\n timeRange.start.name = names[0];\n timeRange.end.name = names.length > 1 ? names[1] : names[0];\n }\n\n if (offsets.length > 1) {\n timeRange.start.offset = CSS.percent(offsets[0]);\n timeRange.end.offset = CSS.percent(offsets[1]);\n }\n\n return timeRange;\n}\n\nexport function animate(keyframes, options) {\n const timeline = options.timeline;\n\n if (timeline instanceof ScrollTimeline)\n delete options.timeline;\n\n const timelineOffset = (options, property) => {\n if (property in options) {\n const value = options[property];\n if (typeof value != 'number') {\n delete options[property];\n return value;\n }\n return null;\n }\n };\n\n const updateDelay = (timelineOffset, value) => {\n if (!value)\n return;\n\n // TODO(kevers): Update property names once ratified.\n // https://github.com/w3c/csswg-drafts/issues/7589\n if (value.phase)\n timelineOffset.name = value.phase;\n\n if (value.percent)\n timelineOffset.offset = value.percent;\n };\n\n const delayTimelineOffset = timelineOffset(options, 'delay');\n const endDelayTimelineOffset = timelineOffset(options, 'endDelay');\n\n const animation = nativeElementAnimate.apply(this, [keyframes, options]);\n const proxyAnimation = new ProxyAnimation(animation, timeline);\n\n if (timeline instanceof ScrollTimeline) {\n animation.pause();\n if (timeline instanceof ViewTimeline) {\n const details = proxyAnimations.get(proxyAnimation);\n details.timeRange = parseTimeRange(options.timeRange);\n updateDelay(details.timeRange.start, delayTimelineOffset);\n updateDelay(details.timeRange.end, endDelayTimelineOffset);\n }\n proxyAnimation.play();\n }\n\n return proxyAnimation;\n};\n","import { ANIMATION_DELAY_NAMES } from './proxy-animation';\nimport { getAnonymousSourceElement } from './scroll-timeline-base';\n\n// This is also used in scroll-timeline-css.js\nexport const RegexMatcher = {\n IDENTIFIER: /[\\w\\\\\\@_-]+/g,\n WHITE_SPACE: /\\s*/g,\n NUMBER: /^[0-9]+/,\n TIME: /^[0-9]+(s|ms)/,\n VIEW_TIMELINE: /view-timeline\\s*:([^;}]+)/,\n VIEW_TIMELINE_NAME: /view-timeline-name\\s*:([^;}]+)/,\n VIEW_TIMELINE_AXIS: /view-timeline-axis\\s*:([^;}]+)/,\n ANIMATION_TIMELINE: /animation-timeline\\s*:([^;}]+)/,\n ANIMATION_DELAY: /animation-delay\\s*:([^;}]+)/,\n ANIMATION_END_DELAY: /animation-end-delay\\s*:([^;}]+)/,\n ANIMATION_TIME_RANGE: /animation-time-range\\s*:([^;}]+)/,\n ANIMATION_NAME: /animation-name\\s*:([^;}]+)/,\n ANIMATION: /animation\\s*:([^;}]+)/,\n SOURCE_ELEMENT: /selector\\(#([^)]+)\\)/,\n};\n\n// Used for ANIMATION_TIMELINE, ANIMATION_NAME and ANIMATION regex\nconst VALUES_CAPTURE_INDEX = 1;\n\nconst WHOLE_MATCH_INDEX = 0;\n\nconst ANIMATION_KEYWORDS = [\n 'normal', 'reverse', 'alternate', 'alternate-reverse',\n 'none', 'forwards', 'backwards', 'both',\n 'running', 'paused',\n 'ease', 'linear', 'ease-in', 'ease-out', 'ease-in-out'\n];\n\nconst TIMELINE_AXIS_TYPES = ['block', 'inline', 'vertical', 'horizontal'];\nconst ANONYMOUS_TIMELINE_SOURCE_TYPES = ['nearest', 'root'];\n\n// 1 - Extracts @scroll-timeline and saves it in scrollTimelineOptions.\n// 2 - If we find any animation-timeline in any of the CSS Rules, \n// we will save objects in a list named cssRulesWithTimelineName\nexport class StyleParser {\n constructor() {\n this.cssRulesWithTimelineName = [];\n this.scrollTimelineOptions = new Map(); // save options by name\n this.nextAnonymousTimelineNameIndex = 0;\n this.anonymousScrollTimelineOptions = new Map(); // save anonymous options by name\n this.subjectSelectorToViewTimeline = [];\n this.keyframeNamesSelectors = new Map();\n }\n\n // Inspired by\n // https://drafts.csswg.org/css-syntax/#parser-diagrams\n // https://github.com/GoogleChromeLabs/container-query-polyfill/blob/main/src/engine.ts\n // This function is called twice, in the first pass we are interested in saving\n // @scroll-timeline and @keyframe names, in the second pass\n // we will parse other rules\n transpileStyleSheet(sheetSrc, firstPass, srcUrl) {\n // AdhocParser\n const p = {\n sheetSrc: sheetSrc,\n index: 0,\n name: srcUrl,\n };\n\n while (p.index < p.sheetSrc.length) {\n this.eatWhitespace(p);\n if (p.index >= p.sheetSrc.length) break;\n if (this.lookAhead(\"/*\", p)) {\n while (this.lookAhead(\"/*\", p)) {\n this.eatComment(p);\n this.eatWhitespace(p);\n }\n continue;\n }\n\n if (this.lookAhead(\"@scroll-timeline\", p)) {\n const { scrollTimeline, startIndex, endIndex } = this.parseScrollTimeline(p);\n if (firstPass) this.scrollTimelineOptions.set(scrollTimeline.name, scrollTimeline);\n } else {\n const rule = this.parseQualifiedRule(p);\n if (!rule) continue;\n if (firstPass) {\n this.parseKeyframesAndSaveNameMapping(rule, p);\n } else {\n this.handleScrollTimelineProps(rule, p);\n }\n }\n }\n\n // If this sheet has no srcURL (like from a