motion-dom.js 18 KB

1
  1. !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("motion-utils")):"function"==typeof define&&define.amd?define(["exports","motion-utils"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).MotionDom={},t.MotionUtils)}(this,(function(t,e){"use strict";const n=e.memo((()=>void 0!==window.ScrollTimeline));class i{constructor(t){this.stop=()=>this.runAll("stop"),this.animations=t.filter(Boolean)}get finished(){return Promise.all(this.animations.map((t=>t.finished)))}getAll(t){return this.animations[0][t]}setAll(t,e){for(let n=0;n<this.animations.length;n++)this.animations[n][t]=e}attachTimeline(t,e){const i=this.animations.map((i=>n()&&i.attachTimeline?i.attachTimeline(t):"function"==typeof e?e(i):void 0));return()=>{i.forEach(((t,e)=>{t&&t(),this.animations[e].stop()}))}}get time(){return this.getAll("time")}set time(t){this.setAll("time",t)}get speed(){return this.getAll("speed")}set speed(t){this.setAll("speed",t)}get startTime(){return this.getAll("startTime")}get duration(){let t=0;for(let e=0;e<this.animations.length;e++)t=Math.max(t,this.animations[e].duration);return t}runAll(t){this.animations.forEach((e=>e[t]()))}flatten(){this.runAll("flatten")}play(){this.runAll("play")}pause(){this.runAll("pause")}cancel(){this.runAll("cancel")}complete(){this.runAll("complete")}}const a=t=>t.startsWith("--"),r=(t,e,n)=>{a(e)?t.style.setProperty(e,n):t.style[e]=n},o=(t,e)=>a(e)?t.style.getPropertyValue(e):t.style[e],s=t=>null!==t;const u=e.memo((()=>{try{document.createElement("div").animate({opacity:[1]})}catch(t){return!1}return!0})),c=new Set(["borderWidth","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderRadius","radius","borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius","width","maxWidth","height","maxHeight","top","right","bottom","left","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","margin","marginTop","marginRight","marginBottom","marginLeft","backgroundPositionX","backgroundPositionY"]);const l={layout:0,mainThread:0,waapi:0},d={value:null,addProjectionMetrics:null},m=t=>Array.isArray(t)&&"number"==typeof t[0],h={};function p(t,n){const i=e.memo(t);return()=>h[n]??i()}const f=p((()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch(t){return!1}return!0}),"linearEasing"),y=(t,e,n=10)=>{let i="";const a=Math.max(Math.round(e/n),2);for(let e=0;e<a;e++)i+=t(e/(a-1))+", ";return`linear(${i.substring(0,i.length-2)})`},g=([t,e,n,i])=>`cubic-bezier(${t}, ${e}, ${n}, ${i})`,v={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:g([0,.65,.55,1]),circOut:g([.55,0,1,.45]),backIn:g([.31,.01,.66,-.59]),backOut:g([.33,1.53,.69,.99])};function w(t,e){return t?"function"==typeof t&&f()?y(t,e):m(t)?g(t):Array.isArray(t)?t.map((t=>w(t,e)||v.easeOut)):v[t]:void 0}function T(t,e,n,{delay:i=0,duration:a=300,repeat:r=0,repeatType:o="loop",ease:s="easeInOut",times:u}={},c=void 0){const m={[e]:n};u&&(m.offset=u);const h=w(s,a);Array.isArray(h)&&(m.easing=h),d.value&&l.waapi++;const p=t.animate(m,{delay:i,duration:a,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:r+1,direction:"reverse"===o?"alternate":"normal",pseudoElement:c});return d.value&&p.finished.finally((()=>{l.waapi--})),p}function A(t){return"function"==typeof t&&"applyToOptions"in t}function E({type:t,...e}){return A(t)?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}const b=new WeakMap;class P{constructor(t){if("animation"in t)return void(this.animation=t.animation);const{element:n,name:i,keyframes:a,pseudoElement:l,allowFlatten:d=!1}=t;let{transition:m}=t;this.isPseudoElement=Boolean(l),this.allowFlatten=d;const h=function(t){const e=b.get(t)||new Map;return b.set(t,e),e}(n),p=((t,e)=>`${t}:${e}`)(i,l||""),f=h.get(p);f&&f.stop();const y=function(t,e,n,i){Array.isArray(n)||(n=[n]);for(let a=0;a<n.length;a++)null===n[a]&&(n[a]=0!==a||i?n[a-1]:o(t,e)),"number"==typeof n[a]&&c.has(e)&&(n[a]=n[a]+"px");return!i&&!u()&&n.length<2&&n.unshift(o(t,e)),n}(n,i,a,l);e.invariant("string"!=typeof m.type,'animateMini doesn\'t support "type" as a string. Did you mean to import { spring } from "motion"?'),m=E(m),this.animation=T(n,i,y,m,l),!1===m.autoplay&&this.animation.pause(),this.removeAnimation=()=>h.delete(p),this.animation.onfinish=()=>{l||(r(n,i,function(t,{repeat:e,repeatType:n="loop"},i){const a=t.filter(s),r=e&&"loop"!==n&&e%2==1?0:a.length-1;return r&&void 0!==i?i:a[r]}(y,m)),this.cancel())},h.set(p,this)}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.finish()}cancel(){try{this.animation.cancel()}catch(t){}this.removeAnimation()}stop(){const{state:t}=this;"idle"!==t&&"finished"!==t&&(this.commitStyles(),this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const t=this.animation.effect?.getComputedTiming().duration||0;return e.millisecondsToSeconds(Number(t))}get time(){return e.millisecondsToSeconds(Number(this.animation.currentTime)||0)}set time(t){this.animation.currentTime=e.secondsToMilliseconds(t)}get speed(){return this.animation.playbackRate}set speed(t){this.animation.playbackRate=t}get state(){return this.animation.playState}get startTime(){return Number(this.animation.startTime)}get finished(){return this.animation.finished}flatten(){this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"})}attachTimeline(t){return this.animation.timeline=t,this.animation.onfinish=null,e.noop}then(t,e){return this.finished.then(t).catch(e)}}function x(t,e){return t?.[e]??t?.default??t}const M=2e4;function k(t){let e=0;let n=t.next(e);for(;!n.done&&e<M;)e+=50,n=t.next(e);return e>=M?1/0:e}const R=["read","resolveKeyframes","update","preRender","render","postRender"];function S(t,n){let i=!1,a=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>i=!0,s=R.reduce(((t,e)=>(t[e]=function(t,e){let n=new Set,i=new Set,a=!1,r=!1;const o=new WeakSet;let s={delta:0,timestamp:0,isProcessing:!1},u=0;function c(e){o.has(e)&&(l.schedule(e),t()),u++,e(s)}const l={schedule:(t,e=!1,r=!1)=>{const s=r&&a?n:i;return e&&o.add(t),s.has(t)||s.add(t),t},cancel:t=>{i.delete(t),o.delete(t)},process:t=>{s=t,a?r=!0:(a=!0,[n,i]=[i,n],n.forEach(c),e&&d.value&&d.value.frameloop[e].push(u),u=0,n.clear(),a=!1,r&&(r=!1,l.process(t)))}};return l}(o,n?e:void 0),t)),{}),{read:u,resolveKeyframes:c,update:l,preRender:m,render:h,postRender:p}=s,f=()=>{const o=e.MotionGlobalConfig.useManualTiming?r.timestamp:performance.now();i=!1,e.MotionGlobalConfig.useManualTiming||(r.delta=a?1e3/60:Math.max(Math.min(o-r.timestamp,40),1)),r.timestamp=o,r.isProcessing=!0,u.process(r),c.process(r),l.process(r),m.process(r),h.process(r),p.process(r),r.isProcessing=!1,i&&n&&(a=!1,t(f))};return{schedule:R.reduce(((e,n)=>{const o=s[n];return e[n]=(e,n=!1,s=!1)=>(i||(i=!0,a=!0,r.isProcessing||t(f)),o.schedule(e,n,s)),e}),{}),cancel:t=>{for(let e=0;e<R.length;e++)s[R[e]].cancel(t)},state:r,steps:s}}const{schedule:L,cancel:V,state:j,steps:C}=S("undefined"!=typeof requestAnimationFrame?requestAnimationFrame:e.noop,!0),{schedule:F,cancel:W}=S(queueMicrotask,!1);let B;function N(){B=void 0}const D={now:()=>(void 0===B&&D.set(j.isProcessing||e.MotionGlobalConfig.useManualTiming?j.timestamp:performance.now()),B),set:t=>{B=t,queueMicrotask(N)}},O={x:!1,y:!1};function $(){return O.x||O.y}function G(t,e,n){if(t instanceof EventTarget)return[t];if("string"==typeof t){let i=document;e&&(i=e.current);const a=n?.[t]??i.querySelectorAll(t);return a?Array.from(a):[]}return Array.from(t)}function I(t,e){const n=G(t),i=new AbortController;return[n,{passive:!0,...e,signal:i.signal},()=>i.abort()]}function q(t){return!("touch"===t.pointerType||$())}const K=(t,e)=>!!e&&(t===e||K(t,e.parentElement)),U=t=>"mouse"===t.pointerType?"number"!=typeof t.button||t.button<=0:!1!==t.isPrimary,z=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);const H=new WeakSet;function X(t){return e=>{"Enter"===e.key&&t(e)}}function Y(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}function J(t){return U(t)&&!$()}function Q(){const{value:t}=d;null!==t?(t.frameloop.rate.push(j.delta),t.animations.mainThread.push(l.mainThread),t.animations.waapi.push(l.waapi),t.animations.layout.push(l.layout)):V(Q)}function Z(t){return t.reduce(((t,e)=>t+e),0)/t.length}function _(t,e=Z){return 0===t.length?{min:0,max:0,avg:0}:{min:Math.min(...t),max:Math.max(...t),avg:e(t)}}const tt=t=>Math.round(1e3/t);function et(){d.value=null,d.addProjectionMetrics=null}function nt(){const{value:t}=d;if(!t)throw new Error("Stats are not being measured");et(),V(Q);const e={frameloop:{rate:_(t.frameloop.rate),read:_(t.frameloop.read),resolveKeyframes:_(t.frameloop.resolveKeyframes),update:_(t.frameloop.update),preRender:_(t.frameloop.preRender),render:_(t.frameloop.render),postRender:_(t.frameloop.postRender)},animations:{mainThread:_(t.animations.mainThread),waapi:_(t.animations.waapi),layout:_(t.animations.layout)},layoutProjection:{nodes:_(t.layoutProjection.nodes),calculatedTargetDeltas:_(t.layoutProjection.calculatedTargetDeltas),calculatedProjections:_(t.layoutProjection.calculatedProjections)}},{rate:n}=e.frameloop;return n.min=tt(n.min),n.max=tt(n.max),n.avg=tt(n.avg),[n.min,n.max]=[n.max,n.min],e}const it={current:void 0};class at{constructor(t,e={}){this.version="12.7.3",this.canTrackVelocity=null,this.events={},this.updateAndNotify=(t,e=!0)=>{const n=D.now();this.updatedAt!==n&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(t),this.current!==this.prev&&this.events.change&&this.events.change.notify(this.current),e&&this.events.renderRequest&&this.events.renderRequest.notify(this.current)},this.hasAnimated=!1,this.setCurrent(t),this.owner=e.owner}setCurrent(t){var e;this.current=t,this.updatedAt=D.now(),null===this.canTrackVelocity&&void 0!==t&&(this.canTrackVelocity=(e=this.current,!isNaN(parseFloat(e))))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return this.on("change",t)}on(t,n){this.events[t]||(this.events[t]=new e.SubscriptionManager);const i=this.events[t].add(n);return"change"===t?()=>{i(),L.read((()=>{this.events.change.getSize()||this.stop()}))}:i}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,e){this.passiveEffect=t,this.stopPassiveEffect=e}set(t,e=!0){e&&this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t,e)}setWithVelocity(t,e,n){this.set(e),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-n}jump(t,e=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,e&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}get(){return it.current&&it.current.push(this),this.current}getPrevious(){return this.prev}getVelocity(){const t=D.now();if(!this.canTrackVelocity||void 0===this.prevFrameValue||t-this.updatedAt>30)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,30);return e.velocityPerSecond(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(t){return this.stop(),new Promise((e=>{this.hasAnimated=!0,this.animation=t(e),this.events.animationStart&&this.events.animationStart.notify()})).then((()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()}))}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function rt(t){return"layout"===t?"group":"enter"===t||"new"===t?"new":"exit"===t||"old"===t?"old":"group"}let ot={},st=null;const ut=(t,e)=>{ot[t]=e},ct=()=>{st||(st=document.createElement("style"),st.id="motion-view");let t="";for(const e in ot){const n=ot[e];t+=`${e} {\n`;for(const[e,i]of Object.entries(n))t+=` ${e}: ${i};\n`;t+="}\n"}st.textContent=t,document.head.appendChild(st),ot={}},lt=()=>{st&&st.parentElement&&st.parentElement.removeChild(st)};function dt(t){const e=t.match(/::view-transition-(old|new|group|image-pair)\((.*?)\)/);return e?{layer:e[2],type:e[1]}:null}function mt(t){const{effect:e}=t;return!!e&&(e.target===document.documentElement&&e.pseudoElement?.startsWith("::view-transition"))}const ht=["layout","enter","exit","new","old"];function pt(t){const{update:n,targets:a,options:r}=t;if(!document.startViewTransition)return new Promise((async t=>{await n(),t(new i([]))}));(function(t,e){return e.has(t)&&Object.keys(e.get(t)).length>0})("root",a)||ut(":root",{"view-transition-name":"none"}),ut("::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*)",{"animation-timing-function":"linear !important"}),ct();const o=document.startViewTransition((async()=>{await n()}));return o.finished.finally((()=>{lt()})),new Promise((t=>{o.ready.then((()=>{const n=document.getAnimations().filter(mt),o=[];a.forEach(((t,n)=>{for(const i of ht){if(!t[i])continue;const{keyframes:a,options:s}=t[i];for(let[t,u]of Object.entries(a)){if(!u)continue;const a={...x(r,t),...x(s,t)},c=rt(i);if("opacity"===t&&!Array.isArray(u)){u=["new"===c?0:1,u]}"function"==typeof a.delay&&(a.delay=a.delay(0,1)),a.duration&&(a.duration=e.secondsToMilliseconds(a.duration)),a.delay&&(a.delay=e.secondsToMilliseconds(a.delay));const l=new P({element:document.documentElement,name:t,pseudoElement:`::view-transition-${c}(${n})`,keyframes:u,transition:a});o.push(l)}}}));for(const t of n){if("finished"===t.playState)continue;const{effect:n}=t;if(!(n&&n instanceof KeyframeEffect))continue;const{pseudoElement:i}=n;if(!i)continue;const s=dt(i);if(!s)continue;const u=a.get(s.layer);if(u)ft(u,"enter")&&ft(u,"exit")&&n.getKeyframes().some((t=>t.mixBlendMode))?o.push(new P({animation:t})):t.cancel();else{const i="group"===s.type?"layout":"";let a={...x(r,i)};a.duration&&(a.duration=e.secondsToMilliseconds(a.duration)),a=E(a);const u=w(a.ease,a.duration);n.updateTiming({delay:e.secondsToMilliseconds(a.delay??0),duration:a.duration,easing:u}),o.push(new P({animation:t}))}}t(new i(o))}))}))}function ft(t,e){return t?.[e]?.keyframes.opacity}let yt=[],gt=null;function vt(){gt=null;const[t]=yt;var n;t&&(n=t,e.removeItem(yt,n),gt=n,pt(n).then((t=>{n.notifyReady(t),t.finished.finally(vt)})))}function wt(){for(let t=yt.length-1;t>=0;t--){const e=yt[t],{interrupt:n}=e.options;if("immediate"===n){const n=yt.slice(0,t+1).map((t=>t.update)),i=yt.slice(t+1);e.update=()=>{n.forEach((t=>t()))},yt=[e,...i];break}}gt&&"immediate"!==yt[0]?.options.interrupt||vt()}class Tt{constructor(t,n={}){var i;this.currentTarget="root",this.targets=new Map,this.notifyReady=e.noop,this.readyPromise=new Promise((t=>{this.notifyReady=t})),this.update=t,this.options={interrupt:"wait",...n},i=this,yt.push(i),F.render(wt)}get(t){return this.currentTarget=t,this}layout(t,e){return this.updateTarget("layout",t,e),this}new(t,e){return this.updateTarget("new",t,e),this}old(t,e){return this.updateTarget("old",t,e),this}enter(t,e){return this.updateTarget("enter",t,e),this}exit(t,e){return this.updateTarget("exit",t,e),this}crossfade(t){return this.updateTarget("enter",{opacity:1},t),this.updateTarget("exit",{opacity:0},t),this}updateTarget(t,e,n={}){const{currentTarget:i,targets:a}=this;a.has(i)||a.set(i,{});a.get(i)[t]={keyframes:e,options:n}}then(t,e){return this.readyPromise.then(t,e)}}const At=L,Et=R.reduce(((t,e)=>(t[e]=t=>V(t),t)),{});t.GroupAnimation=i,t.GroupAnimationWithThen=class extends i{then(t,e){return this.finished.finally(t).then((()=>{}))}},t.MotionValue=at,t.NativeAnimation=P,t.ViewTransitionBuilder=Tt,t.activeAnimations=l,t.animateView=function(t,e={}){return new Tt(t,e)},t.attachTimeline=function(t,e){t.timeline=e,t.onfinish=null},t.calcGeneratorDuration=k,t.cancelFrame=V,t.cancelMicrotask=W,t.cancelSync=Et,t.collectMotionValues=it,t.createGeneratorEasing=function(t,n=100,i){const a=i({...t,keyframes:[0,n]}),r=Math.min(k(a),M);return{type:"keyframes",ease:t=>a.next(r*t).value/n,duration:e.millisecondsToSeconds(r)}},t.createRenderBatcher=S,t.cubicBezierAsString=g,t.frame=L,t.frameData=j,t.frameSteps=C,t.generateLinearEasing=y,t.getValueTransition=x,t.hover=function(t,e,n={}){const[i,a,r]=I(t,n),o=t=>{if(!q(t))return;const{target:n}=t,i=e(n,t);if("function"!=typeof i||!n)return;const r=t=>{q(t)&&(i(t),n.removeEventListener("pointerleave",r))};n.addEventListener("pointerleave",r,a)};return i.forEach((t=>{t.addEventListener("pointerenter",o,a)})),r},t.isBezierDefinition=m,t.isDragActive=$,t.isDragging=O,t.isGenerator=A,t.isNodeOrChild=K,t.isPrimaryPointer=U,t.isWaapiSupportedEasing=function t(e){return Boolean("function"==typeof e&&f()||!e||"string"==typeof e&&(e in v||f())||m(e)||Array.isArray(e)&&e.every(t))},t.mapEasingToNativeEasing=w,t.maxGeneratorDuration=M,t.microtask=F,t.motionValue=function(t,e){return new at(t,e)},t.press=function(t,e,n={}){const[i,a,r]=I(t,n),o=t=>{const i=t.currentTarget;if(!J(t)||H.has(i))return;H.add(i);const r=e(i,t),o=(t,e)=>{window.removeEventListener("pointerup",s),window.removeEventListener("pointercancel",u),J(t)&&H.has(i)&&(H.delete(i),"function"==typeof r&&r(t,{success:e}))},s=t=>{o(t,i===window||i===document||n.useGlobalTarget||K(i,t.target))},u=t=>{o(t,!1)};window.addEventListener("pointerup",s,a),window.addEventListener("pointercancel",u,a)};return i.forEach((t=>{var e;(n.useGlobalTarget?window:t).addEventListener("pointerdown",o,a),t instanceof HTMLElement&&(t.addEventListener("focus",(t=>((t,e)=>{const n=t.currentTarget;if(!n)return;const i=X((()=>{if(H.has(n))return;Y(n,"down");const t=X((()=>{Y(n,"up")}));n.addEventListener("keyup",t,e),n.addEventListener("blur",(()=>Y(n,"cancel")),e)}));n.addEventListener("keydown",i,e),n.addEventListener("blur",(()=>n.removeEventListener("keydown",i)),e)})(t,a))),e=t,z.has(e.tagName)||-1!==e.tabIndex||t.hasAttribute("tabindex")||(t.tabIndex=0))})),r},t.recordStats=function(){if(d.value)throw et(),new Error("Stats are already being measured");const t=d;return t.value={frameloop:{rate:[],read:[],resolveKeyframes:[],update:[],preRender:[],render:[],postRender:[]},animations:{mainThread:[],waapi:[],layout:[]},layoutProjection:{nodes:[],calculatedTargetDeltas:[],calculatedProjections:[]}},t.addProjectionMetrics=e=>{const{layoutProjection:n}=t.value;n.nodes.push(e.nodes),n.calculatedTargetDeltas.push(e.calculatedTargetDeltas),n.calculatedProjections.push(e.calculatedProjections)},L.postRender(Q,!0),nt},t.resolveElements=G,t.setDragLock=function(t){return"x"===t||"y"===t?O[t]?null:(O[t]=!0,()=>{O[t]=!1}):O.x||O.y?null:(O.x=O.y=!0,()=>{O.x=O.y=!1})},t.startWaapiAnimation=T,t.statsBuffer=d,t.supportedWaapiEasing=v,t.supportsFlags=h,t.supportsLinearEasing=f,t.supportsScrollTimeline=n,t.sync=At,t.time=D}));