From 8c2738bce3948fa26e23462965ccf4757c270454 Mon Sep 17 00:00:00 2001 From: Bramus Date: Thu, 21 Apr 2022 23:02:35 +0200 Subject: [PATCH 1/2] Add CSS @scroll-timeline demo --- demo/basic/css.html | 49 +++++++++++++++++++++++++++++++++++++++++++++ index.html | 3 +++ 2 files changed, 52 insertions(+) create mode 100644 demo/basic/css.html diff --git a/demo/basic/css.html b/demo/basic/css.html new file mode 100644 index 00000000..cabed17e --- /dev/null +++ b/demo/basic/css.html @@ -0,0 +1,49 @@ + + + +

ScrollTimeline polyfill

+

A more advanced demo based on element intersection.

+
+
+ + diff --git a/index.html b/index.html index 595bb63d..1e92c171 100644 --- a/index.html +++ b/index.html @@ -12,6 +12,9 @@
  • demo/basic
  • +
  • + demo/basic/css +
  • demo/parallax
  • From 0950b176a0afa8d52abcb7297a3de92b9fecb756 Mon Sep 17 00:00:00 2001 From: Bramus Date: Thu, 21 Apr 2022 23:02:48 +0200 Subject: [PATCH 2/2] Don't load CSS Polyfill if browser claims support --- dist/scroll-timeline.js | 2 +- dist/scroll-timeline.js.map | 2 +- src/scroll-timeline-css.js | 5 +++++ 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/dist/scroll-timeline.js b/dist/scroll-timeline.js index e471eaac..c85c2591 100644 --- a/dist/scroll-timeline.js +++ b/dist/scroll-timeline.js @@ -1,2 +1,2 @@ -!function(){function e(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,i=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function l(e,t){if(e instanceof CSSUnitValue||e instanceof CSSMathSum)return e;if(!t)return null;var n=e.trim().match(/^(-?[0-9]*\.?[0-9]*)(px|%)$/);return n?new CSSUnitValue(n[1],"%"==n[2]?"percent":n[2]):null}!function(){var e,n=new WeakMap;function r(e){for(var t,n=[],i=0;i=r&&r=n)return CSS.percent(100);var r=function(e,t){var n;for(n=t.length-2;n>=0&&!(t[n]<=e&&e0&&i>=a?((null===o||o0)&&(o=0),e.holdTime=t?i:o):0!=r&&(t&&null!==e.holdTime&&(e.startTime=O(e,e.holdTime)),e.holdTime=null)}U(e),e.previousCurrentTime=P(e,e.proxy.currentTime),"finished"==e.proxy.playState?(e.finishedPromise||(e.finishedPromise=new w),"pending"==e.finishedPromise.state&&(n?C(e):Promise.resolve().then(function(){C(e)}))):(e.finishedPromise&&"resolved"==e.finishedPromise.state&&(e.finishedPromise=new w),"paused"!=e.animation.playState&&e.animation.pause())}}function A(e){var t=function(e){var t=e.proxy.effect.getTiming();return e.normalizedTiming||t}(e);return Math.max(0,t.delay+t.endDelay+t.iterations*t.duration)}function U(e){if(e.timeline)if(null!==e.startTime){var t=P(e,e.timeline.currentTime);e.animation.currentTime=(t-e.startTime)*e.animation.playbackRate}else null!==e.holdTime&&(e.animation.currentTime=e.holdTime)}function W(e,t){if(e.timeline){var n="paused"==e.proxy.playState&&e.proxy.pending,i=!1,r=null,a=P(e,e.proxy.currentTime);e.resetCurrentTimeOnResume&&(a=null,e.resetCurrentTimeOnResume=!1);var o=I(e),l=A(e);if(o>0&&t&&(null==a||a<0||a>=l))r=0;else if(o<0&&t&&(null==a||a<=0||a>l)){if(Infinity==l)return void e.animation.play();r=l}else 0==o&&null==a&&(r=0);null!=r&&(e.startTime=r,e.holdTime=null,R(e)),y(e.timeline,e.animation,F.bind(e.proxy)),e.holdTime&&(e.startTime=null),e.pendingTask&&(e.pendingTask=null,i=!0),(null!==e.holdTime||null!==r||n||null!==e.pendingPlaybackRate)&&(e.readyPromise&&!i&&(e.readyPromise=null),U(e),e.readyPromise||b(e),e.pendingTask="play",N(e,!1,!1))}}function F(e){var t=j.get(this);if(null!=e){t.pendingTask&&L(t);var n=this.playState;if("running"==n||"finished"==n){var i=P(t,e);t.animation.currentTime=(i-P(t,this.startTime))*this.playbackRate,"finished"==n&&0!=I(t)&&(t.holdTime=null),N(t,!1,!1)}}else"idle"!=t.animation.playState&&t.animation.cancel()}function L(e){"pause"==e.pendingTask?function(e){var t=P(e,e.timeline.currentTime);null!=e.startTime&&null==e.holdTime&&(e.holdTime=(t-e.startTime)*e.animation.playbackRate),R(e),e.startTime=null,e.readyPromise.resolve(e.proxy),N(e,!1,!1),U(e),e.pendingTask=null}(e):"play"==e.pendingTask&&function(e){var t=P(e,e.timeline.currentTime);if(null!=e.holdTime)R(e),0==e.animation.playbackRate?e.startTime=t:(e.startTime=t-e.holdTime/e.animation.playbackRate,e.holdTime=null);else if(null!==e.startTime&&null!==e.pendingPlaybackRate){var n=(t-e.startTime)*e.animation.playbackRate;R(e);var i=e.animation.playbackRate;0==i?(e.holdTime=null,e.startTime=t):e.startTime=t-n/i}e.readyPromise&&"pending"==e.readyPromise.state&&e.readyPromise.resolve(e.proxy),N(e,!1,!1),U(e),e.pendingTask=null}(e)}var j=new WeakMap,_=function(){function e(e,t){var n=e instanceof k?e:new k(e,r),i=t instanceof T,r=i?void 0:t;j.set(this,{animation:n,timeline:i?t:void 0,playState:i?"idle":null,readyPromise:null,finishedPromise:null,startTime:null,holdTime:null,previousCurrentTime:null,resetCurrentTimeOnResume:!1,pendingPlaybackRate:null,pendingTask:null,specifiedTiming:null,normalizedTiming:null,effect:null,proxy:this})}var n=e.prototype;return n.finish=function(){var e=j.get(this);if(e.timeline){var t=I(e),n=A(e);if(0==t)throw new DOMException("Cannot finish Animation with a playbackRate of 0.","InvalidStateError");if(t>0&&Infinity==n)throw new DOMException("Cannot finish Animation with an infinite target effect end.","InvalidStateError");R(e);var i=t<0?0:n;this.currentTime=x(e,i);var r=P(e,e.timeline.currentTime);null===e.startTime&&null!==r&&(e.startTime=r-i/e.animation.playbackRate),"pause"==e.pendingTask&&null!==e.startTime&&(e.holdTime=null,e.pendingTask=null,e.readyPromise.resolve(this)),"play"==e.pendingTask&&null!==e.startTime&&(e.pendingTask=null,e.readyPromise.resolve(this)),N(e,!0,!0)}else e.animation.finish()},n.play=function(){var e=j.get(this);e.timeline?W(e,!0):e.animation.play()},n.pause=function(){var e=j.get(this);if(e.timeline){if("paused"!=this.playState){var t=null,n=e.animation.playbackRate,i=A(e);if(null===e.animation.currentTime)if(n>=0)t=0;else{if(Infinity==i)return void e.animation.pause();t=i}null!==t&&(e.startTime=t),"play"==e.pendingTask?e.pendingTask=null:e.readyPromise=null,e.readyPromise||b(e),e.pendingTask="pause"}}else e.animation.pause()},n.reverse=function(){var e=j.get(this),t=I(e),n=e.resetCurrentTimeOnResume?null:P(e,this.currentTime),i=Infinity==A(e),r=0!=t&&(t<0||n>0||!i);if(!e.timeline||!r)return r&&(e.pendingPlaybackRate=-I(e)),void e.animation.reverse();if("inactive"==e.timeline.phase)throw new DOMException("Cannot reverse an animation with no active timeline","InvalidStateError");this.updatePlaybackRate(-t),W(e,!0)},n.updatePlaybackRate=function(e){var t=j.get(this);if(t.pendingPlaybackRate=e,t.timeline){if(!t.readyPromise||"pending"!=t.readyPromise.state)switch(this.playState){case"idle":case"paused":R(t);break;case"finished":var n=P(t,t.timeline.currentTime),i=null!==n?(n-t.startTime)*t.animation.playbackRate:null;t.startTime=0==e?n:null!=n&&null!=i?(n-i)/e:null,R(t),N(t,!1,!1),U(t);break;default:W(t,!1)}}else t.animation.updatePlaybackRate(e)},n.persist=function(){j.get(this).animation.persist()},n.cancel=function(){var e=j.get(this);e.timeline?("idle"!=this.playState&&(function(e){e.pendingTask&&(e.pendingTask=null,R(e),e.readyPromise.reject(E()),b(e),e.readyPromise.resolve(e.proxy))}(e),e.finishedPromise&&"pending"==e.finishedPromise.state&&e.finishedPromise.reject(E()),e.finishedPromise=new w,e.animation.cancel()),e.startTime=null,e.holdTime=null,v(e.timeline,e.animation)):e.animation.cancel()},n.addEventListener=function(e,t,n){j.get(this).animation.addEventListener(e,t,n)},n.removeEventListener=function(e,t,n){j.get(this).animation.removeEventListener(e,t,n)},n.dispatchEvent=function(e){j.get(this).animation.dispatchEvent(e)},t(e,[{key:"effect",get:function(){var e=j.get(this);return e.timeline?(e.effect||(e.effect=function(e){var t=e.animation.effect,n=t.updateTiming,i={apply:function(n){t.getTiming();var i=n.apply(t);if(e.timeline){i.localTime=x(e,i.localTime),i.endTime=x(e,i.endTime),i.activeDuration=x(e,i.activeDuration);var r=A(e);i.duration=r?CSS.percent(100*(i.iterations?(r-i.delay-i.endDelay)/i.iterations:0)/r):CSS.percent(0);var a=e.timeline.phase,o=i.fill;"before"==a&&"backwards"!=o&&"both"!=o&&(i.progress=null),"after"==a&&"forwards"!=o&&"both"!=o&&(i.progress=null),void 0===e.timeline.currentTime&&(i.localTime=null)}return i}},r={apply:function(i,r){if(e.specifiedTiming)return e.specifiedTiming;e.specifiedTiming=i.apply(t);var a=Object.assign({},e.specifiedTiming);return null!==a.duration&&"auto"!==a.duration||e.timeline&&(a.delay=0,a.endDelay=0,a.duration=a.iterations?(a.iterations?1e5:0)/a.iterations:0,n.apply(t,[a])),e.normalizedTiming=a,e.specifiedTiming}},a={apply:function(n,i,r){if(e.timeline){var a=r[0];if(Infinity===a.duration)throw TypeError("Effect duration cannot be Infinity when used with Scroll Timelines");if(Infinity===a.iterations)throw TypeError("Effect iterations cannot be Infinity when used with Scroll Timelines")}e.specifiedTiming&&n.apply(t,[e.specifiedTiming]),n.apply(t,r),e.specifiedTiming=null}},o=new Proxy(t,{get:function(e,n){var i=e[n];return"function"==typeof i?i.bind(t):i},set:function(e,t,n){return e[t]=n,!0}});return o.getComputedTiming=new Proxy(t.getComputedTiming,i),o.getTiming=new Proxy(t.getTiming,r),o.updateTiming=new Proxy(t.updateTiming,a),o}(e)),e.effect):e.animation.effect},set:function(e){j.get(this).animation.effect=e,details.effect=null}},{key:"timeline",get:function(){var e=j.get(this);return e.timeline||e.animation.timeline},set:function(e){var t=this.timeline;if(t!=e){var n=this.playState,i=this.currentTime,r=j.get(this),a=A(r),o=a>0?P(r,i)/a:0,l=t instanceof T,s=e instanceof T;r.resetCurrentTimeOnResume=!1;var u=this.pending;if(l&&v(r.timeline,r.animation),s){r.timeline=e,R(r);var c=r.animation.playbackRate>=0?0:A(r);switch(n){case"running":case"finished":r.startTime=c,y(r.timeline,r.animation,F.bind(this));break;case"paused":r.resetCurrentTimeOnResume=!0,r.startTime=null,r.holdTime=P(r,CSS.percent(100*o));break;default:r.holdTime=null,r.startTime=null}return u&&(r.readyPromise&&"resolved"!=r.readyPromise.state||b(r),r.pendingTask="paused"==n?"pause":"play"),null!==r.startTime&&(r.holdTime=null),void N(r,!1,!1)}if(r.animation.timeline!=e)throw TypeError("Unsupported timeline: "+e);if(v(r.timeline,r.animation),r.timeline=null,l)switch(null!==i&&(r.animation.currentTime=o*A(r)),n){case"paused":r.animation.pause();break;case"running":case"finished":r.animation.play()}}}},{key:"startTime",get:function(){var e=j.get(this);return e.timeline?x(e,e.startTime):e.animation.startTime},set:function(e){var t=j.get(this);if(e=P(t,e),t.timeline){null==P(t,t.timeline.currentTime)&&null!=t.startTime&&(t.holdTime=null,U(t));var n=P(t,this.currentTime);R(t),t.startTime=e,t.resetCurrentTimeOnResume=!1,t.holdTime=null!==t.startTime&&0!=t.animation.playbackRate?null:n,t.pendingTask&&(t.pendingTask=null,t.readyPromise.resolve(this)),N(t,!0,!1),U(t)}else t.animation.startTime=e}},{key:"currentTime",get:function(){var e=j.get(this);return e.timeline?x(e,null!=e.holdTime?e.holdTime:M(e)):e.animation.currentTime},set:function(e){var t=j.get(this);if(e=P(t,e),t.timeline&&null!=e){var n=t.timeline.phase;null!==t.holdTime||null===t.startTime||"inactive"==n||0==t.animation.playbackRate?t.holdTime=e:t.startTime=O(t,e),t.resetCurrentTimeOnResume=!1,"inactive"==n&&(t.startTime=null),t.previousCurrentTime=null,"pause"==t.pendingTask&&(t.holdTime=e,R(t),t.startTime=null,t.pendingTask=null,t.readyPromise.resolve(this)),N(t,!0,!1)}else t.animation.currentTime=e}},{key:"playbackRate",get:function(){return j.get(this).animation.playbackRate},set:function(e){var t=j.get(this);if(t.timeline){t.pendingPlaybackRate=null;var n=this.currentTime;t.animation.playbackRate=e,null!==n&&(this.currentTime=n)}else t.animation.playbackRate=e}},{key:"playState",get:function(){var e=j.get(this);if(!e.timeline)return e.animation.playState;var t=P(e,this.currentTime);if(null===t&&null===e.startTime&&null==e.pendingTask)return"idle";if("pause"==e.pendingTask||null===e.startTime&&"play"!=e.pendingTask)return"paused";if(null!=t){if(e.animation.playbackRate>0&&t>=A(e))return"finished";if(e.animation.playbackRate<0&&t<=0)return"finished"}return"running"}},{key:"replaceState",get:function(){return j.get(this).animation.pending}},{key:"pending",get:function(){var e=j.get(this);return e.timeline?!!e.readyPromise&&"pending"==e.readyPromise.state:e.animation.pending}},{key:"id",get:function(){return j.get(this).animation.id}},{key:"onfinish",get:function(){return j.get(this).animation.onfinish},set:function(e){j.get(this).animation.onfinish=e}},{key:"oncancel",get:function(){return j.get(this).animation.oncancel},set:function(e){j.get(this).animation.oncancel=e}},{key:"onremove",get:function(){return j.get(this).animation.onremove},set:function(e){j.get(this).animation.onremove=e}},{key:"finished",get:function(){var e=j.get(this);return e.timeline?(e.finishedPromise||(e.finishedPromise=new w),e.finishedPromise.promise):e.animation.finished}},{key:"ready",get:function(){var e=j.get(this);return e.timeline?(e.readyPromise||(e.readyPromise=new w,e.readyPromise.resolve(this)),e.readyPromise.promise):e.animation.ready}}]),e}(),V=new WeakMap,D=[[[0,1,2,3]],[[0,2],[1,3]],[[0],[1,3],[2]],[[0],[1],[2],[3]]],H=function(){function e(e){V.set(this,{target:null,edge:"start",threshold:0,rootMargin:[[0,"px"],[0,"px"],[0,"px"],[0,"px"]]}),this.target=e.target,this.edge=e.edge||"start",this.threshold=e.threshold||0,this.rootMargin=e.rootMargin||"0px 0px 0px 0px",this.clamp=e.clamp||!1}return t(e,[{key:"target",get:function(){return V.get(this).target},set:function(e){if(!(e instanceof Element))throw V.get(this).target=null,Error("Intersection target must be an element.");V.get(this).target=e}},{key:"edge",get:function(){return V.get(this).edge},set:function(e){-1!=["start","end"].indexOf(e)&&(V.get(this).edge=e)}},{key:"threshold",get:function(){return V.get(this).threshold},set:function(e){var t=parseFloat(e);if(t!=t)throw TypeError("Invalid threshold.");if(t<0||t>1)throw TypeError("threshold must be in the range [0, 1]");V.get(this).threshold=t}},{key:"rootMargin",get:function(){return V.get(this).rootMargin.map(function(e){return e.join("")}).join(" ")},set:function(e){var t=e.split(/ +/);if(t.length<1||t.length>4)throw TypeError("rootMargin must contain between 1 and 4 length components");for(var n=[[],[],[],[]],i=0;i=i.sheetSrc.length));)if(this.lookAhead("/*",i))for(;this.lookAhead("/*",i);)this.eatComment(i),this.eatWhitespace(i);else if(this.lookAhead("@scroll-timeline",i)){var r=this.parseScrollTimeline(i).scrollTimeline;t&&this.scrollTimelineOptions.set(r.name,r)}else{var a=this.parseQualifiedRule(i);if(!a)continue;t?this.extractAndSaveKeyframeName(a.selector):this.handleScrollTimelineProps(a,i)}return i.sheetSrc},t.getScrollTimelineName=function(e,t){for(var n=this.cssRulesWithTimelineName.length-1;n>=0;n--){var i=this.cssRulesWithTimelineName[n];if(t.matches(i.selector)&&(!i["animation-name"]||i["animation-name"]==e))return i["animation-timeline"]}return null},t.parseScrollTimeline=function(e){var t=e.index;this.assertString(e,"@scroll-timeline"),this.eatWhitespace(e);var n=this.parseIdentifier(e);this.eatWhitespace(e),this.assertString(e,"{"),this.eatWhitespace(e);for(var i={name:n,source:"auto",orientation:void 0,"scroll-offsets":void 0};"}"!==this.peek(e);){var r=this.parseIdentifier(e);this.eatWhitespace(e),this.assertString(e,":"),this.eatWhitespace(e),i[r]=this.removeEnclosingDoubleQuotes(this.eatUntil(";",e)),this.assertString(e,";"),this.eatWhitespace(e)}this.assertString(e,"}");var a=e.index;return this.eatWhitespace(e),{scrollTimeline:i,startIndex:t,endIndex:a}},t.handleScrollTimelineProps=function(e,t){var n=this;if(!e.selector.includes("@keyframes")){var i=e.block.contents.includes("animation-name:"),r=e.block.contents.includes("animation-timeline:"),a=e.block.contents.includes("animation:"),o=[],l=[];r&&(o=this.extractMatches(e.block.contents,z.ANIMATION_TIMELINE)),i&&(l=this.extractMatches(e.block.contents,z.ANIMATION_NAME)),r&&i||a&&this.extractMatches(e.block.contents,z.ANIMATION).forEach(function(i){var r=n.extractAnimationName(i),a=n.extractTimelineName(i);r&&l.push(r),a&&(o.push(a),e.block.contents=e.block.contents.replace(a,""),n.replacePart(e.block.startIndex,e.block.endIndex,e.block.contents,t))}),this.saveRelationInList(e,o,l)}},t.saveRelationInList=function(e,t,n){if(0==n.length)for(var i=0;i0&&t.keyframeNames.add(e)})},t.parseQualifiedRule=function(e){var t=e.index,n=this.parseSelector(e).trim();if(n)return{selector:n,block:this.eatBlock(e),startIndex:t,endIndex:e.index}},t.removeEnclosingDoubleQuotes=function(e){return e.substring('"'==e[0]?1:0,'"'==e[e.length-1]?e.length-1:e.length)},t.assertString=function(e,t){if(e.sheetSrc.substr(e.index,t.length)!=t)throw this.parseError(e,"Did not find expected sequence "+t);e.index+=t.length},t.replacePart=function(e,t,n,i){i.sheetSrc=i.sheetSrc.slice(0,e)+n+i.sheetSrc.slice(t),i.index>=t&&(i.index=e+n.length+(i.index-t))},t.eatComment=function(e){this.assertString(e,"/*"),this.eatUntil("*/",e),this.assertString(e,"*/")},t.eatBlock=function(e){var t=e.index;this.assertString(e,"{");for(var n=1;0!=n;)"{"===e.sheetSrc[e.index]?n++:"}"===e.sheetSrc[e.index]&&n--,this.advance(e);var i=e.index;return{startIndex:t,endIndex:i,contents:e.sheetSrc.slice(t,i)}},t.advance=function(e){if(e.index++,e.index>e.sheetSrc.length)throw this.parseError(e,"Advanced beyond the end")},t.eatUntil=function(e,t){for(var n=t.index;!this.lookAhead(e,t);)this.advance(t);return t.sheetSrc.slice(n,t.index)},t.parseSelector=function(e){var t=e.index;if(this.eatUntil("{",e),t===e.index)throw Error("Empty selector");return e.sheetSrc.slice(t,e.index)},t.eatWhitespace=function(e){z.WHITE_SPACE.lastIndex=e.index;var t=z.WHITE_SPACE.exec(e.sheetSrc);t&&(e.index+=t[0].length)},t.lookAhead=function(e,t){return t.sheetSrc.substr(t.index,e.length)==e},t.peek=function(e){return e.sheetSrc[e.index]},t.extractMatches=function(e,t){return t.exec(e)[1].trim().split(",").map(function(e){return e.trim()})},e}());function B(e){var t=z.SOURCE_ELEMENT.exec(e);return t?document.getElementById(t[1]):"auto"===e?document.scrollingElement:null}function K(e,t){for(;e;){if(e==t)return!0;e=e.parentNode}return!1}if(c.push({parse:function(e){if(e.target)return new H(e)},evaluate:function(e,t,n,i){"block"==t?t="vertical":"inline"==t&&(t="horizontal");for(var r,a=e==document.scrollingElement?{left:0,right:e.clientWidth,top:0,bottom:e.clientHeight,width:e.clientWidth,height:e.clientHeight}:e.getBoundingClientRect(),o=V.get(n).rootMargin,l=[],s=0;s<4;s++)l.push("percent"==(r=o[s])[1]?r[0]*(s%2==0?a.height:a.width)/100:r[0]);var u=a.left-l[3],c=a.right-a.left+l[3]+l[1],m=a.top-l[0],f=a.bottom-a.top+l[0]+l[2],h=V.get(n).clamp,d=n.target.getBoundingClientRect(),p=n.threshold;if("start"==n.edge&&(p=1-p),"vertical"==t){var g=d.top+d.height*p-m+e.scrollTop;return h?"end"==n.edge?Math.max(0,g-f):Math.min(g,e.scrollHeight-f):"end"==n.edge?g-f:g}var v=d.left+d.width*p-u+e.scrollLeft;return h?"end"==n.edge?Math.max(0,v-c):Math.min(v,e.scrollWidth-c):"end"==n.edge?v-c:v}}),function(){function e(e){if(0!==e.innerHTML.trim().length){var t=q.transpileStyleSheet(e.innerHTML,!0);t=q.transpileStyleSheet(t,!1),e.innerHTML=t}}new MutationObserver(function(t){for(var n,i=o(t);!(n=i()).done;)for(var r,a=o(n.value.addedNodes);!(r=a()).done;){var l=r.value;l instanceof HTMLStyleElement&&e(l)}}).observe(document.documentElement,{childList:!0,subtree:!0}),document.querySelectorAll("style").forEach(function(t){return e(t)}),document.querySelectorAll("link").forEach(function(e){})}(),window.addEventListener("animationstart",function(e){e.target.getAnimations().filter(function(t){return t.animationName===e.animationName}).forEach(function(t){var i=q.getScrollTimelineName(t.animationName,e.target);if(i){var r=function(e){var t=q.scrollTimelineOptions.get(e);if(!t)return null;var i=B(t.source),r=function(e,t){var i=void 0;if(t)if("none"==t);else{for(var r,a=o(i=t.split(",").map(function(e){return e.trim()}).filter(function(e){return""!=e}).map(function(e){return function(e){if("auto"==e)return new CSSKeywordValue("auto");var t=z.OFFSET_WITH_SUFFIX.exec(e);if(t)return new CSSUnitValue(parseInt(t[1]),t[2]);var i=z.ELEMENT_OFFSET.exec(e);return i&&document.getElementById(i[1])?n({target:document.getElementById(i[1])},i.length>=3?{edge:i[2]}:{},i.length>=4?{threshold:parseFloat(i[3])}:{}):null}(e)}).filter(function(e){return e}));!(r=a()).done;){var l=r.value;if(l.target&&l.target instanceof Element&&("none"==window.getComputedStyle(l.target,null).display||!K(l.target,e)))return null}if(0==i.length)return null}return i}(i,t["scroll-offsets"]);return null!==r?new ScrollTimeline(n({},i?{source:B(t.source)}:{},r?{scrollOffsets:r}:{},"auto"!=t.orientation?{orientation:t.orientation}:{})):null}(i);if(t.timeline!=r){var a=new _(t,r);t.pause(),a.play()}}})}),!Reflect.defineProperty(window,"ScrollTimeline",{value:T}))throw Error("Error installing ScrollTimeline polyfill: could not attach ScrollTimeline to window");if(!Reflect.defineProperty(Element.prototype,"animate",{value:function(e,t){var n=t.timeline;n instanceof T&&delete t.timeline;var i=S.apply(this,[e,t]),r=new _(i,n);return n instanceof T&&(i.pause(),r.play()),r}}))throw Error("Error installing ScrollTimeline polyfill: could not attach WAAPI's animate to DOM Element");if(!Reflect.defineProperty(window,"Animation",{value:_}))throw Error("Error installing Animation constructor.")}(); +!function(){function e(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,i=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function l(e,t){if(e instanceof CSSUnitValue||e instanceof CSSMathSum)return e;if(!t)return null;var n=e.trim().match(/^(-?[0-9]*\.?[0-9]*)(px|%)$/);return n?new CSSUnitValue(n[1],"%"==n[2]?"percent":n[2]):null}!function(){var e,n=new WeakMap;function r(e){for(var t,n=[],i=0;i=r&&r=n)return CSS.percent(100);var r=function(e,t){var n;for(n=t.length-2;n>=0&&!(t[n]<=e&&e0&&i>=a?((null===o||o0)&&(o=0),e.holdTime=t?i:o):0!=r&&(t&&null!==e.holdTime&&(e.startTime=O(e,e.holdTime)),e.holdTime=null)}U(e),e.previousCurrentTime=P(e,e.proxy.currentTime),"finished"==e.proxy.playState?(e.finishedPromise||(e.finishedPromise=new w),"pending"==e.finishedPromise.state&&(n?C(e):Promise.resolve().then(function(){C(e)}))):(e.finishedPromise&&"resolved"==e.finishedPromise.state&&(e.finishedPromise=new w),"paused"!=e.animation.playState&&e.animation.pause())}}function A(e){var t=function(e){var t=e.proxy.effect.getTiming();return e.normalizedTiming||t}(e);return Math.max(0,t.delay+t.endDelay+t.iterations*t.duration)}function U(e){if(e.timeline)if(null!==e.startTime){var t=P(e,e.timeline.currentTime);e.animation.currentTime=(t-e.startTime)*e.animation.playbackRate}else null!==e.holdTime&&(e.animation.currentTime=e.holdTime)}function W(e,t){if(e.timeline){var n="paused"==e.proxy.playState&&e.proxy.pending,i=!1,r=null,a=P(e,e.proxy.currentTime);e.resetCurrentTimeOnResume&&(a=null,e.resetCurrentTimeOnResume=!1);var o=I(e),l=A(e);if(o>0&&t&&(null==a||a<0||a>=l))r=0;else if(o<0&&t&&(null==a||a<=0||a>l)){if(Infinity==l)return void e.animation.play();r=l}else 0==o&&null==a&&(r=0);null!=r&&(e.startTime=r,e.holdTime=null,R(e)),y(e.timeline,e.animation,F.bind(e.proxy)),e.holdTime&&(e.startTime=null),e.pendingTask&&(e.pendingTask=null,i=!0),(null!==e.holdTime||null!==r||n||null!==e.pendingPlaybackRate)&&(e.readyPromise&&!i&&(e.readyPromise=null),U(e),e.readyPromise||b(e),e.pendingTask="play",N(e,!1,!1))}}function F(e){var t=j.get(this);if(null!=e){t.pendingTask&&L(t);var n=this.playState;if("running"==n||"finished"==n){var i=P(t,e);t.animation.currentTime=(i-P(t,this.startTime))*this.playbackRate,"finished"==n&&0!=I(t)&&(t.holdTime=null),N(t,!1,!1)}}else"idle"!=t.animation.playState&&t.animation.cancel()}function L(e){"pause"==e.pendingTask?function(e){var t=P(e,e.timeline.currentTime);null!=e.startTime&&null==e.holdTime&&(e.holdTime=(t-e.startTime)*e.animation.playbackRate),R(e),e.startTime=null,e.readyPromise.resolve(e.proxy),N(e,!1,!1),U(e),e.pendingTask=null}(e):"play"==e.pendingTask&&function(e){var t=P(e,e.timeline.currentTime);if(null!=e.holdTime)R(e),0==e.animation.playbackRate?e.startTime=t:(e.startTime=t-e.holdTime/e.animation.playbackRate,e.holdTime=null);else if(null!==e.startTime&&null!==e.pendingPlaybackRate){var n=(t-e.startTime)*e.animation.playbackRate;R(e);var i=e.animation.playbackRate;0==i?(e.holdTime=null,e.startTime=t):e.startTime=t-n/i}e.readyPromise&&"pending"==e.readyPromise.state&&e.readyPromise.resolve(e.proxy),N(e,!1,!1),U(e),e.pendingTask=null}(e)}var j=new WeakMap,_=function(){function e(e,t){var n=e instanceof k?e:new k(e,r),i=t instanceof T,r=i?void 0:t;j.set(this,{animation:n,timeline:i?t:void 0,playState:i?"idle":null,readyPromise:null,finishedPromise:null,startTime:null,holdTime:null,previousCurrentTime:null,resetCurrentTimeOnResume:!1,pendingPlaybackRate:null,pendingTask:null,specifiedTiming:null,normalizedTiming:null,effect:null,proxy:this})}var n=e.prototype;return n.finish=function(){var e=j.get(this);if(e.timeline){var t=I(e),n=A(e);if(0==t)throw new DOMException("Cannot finish Animation with a playbackRate of 0.","InvalidStateError");if(t>0&&Infinity==n)throw new DOMException("Cannot finish Animation with an infinite target effect end.","InvalidStateError");R(e);var i=t<0?0:n;this.currentTime=x(e,i);var r=P(e,e.timeline.currentTime);null===e.startTime&&null!==r&&(e.startTime=r-i/e.animation.playbackRate),"pause"==e.pendingTask&&null!==e.startTime&&(e.holdTime=null,e.pendingTask=null,e.readyPromise.resolve(this)),"play"==e.pendingTask&&null!==e.startTime&&(e.pendingTask=null,e.readyPromise.resolve(this)),N(e,!0,!0)}else e.animation.finish()},n.play=function(){var e=j.get(this);e.timeline?W(e,!0):e.animation.play()},n.pause=function(){var e=j.get(this);if(e.timeline){if("paused"!=this.playState){var t=null,n=e.animation.playbackRate,i=A(e);if(null===e.animation.currentTime)if(n>=0)t=0;else{if(Infinity==i)return void e.animation.pause();t=i}null!==t&&(e.startTime=t),"play"==e.pendingTask?e.pendingTask=null:e.readyPromise=null,e.readyPromise||b(e),e.pendingTask="pause"}}else e.animation.pause()},n.reverse=function(){var e=j.get(this),t=I(e),n=e.resetCurrentTimeOnResume?null:P(e,this.currentTime),i=Infinity==A(e),r=0!=t&&(t<0||n>0||!i);if(!e.timeline||!r)return r&&(e.pendingPlaybackRate=-I(e)),void e.animation.reverse();if("inactive"==e.timeline.phase)throw new DOMException("Cannot reverse an animation with no active timeline","InvalidStateError");this.updatePlaybackRate(-t),W(e,!0)},n.updatePlaybackRate=function(e){var t=j.get(this);if(t.pendingPlaybackRate=e,t.timeline){if(!t.readyPromise||"pending"!=t.readyPromise.state)switch(this.playState){case"idle":case"paused":R(t);break;case"finished":var n=P(t,t.timeline.currentTime),i=null!==n?(n-t.startTime)*t.animation.playbackRate:null;t.startTime=0==e?n:null!=n&&null!=i?(n-i)/e:null,R(t),N(t,!1,!1),U(t);break;default:W(t,!1)}}else t.animation.updatePlaybackRate(e)},n.persist=function(){j.get(this).animation.persist()},n.cancel=function(){var e=j.get(this);e.timeline?("idle"!=this.playState&&(function(e){e.pendingTask&&(e.pendingTask=null,R(e),e.readyPromise.reject(E()),b(e),e.readyPromise.resolve(e.proxy))}(e),e.finishedPromise&&"pending"==e.finishedPromise.state&&e.finishedPromise.reject(E()),e.finishedPromise=new w,e.animation.cancel()),e.startTime=null,e.holdTime=null,v(e.timeline,e.animation)):e.animation.cancel()},n.addEventListener=function(e,t,n){j.get(this).animation.addEventListener(e,t,n)},n.removeEventListener=function(e,t,n){j.get(this).animation.removeEventListener(e,t,n)},n.dispatchEvent=function(e){j.get(this).animation.dispatchEvent(e)},t(e,[{key:"effect",get:function(){var e=j.get(this);return e.timeline?(e.effect||(e.effect=function(e){var t=e.animation.effect,n=t.updateTiming,i={apply:function(n){t.getTiming();var i=n.apply(t);if(e.timeline){i.localTime=x(e,i.localTime),i.endTime=x(e,i.endTime),i.activeDuration=x(e,i.activeDuration);var r=A(e);i.duration=r?CSS.percent(100*(i.iterations?(r-i.delay-i.endDelay)/i.iterations:0)/r):CSS.percent(0);var a=e.timeline.phase,o=i.fill;"before"==a&&"backwards"!=o&&"both"!=o&&(i.progress=null),"after"==a&&"forwards"!=o&&"both"!=o&&(i.progress=null),void 0===e.timeline.currentTime&&(i.localTime=null)}return i}},r={apply:function(i,r){if(e.specifiedTiming)return e.specifiedTiming;e.specifiedTiming=i.apply(t);var a=Object.assign({},e.specifiedTiming);return null!==a.duration&&"auto"!==a.duration||e.timeline&&(a.delay=0,a.endDelay=0,a.duration=a.iterations?(a.iterations?1e5:0)/a.iterations:0,n.apply(t,[a])),e.normalizedTiming=a,e.specifiedTiming}},a={apply:function(n,i,r){if(e.timeline){var a=r[0];if(Infinity===a.duration)throw TypeError("Effect duration cannot be Infinity when used with Scroll Timelines");if(Infinity===a.iterations)throw TypeError("Effect iterations cannot be Infinity when used with Scroll Timelines")}e.specifiedTiming&&n.apply(t,[e.specifiedTiming]),n.apply(t,r),e.specifiedTiming=null}},o=new Proxy(t,{get:function(e,n){var i=e[n];return"function"==typeof i?i.bind(t):i},set:function(e,t,n){return e[t]=n,!0}});return o.getComputedTiming=new Proxy(t.getComputedTiming,i),o.getTiming=new Proxy(t.getTiming,r),o.updateTiming=new Proxy(t.updateTiming,a),o}(e)),e.effect):e.animation.effect},set:function(e){j.get(this).animation.effect=e,details.effect=null}},{key:"timeline",get:function(){var e=j.get(this);return e.timeline||e.animation.timeline},set:function(e){var t=this.timeline;if(t!=e){var n=this.playState,i=this.currentTime,r=j.get(this),a=A(r),o=a>0?P(r,i)/a:0,l=t instanceof T,s=e instanceof T;r.resetCurrentTimeOnResume=!1;var u=this.pending;if(l&&v(r.timeline,r.animation),s){r.timeline=e,R(r);var c=r.animation.playbackRate>=0?0:A(r);switch(n){case"running":case"finished":r.startTime=c,y(r.timeline,r.animation,F.bind(this));break;case"paused":r.resetCurrentTimeOnResume=!0,r.startTime=null,r.holdTime=P(r,CSS.percent(100*o));break;default:r.holdTime=null,r.startTime=null}return u&&(r.readyPromise&&"resolved"!=r.readyPromise.state||b(r),r.pendingTask="paused"==n?"pause":"play"),null!==r.startTime&&(r.holdTime=null),void N(r,!1,!1)}if(r.animation.timeline!=e)throw TypeError("Unsupported timeline: "+e);if(v(r.timeline,r.animation),r.timeline=null,l)switch(null!==i&&(r.animation.currentTime=o*A(r)),n){case"paused":r.animation.pause();break;case"running":case"finished":r.animation.play()}}}},{key:"startTime",get:function(){var e=j.get(this);return e.timeline?x(e,e.startTime):e.animation.startTime},set:function(e){var t=j.get(this);if(e=P(t,e),t.timeline){null==P(t,t.timeline.currentTime)&&null!=t.startTime&&(t.holdTime=null,U(t));var n=P(t,this.currentTime);R(t),t.startTime=e,t.resetCurrentTimeOnResume=!1,t.holdTime=null!==t.startTime&&0!=t.animation.playbackRate?null:n,t.pendingTask&&(t.pendingTask=null,t.readyPromise.resolve(this)),N(t,!0,!1),U(t)}else t.animation.startTime=e}},{key:"currentTime",get:function(){var e=j.get(this);return e.timeline?x(e,null!=e.holdTime?e.holdTime:M(e)):e.animation.currentTime},set:function(e){var t=j.get(this);if(e=P(t,e),t.timeline&&null!=e){var n=t.timeline.phase;null!==t.holdTime||null===t.startTime||"inactive"==n||0==t.animation.playbackRate?t.holdTime=e:t.startTime=O(t,e),t.resetCurrentTimeOnResume=!1,"inactive"==n&&(t.startTime=null),t.previousCurrentTime=null,"pause"==t.pendingTask&&(t.holdTime=e,R(t),t.startTime=null,t.pendingTask=null,t.readyPromise.resolve(this)),N(t,!0,!1)}else t.animation.currentTime=e}},{key:"playbackRate",get:function(){return j.get(this).animation.playbackRate},set:function(e){var t=j.get(this);if(t.timeline){t.pendingPlaybackRate=null;var n=this.currentTime;t.animation.playbackRate=e,null!==n&&(this.currentTime=n)}else t.animation.playbackRate=e}},{key:"playState",get:function(){var e=j.get(this);if(!e.timeline)return e.animation.playState;var t=P(e,this.currentTime);if(null===t&&null===e.startTime&&null==e.pendingTask)return"idle";if("pause"==e.pendingTask||null===e.startTime&&"play"!=e.pendingTask)return"paused";if(null!=t){if(e.animation.playbackRate>0&&t>=A(e))return"finished";if(e.animation.playbackRate<0&&t<=0)return"finished"}return"running"}},{key:"replaceState",get:function(){return j.get(this).animation.pending}},{key:"pending",get:function(){var e=j.get(this);return e.timeline?!!e.readyPromise&&"pending"==e.readyPromise.state:e.animation.pending}},{key:"id",get:function(){return j.get(this).animation.id}},{key:"onfinish",get:function(){return j.get(this).animation.onfinish},set:function(e){j.get(this).animation.onfinish=e}},{key:"oncancel",get:function(){return j.get(this).animation.oncancel},set:function(e){j.get(this).animation.oncancel=e}},{key:"onremove",get:function(){return j.get(this).animation.onremove},set:function(e){j.get(this).animation.onremove=e}},{key:"finished",get:function(){var e=j.get(this);return e.timeline?(e.finishedPromise||(e.finishedPromise=new w),e.finishedPromise.promise):e.animation.finished}},{key:"ready",get:function(){var e=j.get(this);return e.timeline?(e.readyPromise||(e.readyPromise=new w,e.readyPromise.resolve(this)),e.readyPromise.promise):e.animation.ready}}]),e}(),V=new WeakMap,D=[[[0,1,2,3]],[[0,2],[1,3]],[[0],[1,3],[2]],[[0],[1],[2],[3]]],H=function(){function e(e){V.set(this,{target:null,edge:"start",threshold:0,rootMargin:[[0,"px"],[0,"px"],[0,"px"],[0,"px"]]}),this.target=e.target,this.edge=e.edge||"start",this.threshold=e.threshold||0,this.rootMargin=e.rootMargin||"0px 0px 0px 0px",this.clamp=e.clamp||!1}return t(e,[{key:"target",get:function(){return V.get(this).target},set:function(e){if(!(e instanceof Element))throw V.get(this).target=null,Error("Intersection target must be an element.");V.get(this).target=e}},{key:"edge",get:function(){return V.get(this).edge},set:function(e){-1!=["start","end"].indexOf(e)&&(V.get(this).edge=e)}},{key:"threshold",get:function(){return V.get(this).threshold},set:function(e){var t=parseFloat(e);if(t!=t)throw TypeError("Invalid threshold.");if(t<0||t>1)throw TypeError("threshold must be in the range [0, 1]");V.get(this).threshold=t}},{key:"rootMargin",get:function(){return V.get(this).rootMargin.map(function(e){return e.join("")}).join(" ")},set:function(e){var t=e.split(/ +/);if(t.length<1||t.length>4)throw TypeError("rootMargin must contain between 1 and 4 length components");for(var n=[[],[],[],[]],i=0;i=i.sheetSrc.length));)if(this.lookAhead("/*",i))for(;this.lookAhead("/*",i);)this.eatComment(i),this.eatWhitespace(i);else if(this.lookAhead("@scroll-timeline",i)){var r=this.parseScrollTimeline(i).scrollTimeline;t&&this.scrollTimelineOptions.set(r.name,r)}else{var a=this.parseQualifiedRule(i);if(!a)continue;t?this.extractAndSaveKeyframeName(a.selector):this.handleScrollTimelineProps(a,i)}return i.sheetSrc},t.getScrollTimelineName=function(e,t){for(var n=this.cssRulesWithTimelineName.length-1;n>=0;n--){var i=this.cssRulesWithTimelineName[n];if(t.matches(i.selector)&&(!i["animation-name"]||i["animation-name"]==e))return i["animation-timeline"]}return null},t.parseScrollTimeline=function(e){var t=e.index;this.assertString(e,"@scroll-timeline"),this.eatWhitespace(e);var n=this.parseIdentifier(e);this.eatWhitespace(e),this.assertString(e,"{"),this.eatWhitespace(e);for(var i={name:n,source:"auto",orientation:void 0,"scroll-offsets":void 0};"}"!==this.peek(e);){var r=this.parseIdentifier(e);this.eatWhitespace(e),this.assertString(e,":"),this.eatWhitespace(e),i[r]=this.removeEnclosingDoubleQuotes(this.eatUntil(";",e)),this.assertString(e,";"),this.eatWhitespace(e)}this.assertString(e,"}");var a=e.index;return this.eatWhitespace(e),{scrollTimeline:i,startIndex:t,endIndex:a}},t.handleScrollTimelineProps=function(e,t){var n=this;if(!e.selector.includes("@keyframes")){var i=e.block.contents.includes("animation-name:"),r=e.block.contents.includes("animation-timeline:"),a=e.block.contents.includes("animation:"),o=[],l=[];r&&(o=this.extractMatches(e.block.contents,z.ANIMATION_TIMELINE)),i&&(l=this.extractMatches(e.block.contents,z.ANIMATION_NAME)),r&&i||a&&this.extractMatches(e.block.contents,z.ANIMATION).forEach(function(i){var r=n.extractAnimationName(i),a=n.extractTimelineName(i);r&&l.push(r),a&&(o.push(a),e.block.contents=e.block.contents.replace(a,""),n.replacePart(e.block.startIndex,e.block.endIndex,e.block.contents,t))}),this.saveRelationInList(e,o,l)}},t.saveRelationInList=function(e,t,n){if(0==n.length)for(var i=0;i0&&t.keyframeNames.add(e)})},t.parseQualifiedRule=function(e){var t=e.index,n=this.parseSelector(e).trim();if(n)return{selector:n,block:this.eatBlock(e),startIndex:t,endIndex:e.index}},t.removeEnclosingDoubleQuotes=function(e){return e.substring('"'==e[0]?1:0,'"'==e[e.length-1]?e.length-1:e.length)},t.assertString=function(e,t){if(e.sheetSrc.substr(e.index,t.length)!=t)throw this.parseError(e,"Did not find expected sequence "+t);e.index+=t.length},t.replacePart=function(e,t,n,i){i.sheetSrc=i.sheetSrc.slice(0,e)+n+i.sheetSrc.slice(t),i.index>=t&&(i.index=e+n.length+(i.index-t))},t.eatComment=function(e){this.assertString(e,"/*"),this.eatUntil("*/",e),this.assertString(e,"*/")},t.eatBlock=function(e){var t=e.index;this.assertString(e,"{");for(var n=1;0!=n;)"{"===e.sheetSrc[e.index]?n++:"}"===e.sheetSrc[e.index]&&n--,this.advance(e);var i=e.index;return{startIndex:t,endIndex:i,contents:e.sheetSrc.slice(t,i)}},t.advance=function(e){if(e.index++,e.index>e.sheetSrc.length)throw this.parseError(e,"Advanced beyond the end")},t.eatUntil=function(e,t){for(var n=t.index;!this.lookAhead(e,t);)this.advance(t);return t.sheetSrc.slice(n,t.index)},t.parseSelector=function(e){var t=e.index;if(this.eatUntil("{",e),t===e.index)throw Error("Empty selector");return e.sheetSrc.slice(t,e.index)},t.eatWhitespace=function(e){z.WHITE_SPACE.lastIndex=e.index;var t=z.WHITE_SPACE.exec(e.sheetSrc);t&&(e.index+=t[0].length)},t.lookAhead=function(e,t){return t.sheetSrc.substr(t.index,e.length)==e},t.peek=function(e){return e.sheetSrc[e.index]},t.extractMatches=function(e,t){return t.exec(e)[1].trim().split(",").map(function(e){return e.trim()})},e}());function B(e){var t=z.SOURCE_ELEMENT.exec(e);return t?document.getElementById(t[1]):"auto"===e?document.scrollingElement:null}function K(e,t){for(;e;){if(e==t)return!0;e=e.parentNode}return!1}if(c.push({parse:function(e){if(e.target)return new H(e)},evaluate:function(e,t,n,i){"block"==t?t="vertical":"inline"==t&&(t="horizontal");for(var r,a=e==document.scrollingElement?{left:0,right:e.clientWidth,top:0,bottom:e.clientHeight,width:e.clientWidth,height:e.clientHeight}:e.getBoundingClientRect(),o=V.get(n).rootMargin,l=[],s=0;s<4;s++)l.push("percent"==(r=o[s])[1]?r[0]*(s%2==0?a.height:a.width)/100:r[0]);var u=a.left-l[3],c=a.right-a.left+l[3]+l[1],m=a.top-l[0],f=a.bottom-a.top+l[0]+l[2],h=V.get(n).clamp,d=n.target.getBoundingClientRect(),p=n.threshold;if("start"==n.edge&&(p=1-p),"vertical"==t){var g=d.top+d.height*p-m+e.scrollTop;return h?"end"==n.edge?Math.max(0,g-f):Math.min(g,e.scrollHeight-f):"end"==n.edge?g-f:g}var v=d.left+d.width*p-u+e.scrollLeft;return h?"end"==n.edge?Math.max(0,v-c):Math.min(v,e.scrollWidth-c):"end"==n.edge?v-c:v}}),CSS.supports("animation-timeline: works")||(function(){function e(e){if(0!==e.innerHTML.trim().length){var t=q.transpileStyleSheet(e.innerHTML,!0);t=q.transpileStyleSheet(t,!1),e.innerHTML=t}}new MutationObserver(function(t){for(var n,i=o(t);!(n=i()).done;)for(var r,a=o(n.value.addedNodes);!(r=a()).done;){var l=r.value;l instanceof HTMLStyleElement&&e(l)}}).observe(document.documentElement,{childList:!0,subtree:!0}),document.querySelectorAll("style").forEach(function(t){return e(t)}),document.querySelectorAll("link").forEach(function(e){})}(),window.addEventListener("animationstart",function(e){e.target.getAnimations().filter(function(t){return t.animationName===e.animationName}).forEach(function(t){var i=q.getScrollTimelineName(t.animationName,e.target);if(i){var r=function(e){var t=q.scrollTimelineOptions.get(e);if(!t)return null;var i=B(t.source),r=function(e,t){var i=void 0;if(t)if("none"==t);else{for(var r,a=o(i=t.split(",").map(function(e){return e.trim()}).filter(function(e){return""!=e}).map(function(e){return function(e){if("auto"==e)return new CSSKeywordValue("auto");var t=z.OFFSET_WITH_SUFFIX.exec(e);if(t)return new CSSUnitValue(parseInt(t[1]),t[2]);var i=z.ELEMENT_OFFSET.exec(e);return i&&document.getElementById(i[1])?n({target:document.getElementById(i[1])},i.length>=3?{edge:i[2]}:{},i.length>=4?{threshold:parseFloat(i[3])}:{}):null}(e)}).filter(function(e){return e}));!(r=a()).done;){var l=r.value;if(l.target&&l.target instanceof Element&&("none"==window.getComputedStyle(l.target,null).display||!K(l.target,e)))return null}if(0==i.length)return null}return i}(i,t["scroll-offsets"]);return null!==r?new ScrollTimeline(n({},i?{source:B(t.source)}:{},r?{scrollOffsets:r}:{},"auto"!=t.orientation?{orientation:t.orientation}:{})):null}(i);if(t.timeline!=r){var a=new _(t,r);t.pause(),a.play()}}})})),!Reflect.defineProperty(window,"ScrollTimeline",{value:T}))throw Error("Error installing ScrollTimeline polyfill: could not attach ScrollTimeline to window");if(!Reflect.defineProperty(Element.prototype,"animate",{value:function(e,t){var n=t.timeline;n instanceof T&&delete t.timeline;var i=S.apply(this,[e,t]),r=new _(i,n);return n instanceof T&&(i.pause(),r.play()),r}}))throw Error("Error installing ScrollTimeline polyfill: could not attach WAAPI's animate to DOM Element");if(!Reflect.defineProperty(window,"Animation",{value:_}))throw Error("Error installing Animation constructor.")}(); //# sourceMappingURL=scroll-timeline.js.map diff --git a/dist/scroll-timeline.js.map b/dist/scroll-timeline.js.map index 6d8b6bb3..81a4c514 100644 --- a/dist/scroll-timeline.js.map +++ b/dist/scroll-timeline.js.map @@ -1 +1 @@ -{"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","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