{"version":3,"file":"scroll-timeline.js","sources":["../src/utils.js","../src/proxy-cssom.js","../src/scroll-timeline-base.js","../src/proxy-animation.js","../src/intersection-based-offset.js","../src/scroll-timeline-css-parser.js","../src/scroll-timeline-css.js","../src/index.js"],"sourcesContent":["export function parseLength(obj, acceptStr) {\n if (obj instanceof CSSUnitValue || obj instanceof CSSMathSum)\n return obj;\n if (!acceptStr)\n return null;\n let matches = obj.trim().match(/^(-?[0-9]*\\.?[0-9]*)(px|%)$/);\n if (matches) {\n let value = matches[1];\n // The unit for % is percent.\n let unit = matches[2] == '%' ? 'percent' : matches[2];\n return new CSSUnitValue(value, unit);\n }\n return null;\n}\n","// 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 let animations = scrollTimelineOptions.get(scrollTimelineInstance).animations;\n if (animations.length === 0) return;\n let timelineTime = scrollTimelineInstance.currentTime;\n\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 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 * Enables the usage of custom parser and evaluator function, utilized by intersection based offset.\n * @param parseFunction {Function}\n * @param evaluateFunction {Function}\n * @returns {Array} all currently installed parsers\n */\nexport function installScrollOffsetExtension(parseFunction, evaluateFunction) {\n extensionScrollOffsetFunctions.push({\n parse: parseFunction,\n evaluate: evaluateFunction,\n });\n return extensionScrollOffsetFunctions;\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(this.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\nexport function calculateScrollOffset(\n autoValue,\n source,\n orientation,\n offset,\n fn\n) {\n if (fn)\n return fn(\n source,\n orientation,\n offset,\n autoValue.value == 0 ? \"start\" : \"end\"\n );\n // TODO: Support other writing directions.\n if (orientation === \"block\") orientation = \"vertical\";\n else if (orientation === \"inline\") orientation = \"horizontal\";\n\n let maxValue =\n orientation === \"vertical\"\n ? source.scrollHeight - source.clientHeight\n : source.scrollWidth - source.clientWidth;\n let parsed = parseLength(offset === AUTO ? autoValue : offset);\n return resolvePx(parsed, maxValue);\n}\n\n/**\n * Resolve scroll offsets per\n * https://drafts.csswg.org/scroll-animations-1/#effective-scroll-offsets-algorithm\n * @param source {DOMElement}\n * @param orientation {String}\n * @param scrollOffsets {Array}\n * @param fns {Array}\n * @returns {Array}\n */\nexport function resolveScrollOffsets(\n source,\n orientation,\n scrollOffsets,\n fns\n) {\n // 1. Let effective scroll offsets be an empty list of effective scroll\n // offsets.\n let effectiveScrollOffsets = [];\n // 2. Let first offset be true.\n let firstOffset = true;\n\n // 3. If scrollOffsets is empty\n if(scrollOffsets.length == 0) {\n // 3.1 Run the procedure to resolve a scroll timeline offset for auto with\n // the is first flag set to first offset and add the resulted value into\n // effective scroll offsets.\n effectiveScrollOffsets.push(\n calculateScrollOffset(\n new CSSUnitValue(0, 'percent'),\n source,\n orientation,\n AUTO\n ));\n // 3.2 Set first offset to false.\n firstOffset = false;\n // 3.3 Run the procedure to resolve a scroll timeline offset for auto with\n // the is first flag set to first offset and add the resulted value into\n // effective scroll offsets.\n effectiveScrollOffsets.push(\n calculateScrollOffset(\n new CSSUnitValue(100, 'percent'),\n source,\n orientation,\n AUTO\n ));\n }\n // 4. If scrollOffsets has exactly one element\n else if(scrollOffsets.length == 1) {\n // 4.1 Run the procedure to resolve a scroll timeline offset for auto with\n // the is first flag set to first offset and add the resulted value into\n // effective scroll offsets.\n effectiveScrollOffsets.push(\n calculateScrollOffset(\n new CSSUnitValue(0, 'percent'),\n source,\n orientation,\n AUTO\n ));\n // 4.2 Set first offset to false.\n firstOffset = false;\n }\n // 5. For each scroll offset in the list of scrollOffsets, perform the\n // following steps:\n for (let i = 0; i < scrollOffsets.length; i++) {\n // 5.1 Let effective offset be the result of applying the procedure\n // to resolve a scroll timeline offset for scroll offset with the is\n // first flag set to first offset.\n let effectiveOffset = calculateScrollOffset(\n firstOffset ? new CSSUnitValue(0, 'percent') : new CSSUnitValue(100, 'percent'),\n source,\n orientation,\n scrollOffsets[i],\n fns[i]);\n // 5.2 If effective offset is null, the effective scroll offsets is empty and abort the remaining steps.\n if(effectiveOffset === null)\n return [];\n // 5.3 Add effective offset into effective scroll offsets.\n effectiveScrollOffsets.push(effectiveOffset);\n // 5.4 Set first offset to false.\n firstOffset = false;\n }\n // 6. Return effective scroll offsets.\n return effectiveScrollOffsets;\n}\n\n/**\n * Compute scroll timeline progress per\n * https://drafts.csswg.org/scroll-animations-1/#progress-calculation-algorithm\n * @param offset {number}\n * @param scrollOffsets {Array}\n * @returns {number}\n */\nexport function ComputeProgress(\n offset,\n scrollOffsets\n) {\n // 1. Let scroll offsets be the result of applying the procedure to resolve\n // scroll timeline offsets for scrollOffsets.\n // 2. Let offset index correspond to the position of the last offset in\n // scroll offsets whose value is less than or equal to offset and the value\n // at the following position greater than offset.\n let offsetIndex;\n for (offsetIndex = scrollOffsets.length - 2;\n offsetIndex >= 0 && \n !(scrollOffsets[offsetIndex] <= offset && offset < scrollOffsets[offsetIndex + 1]);\n offsetIndex--) {\n }\n // 3. Let start offset be the offset value at position offset index in\n // scroll offsets.\n let startOffset = scrollOffsets[offsetIndex];\n // 4. Let end offset be the value of next offset in scroll offsets after\n // start offset.\n let endOffset = scrollOffsets[offsetIndex + 1];\n // 5. Let size be the number of offsets in scroll offsets.\n let size = scrollOffsets.length;\n // 6. Let offset weight be the result of evaluating 1 / (size - 1).\n let offsetWeight = 1 / (size - 1);\n // 7. Let interval progress be the result of evaluating\n // (offset - start offset) / (end offset - start offset).\n let intervalProgress = (offset - startOffset) / (endOffset - startOffset);\n // 8. Return the result of evaluating\n // (offset index + interval progress) × offset weight.\n return (offsetIndex + intervalProgress) * offsetWeight;\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 scrollOffsets: [],\n\n // Internal members\n animations: [],\n scrollOffsetFns: [],\n });\n this.source =\n options && options.source !== undefined ? options.source : document.scrollingElement;\n this.orientation = (options && options.orientation) || \"block\";\n this.scrollOffsets = options && options.scrollOffsets !== undefined ? options.scrollOffsets : [];\n }\n\n set source(element) {\n if (this.source)\n scrollEventSource(this.source).removeEventListener(\"scroll\", () =>\n updateInternal(this)\n );\n scrollTimelineOptions.get(this).source = element;\n if (element) {\n scrollEventSource(element).addEventListener(\"scroll\", () =>\n updateInternal(this)\n );\n }\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 set scrollOffsets(value) {\n let offsets = [];\n let fns = [];\n for (let input of value) {\n let fn = null;\n let offset = undefined;\n if (input == \"auto\")\n input = AUTO;\n for (let i = 0; i < extensionScrollOffsetFunctions.length; i++) {\n let result = extensionScrollOffsetFunctions[i].parse(input);\n if (result !== undefined) {\n offset = result;\n fn = extensionScrollOffsetFunctions[i].evaluate;\n break;\n }\n }\n if (!fn) {\n if (input != AUTO) {\n let parsed = parseLength(input);\n // TODO: This should check CSSMathSum values as well.\n if (!parsed || (parsed instanceof CSSUnitValue && parsed.unit == \"number\"))\n throw TypeError(\"Invalid scrollOffsets entry.\");\n }\n offset = input;\n }\n offsets.push(offset);\n fns.push(fn);\n }\n if (offsets.length == 1 && offsets[0] == AUTO)\n throw TypeError(\"Invalid scrollOffsets value.\");\n let data = scrollTimelineOptions.get(this);\n data.scrollOffsets = offsets;\n data.scrollOffsetFns = fns;\n updateInternal(this);\n }\n\n get scrollOffsets() {\n let data = scrollTimelineOptions.get(this);\n return data.scrollOffsets;\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 let unresolved = null;\n // if source is null\n if (!this.source) return \"inactive\";\n let scrollerStyle = getComputedStyle(this.source);\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 (this.source != document.scrollingElement &&\n (scrollerStyle.overflow == 'visible' ||\n scrollerStyle.overflow == \"clip\")) {\n return \"inactive\";\n }\n\n let effectiveScrollOffsets = resolveScrollOffsets(\n this.source,\n this.orientation,\n this.scrollOffsets,\n scrollTimelineOptions.get(this).scrollOffsetFns\n );\n\n // if source's effective scroll range is null\n if (effectiveScrollOffsets.length == 0)\n return \"inactive\";\n\n let maxOffset = calculateScrollOffset(\n new CSSUnitValue(100, 'percent'),\n this.source,\n this.orientation,\n new CSSUnitValue(100, 'percent'),\n null\n );\n let startOffset = effectiveScrollOffsets[0];\n let endOffset = effectiveScrollOffsets[effectiveScrollOffsets.length - 1];\n\n // Step 2\n const currentScrollOffset =\n directionAwareScrollOffset(this.source, this.orientation);\n\n // Step 3\n if (currentScrollOffset < startOffset)\n return \"before\";\n if (currentScrollOffset >= endOffset && endOffset < maxOffset)\n return \"after\";\n return \"active\"\n }\n\n get currentTime() {\n // Per https://wicg.github.io/scroll-animations/#current-time-algorithm\n // Step 1\n let unresolved = null;\n if (!this.source) return unresolved;\n if (this.phase == 'inactive')\n return unresolved;\n\n let effectiveScrollOffsets = resolveScrollOffsets(\n this.source,\n this.orientation,\n this.scrollOffsets,\n scrollTimelineOptions.get(this).scrollOffsetFns\n );\n let startOffset = effectiveScrollOffsets[0];\n let endOffset = effectiveScrollOffsets[effectiveScrollOffsets.length - 1];\n\n // Step 2\n const currentScrollOffset =\n directionAwareScrollOffset(this.source, this.orientation);\n\n // Step 3\n if (currentScrollOffset < startOffset)\n return CSS.percent(0);\n\n // Step 4\n if (currentScrollOffset >= endOffset)\n return CSS.percent(100);\n\n // Step 5\n let progress = ComputeProgress(\n currentScrollOffset,\n effectiveScrollOffsets\n );\n return CSS.percent(100 * progress);\n }\n\n get __polyfill() {\n return true;\n }\n}\n\nfunction getScrollParent(node) {\n if (!node)\n return undefined;\n\n const style = getComputedStyle(node);\n switch(style['overflow-x']) {\n case 'auto':\n case 'scroll':\n case 'hidden':\n return node;\n\n default:\n return getScrollParent(node.parentNode);\n }\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 // We rely on having source set in order to properly set up the\n // scroll listener. Ideally, this should be null if left unspecified.\n // TODO: Add a mutation observer that detects any style change that could\n // affect resolution of the source container.\n if (options.subject && !options.source)\n options.source = getScrollParent(options.subject.parentNode);\n\n super(options);\n\n const details = scrollTimelineOptions.get(this);\n details.subject = options && options.subject ? options.subject : undefined;\n details.range = options && options.range ? options.range : 'cover';\n // TODO: Handle insets.\n }\n\n get subject() {\n return scrollTimelineOptions.get(this).subject;\n }\n\n\n // As currently specced phase can be in one of 4 states: active, inactive,\n // before, and after. This creates potential confusion with animation effect\n // phases. The phase calculation for an animation effect already knows how\n // to handle currentTime being outside the range of [0, effect end]. The\n // implementation of phase for the view timeline drops the before and after\n // phases and simply allows currentTime to extend outside the [0%, 100%]\n // range. Visually, this produces the correct result and there is a proposal\n // to update the spec to align with this implementation.\n // http://github.com/w3c/csswg-drafts/issues/7240\n // TODO: Update once specced.\n get phase() {\n if (!this.subject)\n return \"inactive\";\n\n const container = this.source;\n if (!container)\n return \"inactive\";\n\n let scrollerStyle = getComputedStyle(container);\n\n if (scrollerStyle.display == \"none\")\n return \"inactive\";\n\n if (container != document.scrollingElement &&\n (scrollerStyle.overflow == 'visible' ||\n scrollerStyle.overflow == \"clip\")) {\n return \"inactive\";\n }\n\n // This check is not in the spec.\n // http://github.com/w3c/csswg-drafts/issues/7259\n // Update once specced.\n let node = this.subject;\n while (node && node != container) {\n node = node.offsetParent;\n }\n if (node != container)\n return \"inactive\";\n\n return \"active\";\n }\n\n // Currently specced as fit with proposal to rename in order to more naturally\n // support start and end transitions.\n // http://github.com/w3c/csswg-drafts/issues/7044\n // TODO: Update once specced.\n get range() {\n return scrollTimelineOptions.get(this).range;\n }\n\n get currentTime() {\n const unresolved = null;\n if (this.phase === 'inactive')\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 = this.source;\n const target = this.subject;\n\n let top = 0;\n let left = 0;\n let node = target;\n while (node && node != container) {\n left += node.offsetLeft;\n top += node.offsetTop;\n node = node.offsetParent;\n }\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';\n let viewSize = undefined;\n let viewPos = undefined;\n let containerSize = undefined;\n const orientation = this.orientation;\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 scrollPos = directionAwareScrollOffset(container, orientation);\n let startOffset = undefined;\n let endOffset = undefined;\n\n switch(this.range) {\n case 'cover':\n // Range of scroll offsets where the subject element intersects the\n // source's viewport.\n startOffset = viewPos - containerSize;\n endOffset = viewPos + viewSize;\n break;\n\n case 'contain':\n // Range of scroll offsets where the subject element is fully inside of\n // the container's viewport. If the subject's bounds exceed the size\n // of the viewport in the scroll direction then the scroll range is\n // empty.\n startOffset = viewPos + viewSize - containerSize;\n endOffset = viewPos;\n break;\n\n case 'start':\n // Range of scroll offsets where the subject element overlaps the\n // logical-start edge of the viewport.\n startOffset = viewPos - containerSize;\n endOffset = viewPos + viewSize - containerSize;\n break;\n\n case 'end':\n // Range of scroll offsets where the subject element overlaps the\n // logical-end edge of the viewport.\n startOffset = viewPos;\n endOffset = viewPos + viewSize;\n break;\n\n default:\n // TODO: support offset pair.\n }\n\n if (startOffset < endOffset) {\n const progress = (scrollPos - startOffset) / (endOffset - startOffset);\n return CSS.percent(100 * progress);\n }\n\n return unresolved;\n }\n}\n","import {\n ScrollTimeline,\n installScrollOffsetExtension,\n addAnimation,\n removeAnimation\n} from \"./scroll-timeline-base\";\n\nconst nativeElementAnimate = window.Element.prototype.animate;\nconst nativeAnimation = window.Animation;\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 // TODO: Support hold phase.\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 = fromCssNumberish(details,\n details.timeline.currentTime);\n details.animation.currentTime =\n (timelineTime - details.startTime) *\n details.animation.playbackRate;\n } else if (details.holdTime !== null) {\n details.animation.currentTime = details.holdTime;\n }\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 details.animation.currentTime =\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 timeline phase.\n const phase = details.timeline.phase;\n const fill = timing.fill;\n\n if(phase == 'before' && fill != 'backwards' && fill != 'both') {\n timing.progress = null;\n }\n if (phase == 'after' && fill != 'forwards' && fill != 'both') {\n timing.progress = null;\n }\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 let totalDuration;\n\n // Duration 'auto' case.\n if (timing.duration === null || timing.duration === 'auto') {\n if (details.timeline) {\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 totalDuration = timing.iterations ? INTERNAL_DURATION_MS : 0;\n timing.duration =\n timing.iterations ? totalDuration / timing.iterations : 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// 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) {\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 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\nexport function animate(keyframes, options) {\n const timeline = options.timeline;\n\n if (timeline instanceof ScrollTimeline)\n delete options.timeline;\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 proxyAnimation.play();\n }\n\n return proxyAnimation;\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\nlet IntersectionOptions = new WeakMap();\n\n// Margin is stored as a 4 element array [top, right, bottom, left] but can be\n// specified using anywhere from 1 - 4 elements. This map defines how to convert\n// various length inputs to their components.\nconst TOP = 0;\nconst RIGHT = 1;\nconst BOTTOM = 2;\nconst LEFT = 3;\nconst MARGIN_MAP = [\n // 1 length maps to all positions.\n [[TOP, RIGHT, BOTTOM, LEFT]],\n // 2 lengths maps to vertical and horizontal margins.\n [\n [TOP, BOTTOM],\n [RIGHT, LEFT],\n ],\n // 3 lengths maps to top, horizontal, bottom margins.\n [[TOP], [RIGHT, LEFT], [BOTTOM]],\n // 4 lengths maps to each component.\n [[TOP], [RIGHT], [BOTTOM], [LEFT]],\n];\n\nclass IntersectionBasedOffset {\n constructor(value) {\n IntersectionOptions.set(this, {\n target: null,\n edge: \"start\",\n threshold: 0,\n rootMargin: [\n [0, \"px\"],\n [0, \"px\"],\n [0, \"px\"],\n [0, \"px\"],\n ],\n });\n this.target = value.target;\n this.edge = value.edge || \"start\";\n this.threshold = value.threshold || 0;\n this.rootMargin = value.rootMargin || \"0px 0px 0px 0px\";\n this.clamp = value.clamp || false;\n }\n\n set target(element) {\n if (!(element instanceof Element)) {\n IntersectionOptions.get(this).target = null;\n throw Error(\"Intersection target must be an element.\");\n }\n IntersectionOptions.get(this).target = element;\n }\n\n get target() {\n return IntersectionOptions.get(this).target;\n }\n\n set edge(value) {\n if ([\"start\", \"end\"].indexOf(value) == -1) return;\n IntersectionOptions.get(this).edge = value;\n }\n\n get edge() {\n return IntersectionOptions.get(this).edge;\n }\n\n set threshold(value) {\n let threshold = parseFloat(value);\n // Throw a TypeError for a parse error.\n if (threshold != threshold)\n throw TypeError(\"Invalid threshold.\");\n // TODO(https://crbug.com/1136516): This should throw a RangeError\n // consistent with the intersection observer spec but the current\n // test expectations are looking for a TypeError.\n if (threshold < 0 || threshold > 1)\n throw TypeError(\"threshold must be in the range [0, 1]\");\n IntersectionOptions.get(this).threshold = threshold;\n }\n\n get threshold() {\n return IntersectionOptions.get(this).threshold;\n }\n\n set rootMargin(value) {\n let margins = value.split(/ +/);\n if (margins.length < 1 || margins.length > 4)\n throw TypeError(\n \"rootMargin must contain between 1 and 4 length components\"\n );\n let parsedMargins = [[], [], [], []];\n for (let i = 0; i < margins.length; i++) {\n let parsedValue = parseLength(margins[i], true);\n if (!parsedValue) throw TypeError(\"Unrecognized rootMargin length\");\n let positions = MARGIN_MAP[margins.length - 1][i];\n for (let j = 0; j < positions.length; j++) {\n parsedMargins[positions[j]] = [\n parseFloat(parsedValue.value),\n parsedValue.unit,\n ];\n }\n }\n IntersectionOptions.get(this).rootMargin = parsedMargins;\n }\n\n get rootMargin() {\n // TODO: Simplify to the shortest matching specification for the given margins.\n return IntersectionOptions.get(this)\n .rootMargin.map((margin) => {\n return margin.join(\"\");\n })\n .join(\" \");\n }\n\n set clamp(value) {\n // This is just for testing alternative proposals - not intended to be part\n // of the specification.\n IntersectionOptions.get(this).clamp = !!value;\n }\n}\n\nexport function parseOffset(value) {\n if (value.target) return new IntersectionBasedOffset(value);\n}\n\nfunction resolveLength(length, containerSize) {\n if (length[1] == \"percent\") return (length[0] * containerSize) / 100;\n // Assumption is only px or % will be passed in.\n // TODO: Support other length types (e.g. em, vh, etc).\n return length[0];\n}\n\nexport function calculateOffset(source, orientation, offset, startOrEnd) {\n // TODO: Support other writing directions.\n if (orientation == \"block\") orientation = \"vertical\";\n else if (orientation == \"inline\") orientation = \"horizontal\";\n let originalViewport =\n source == document.scrollingElement\n ? {\n left: 0,\n right: source.clientWidth,\n top: 0,\n bottom: source.clientHeight,\n width: source.clientWidth,\n height: source.clientHeight,\n }\n : source.getBoundingClientRect();\n\n // Resolve margins and offset viewport.\n let parsedMargins = IntersectionOptions.get(offset).rootMargin;\n let computedMargins = [];\n for (let i = 0; i < 4; i++) {\n computedMargins.push(\n resolveLength(\n parsedMargins[i],\n i % 2 == 0 ? originalViewport.height : originalViewport.width\n )\n );\n }\n let viewport = {\n left: originalViewport.left - computedMargins[LEFT],\n right: originalViewport.right + computedMargins[RIGHT],\n width:\n originalViewport.right -\n originalViewport.left +\n computedMargins[LEFT] +\n computedMargins[RIGHT],\n top: originalViewport.top - computedMargins[TOP],\n bottom: originalViewport.bottom + computedMargins[BOTTOM],\n height:\n originalViewport.bottom -\n originalViewport.top +\n computedMargins[TOP] +\n computedMargins[BOTTOM],\n };\n\n let clamped = IntersectionOptions.get(offset).clamp;\n let target = offset.target.getBoundingClientRect();\n let threshold = offset.threshold;\n // Invert threshold for start position.\n if (offset.edge == \"start\") threshold = 1 - threshold;\n // Projected point into the scroller scroll range.\n if (orientation == \"vertical\") {\n let point =\n target.top +\n target.height * threshold -\n viewport.top +\n source.scrollTop;\n if (clamped) {\n if (offset.edge == \"end\") return Math.max(0, point - viewport.height);\n return Math.min(point, source.scrollHeight - viewport.height);\n } else {\n if (offset.edge == \"end\") return point - viewport.height;\n return point;\n }\n } else {\n // orientation == 'horizontal'\n let point =\n target.left +\n target.width * threshold -\n viewport.left +\n source.scrollLeft;\n if (clamped) {\n if (offset.edge == \"end\") return Math.max(0, point - viewport.width);\n return Math.min(point, source.scrollWidth - viewport.width);\n } else {\n if (offset.edge == \"end\") return point - viewport.width;\n return point;\n }\n }\n}\n","const VALID_SCROLL_OFFSET_SUFFIXES = [\n // Relative lengths.\n 'em',\n 'ex',\n 'ch',\n 'rem',\n 'vw',\n 'vh',\n 'vmin',\n 'vmax',\n // Absolute lengths.\n 'cm',\n 'mm',\n 'q',\n 'in',\n 'pc',\n 'pt',\n 'px',\n // Percentage.\n '%',\n];\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 ANIMATION_TIMELINE: /animation-timeline\\s*:([^;}]+)/,\n ANIMATION_NAME: /animation-name\\s*:([^;}]+)/,\n ANIMATION: /animation\\s*:([^;}]+)/,\n OFFSET_WITH_SUFFIX: new RegExp('(^[0-9]+)(' + VALID_SCROLL_OFFSET_SUFFIXES.join('|') + ')'),\n ELEMENT_OFFSET: /selector\\(#([^)]+)\\)[ ]{0,1}(start|end)*[ ]{0,1}([0-9]+[.]{0,1}[0-9]*)*/,\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\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.keyframeNames = new Set();\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.extractAndSaveKeyframeName(rule.selector);\n } else {\n this.handleScrollTimelineProps(rule, p);\n }\n }\n }\n\n // If this sheet has no srcURL (like from a