UNPKG

scroll-seamless

Version:

A seamless scroll library for JS, Vue, and React.

12 lines (11 loc) 36.2 kB
import e,{forwardRef as t,useRef as n,useState as s,useImperativeHandle as r,useEffect as i}from"react";var o,a={exports:{}},l={};var c,h,u={}; /** * @license React * react-jsx-runtime.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */function p(){return c||(c=1,"production"!==process.env.NODE_ENV&&function(){var t=e,n=Symbol.for("react.element"),s=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),a=Symbol.for("react.provider"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),p=Symbol.for("react.suspense_list"),d=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),m=Symbol.for("react.offscreen"),y=Symbol.iterator;var g=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function v(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];!function(e,t,n){var s=g.ReactDebugCurrentFrame,r=s.getStackAddendum();""!==r&&(t+="%s",n=n.concat([r]));var i=n.map(function(e){return String(e)});i.unshift("Warning: "+t),Function.prototype.apply.call(console[e],console,i)}("error",e,n)}var b;function w(e){return e.displayName||"Context"}function S(e){if(null==e)return null;if("number"==typeof e.tag&&v("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),"function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case r:return"Fragment";case s:return"Portal";case o:return"Profiler";case i:return"StrictMode";case h:return"Suspense";case p:return"SuspenseList"}if("object"==typeof e)switch(e.$$typeof){case l:return w(e)+".Consumer";case a:return w(e._context)+".Provider";case c:return function(e,t,n){var s=e.displayName;if(s)return s;var r=t.displayName||t.name||"";return""!==r?n+"("+r+")":n}(e,e.render,"ForwardRef");case d:var t=e.displayName||null;return null!==t?t:S(e.type)||"Memo";case f:var n=e,u=n._payload,m=n._init;try{return S(m(u))}catch(e){return null}}return null}b=Symbol.for("react.module.reference");var E,x,C,k,O,T,_,R=Object.assign,$=0;function j(){}j.__reactDisabledLog=!0;var z,D=g.ReactCurrentDispatcher;function I(e,t,n){if(void 0===z)try{throw Error()}catch(e){var s=e.stack.trim().match(/\n( *(at )?)/);z=s&&s[1]||""}return"\n"+z+e}var P,N=!1,M="function"==typeof WeakMap?WeakMap:Map;function F(e,t){if(!e||N)return"";var n,s=P.get(e);if(void 0!==s)return s;N=!0;var r,i=Error.prepareStackTrace;Error.prepareStackTrace=void 0,r=D.current,D.current=null,function(){if(0===$){E=console.log,x=console.info,C=console.warn,k=console.error,O=console.group,T=console.groupCollapsed,_=console.groupEnd;var e={configurable:!0,enumerable:!0,value:j,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}$++}();try{if(t){var o=function(){throw Error()};if(Object.defineProperty(o.prototype,"props",{set:function(){throw Error()}}),"object"==typeof Reflect&&Reflect.construct){try{Reflect.construct(o,[])}catch(e){n=e}Reflect.construct(e,[],o)}else{try{o.call()}catch(e){n=e}e.call(o.prototype)}}else{try{throw Error()}catch(e){n=e}e()}}catch(t){if(t&&n&&"string"==typeof t.stack){for(var a=t.stack.split("\n"),l=n.stack.split("\n"),c=a.length-1,h=l.length-1;c>=1&&h>=0&&a[c]!==l[h];)h--;for(;c>=1&&h>=0;c--,h--)if(a[c]!==l[h]){if(1!==c||1!==h)do{if(c--,--h<0||a[c]!==l[h]){var u="\n"+a[c].replace(" at new "," at ");return e.displayName&&u.includes("<anonymous>")&&(u=u.replace("<anonymous>",e.displayName)),"function"==typeof e&&P.set(e,u),u}}while(c>=1&&h>=0);break}}}finally{N=!1,D.current=r,function(){if(0===--$){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:R({},e,{value:E}),info:R({},e,{value:x}),warn:R({},e,{value:C}),error:R({},e,{value:k}),group:R({},e,{value:O}),groupCollapsed:R({},e,{value:T}),groupEnd:R({},e,{value:_})})}$<0&&v("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}(),Error.prepareStackTrace=i}var p=e?e.displayName||e.name:"",d=p?I(p):"";return"function"==typeof e&&P.set(e,d),d}function A(e,t,n){if(null==e)return"";if("function"==typeof e)return F(e,!(!(s=e.prototype)||!s.isReactComponent));var s;if("string"==typeof e)return I(e);switch(e){case h:return I("Suspense");case p:return I("SuspenseList")}if("object"==typeof e)switch(e.$$typeof){case c:return F(e.render,!1);case d:return A(e.type,t,n);case f:var r=e,i=r._payload,o=r._init;try{return A(o(i),t,n)}catch(e){}}return""}P=new M;var L=Object.prototype.hasOwnProperty,H={},W=g.ReactDebugCurrentFrame;function Y(e){if(e){var t=e._owner,n=A(e.type,e._source,t?t.type:null);W.setExtraStackFrame(n)}else W.setExtraStackFrame(null)}var q=Array.isArray;function X(e){return q(e)}function K(e){return""+e}function U(e){if(function(e){try{return K(e),!1}catch(e){return!0}}(e))return v("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",function(e){return"function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object"}(e)),K(e)}var V,B,J=g.ReactCurrentOwner,G={key:!0,ref:!0,__self:!0,__source:!0};function Q(e,t,s,r,i){var o,a={},l=null,c=null;for(o in void 0!==s&&(U(s),l=""+s),function(e){if(L.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return void 0!==e.key}(t)&&(U(t.key),l=""+t.key),function(e){if(L.call(e,"ref")){var t=Object.getOwnPropertyDescriptor(e,"ref").get;if(t&&t.isReactWarning)return!1}return void 0!==e.ref}(t)&&(c=t.ref,function(e){"string"==typeof e.ref&&J.current}(t)),t)L.call(t,o)&&!G.hasOwnProperty(o)&&(a[o]=t[o]);if(e&&e.defaultProps){var h=e.defaultProps;for(o in h)void 0===a[o]&&(a[o]=h[o])}if(l||c){var u="function"==typeof e?e.displayName||e.name||"Unknown":e;l&&function(e,t){var n=function(){V||(V=!0,v("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",t))};n.isReactWarning=!0,Object.defineProperty(e,"key",{get:n,configurable:!0})}(a,u),c&&function(e,t){var n=function(){B||(B=!0,v("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",t))};n.isReactWarning=!0,Object.defineProperty(e,"ref",{get:n,configurable:!0})}(a,u)}return function(e,t,s,r,i,o,a){var l={$$typeof:n,type:e,key:t,ref:s,props:a,_owner:o,_store:{}};return Object.defineProperty(l._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(l,"_self",{configurable:!1,enumerable:!1,writable:!1,value:r}),Object.defineProperty(l,"_source",{configurable:!1,enumerable:!1,writable:!1,value:i}),Object.freeze&&(Object.freeze(l.props),Object.freeze(l)),l}(e,l,c,i,r,J.current,a)}var Z,ee=g.ReactCurrentOwner,te=g.ReactDebugCurrentFrame;function ne(e){if(e){var t=e._owner,n=A(e.type,e._source,t?t.type:null);te.setExtraStackFrame(n)}else te.setExtraStackFrame(null)}function se(e){return"object"==typeof e&&null!==e&&e.$$typeof===n}function re(){if(ee.current){var e=S(ee.current.type);if(e)return"\n\nCheck the render method of `"+e+"`."}return""}Z=!1;var ie={};function oe(e,t){if(e._store&&!e._store.validated&&null==e.key){e._store.validated=!0;var n=function(e){var t=re();if(!t){var n="string"==typeof e?e:e.displayName||e.name;n&&(t="\n\nCheck the top-level render call using <"+n+">.")}return t}(t);if(!ie[n]){ie[n]=!0;var s="";e&&e._owner&&e._owner!==ee.current&&(s=" It was passed a child from "+S(e._owner.type)+"."),ne(e),v('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',n,s),ne(null)}}}function ae(e,t){if("object"==typeof e)if(X(e))for(var n=0;n<e.length;n++){var s=e[n];se(s)&&oe(s,t)}else if(se(e))e._store&&(e._store.validated=!0);else if(e){var r=function(e){if(null===e||"object"!=typeof e)return null;var t=y&&e[y]||e["@@iterator"];return"function"==typeof t?t:null}(e);if("function"==typeof r&&r!==e.entries)for(var i,o=r.call(e);!(i=o.next()).done;)se(i.value)&&oe(i.value,t)}}function le(e){var t,n=e.type;if(null!=n&&"string"!=typeof n){if("function"==typeof n)t=n.propTypes;else{if("object"!=typeof n||n.$$typeof!==c&&n.$$typeof!==d)return;t=n.propTypes}if(t){var s=S(n);!function(e,t,n,s,r){var i=Function.call.bind(L);for(var o in e)if(i(e,o)){var a=void 0;try{if("function"!=typeof e[o]){var l=Error((s||"React class")+": "+n+" type `"+o+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[o]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw l.name="Invariant Violation",l}a=e[o](t,o,s,n,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(e){a=e}!a||a instanceof Error||(Y(r),v("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",s||"React class",n,o,typeof a),Y(null)),a instanceof Error&&!(a.message in H)&&(H[a.message]=!0,Y(r),v("Failed %s type: %s",n,a.message),Y(null))}}(t,e.props,"prop",s,e)}else if(void 0!==n.PropTypes&&!Z){Z=!0,v("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",S(n)||"Unknown")}"function"!=typeof n.getDefaultProps||n.getDefaultProps.isReactClassApproved||v("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}var ce={};function he(e,t,s,u,y,g){var w=function(e){return"string"==typeof e||"function"==typeof e||e===r||e===o||e===i||e===h||e===p||e===m||"object"==typeof e&&null!==e&&(e.$$typeof===f||e.$$typeof===d||e.$$typeof===a||e.$$typeof===l||e.$$typeof===c||e.$$typeof===b||void 0!==e.getModuleId)}(e);if(!w){var E="";(void 0===e||"object"==typeof e&&null!==e&&0===Object.keys(e).length)&&(E+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var x;E+=re(),null===e?x="null":X(e)?x="array":void 0!==e&&e.$$typeof===n?(x="<"+(S(e.type)||"Unknown")+" />",E=" Did you accidentally export a JSX literal instead of a component?"):x=typeof e,v("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",x,E)}var C=Q(e,t,s,y,g);if(null==C)return C;if(w){var k=t.children;if(void 0!==k)if(u)if(X(k)){for(var O=0;O<k.length;O++)ae(k[O],e);Object.freeze&&Object.freeze(k)}else v("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else ae(k,e)}if(L.call(t,"key")){var T=S(e),_=Object.keys(t).filter(function(e){return"key"!==e}),R=_.length>0?"{key: someKey, "+_.join(": ..., ")+": ...}":"{key: someKey}";if(!ce[T+R])v('A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />',R,T,_.length>0?"{"+_.join(": ..., ")+": ...}":"{}",T),ce[T+R]=!0}return e===r?function(e){for(var t=Object.keys(e.props),n=0;n<t.length;n++){var s=t[n];if("children"!==s&&"key"!==s){ne(e),v("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",s),ne(null);break}}null!==e.ref&&(ne(e),v("Invalid attribute `ref` supplied to `React.Fragment`."),ne(null))}(C):le(C),C}var ue=function(e,t,n){return he(e,t,n,!1)},pe=function(e,t,n){return he(e,t,n,!0)};u.Fragment=r,u.jsx=ue,u.jsxs=pe}()),u}var d=(h||(h=1,"production"===process.env.NODE_ENV?a.exports=function(){if(o)return l;o=1;var t=e,n=Symbol.for("react.element"),s=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,i=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,a={key:!0,ref:!0,__self:!0,__source:!0};function c(e,t,s){var o,l={},c=null,h=null;for(o in void 0!==s&&(c=""+s),void 0!==t.key&&(c=""+t.key),void 0!==t.ref&&(h=t.ref),t)r.call(t,o)&&!a.hasOwnProperty(o)&&(l[o]=t[o]);if(e&&e.defaultProps)for(o in t=e.defaultProps)void 0===l[o]&&(l[o]=t[o]);return{$$typeof:n,type:e,key:c,ref:h,props:l,_owner:i.current}}return l.Fragment=s,l.jsx=c,l.jsxs=c,l}():a.exports=p()),a.exports);class f{constructor(){this.cleanupTasks=[],this.eventListeners=new Map,this.observers=[],this.timers=new Set,this.intervals=new Set,this.rafIds=new Set,this.isDestroyed=!1}addCleanupTask(e){this.isDestroyed||this.cleanupTasks.push(e)}addEventListener(e,t,n,s){if(this.isDestroyed)return;e.addEventListener(t,n,s),this.eventListeners.has(e)||this.eventListeners.set(e,new Map);const r=this.eventListeners.get(e);r.has(t)||r.set(t,[]),r.get(t).push(n)}removeEventListener(e,t,n){e.removeEventListener(t,n);const s=this.eventListeners.get(e);if(s){const e=s.get(t);if(e){const t=e.indexOf(n);t>-1&&e.splice(t,1)}}}createMutationObserver(e,t,n){if(this.isDestroyed)throw new Error("MemoryManager已销毁,无法创建新的Observer");const s=new MutationObserver(e);return s.observe(t,n),this.observers.push(s),s}setTimeout(e,t){if(this.isDestroyed)return-1;const n=window.setTimeout(()=>{this.timers.delete(n),e()},t);return this.timers.add(n),n}setInterval(e,t){if(this.isDestroyed)return-1;const n=window.setInterval(e,t);return this.intervals.add(n),n}clearTimeout(e){window.clearTimeout(e),this.timers.delete(e)}clearInterval(e){window.clearInterval(e),this.intervals.delete(e)}requestAnimationFrame(e){if(this.isDestroyed)return-1;const t=requestAnimationFrame(n=>{this.rafIds.delete(t),e(n)});return this.rafIds.add(t),t}cancelAnimationFrame(e){cancelAnimationFrame(e),this.rafIds.delete(e)}getMemoryStats(){return{cleanupTasks:this.cleanupTasks.length,eventListeners:Array.from(this.eventListeners.values()).reduce((e,t)=>e+Array.from(t.values()).reduce((e,t)=>e+t.length,0),0),observers:this.observers.length,timers:this.timers.size,intervals:this.intervals.size,rafIds:this.rafIds.size,isDestroyed:this.isDestroyed}}destroy(){if(!this.isDestroyed){this.isDestroyed=!0,this.cleanupTasks.forEach(e=>{try{e()}catch(e){console.warn("清理任务执行失败:",e)}}),this.cleanupTasks.length=0;for(const[e,t]of this.eventListeners)for(const[n,s]of t)s.forEach(t=>{try{e.removeEventListener(n,t)}catch(e){console.warn("移除事件监听器失败:",e)}});this.eventListeners.clear(),this.observers.forEach(e=>{try{e.disconnect()}catch(e){console.warn("断开Observer失败:",e)}}),this.observers.length=0,this.timers.forEach(e=>window.clearTimeout(e)),this.timers.clear(),this.intervals.forEach(e=>window.clearInterval(e)),this.intervals.clear(),this.rafIds.forEach(e=>cancelAnimationFrame(e)),this.rafIds.clear()}}}class m{constructor(e,t,n=5,s=50){this.pool=[],this.created=0,this.factory=e,this.reset=t,this.maxSize=s;for(let e=0;e<n;e++)this.pool.push(this.factory()),this.created++}acquire(){return this.pool.length>0?this.pool.pop():(this.created++,this.factory())}release(e){this.pool.length<this.maxSize&&(this.reset(e),this.pool.push(e))}clear(){this.pool.length=0}getStats(){return{poolSize:this.pool.length,totalCreated:this.created,maxSize:this.maxSize}}}class y{constructor(){this.animations=new Map,this.isRunning=!1,this.rafId=null,this.lastTimestamp=0,this.frameCount=0,this.droppedFrames=0,this.fpsHistory=[],this.maxFPSHistory=60,this.frameTimeThreshold=16.67,this.tick=()=>{if(!this.isRunning)return;const e=performance.now(),t=e-this.lastTimestamp;if(this.updateFPS(t),t<.8*this.frameTimeThreshold)return void(this.rafId=requestAnimationFrame(this.tick));const n=Array.from(this.animations.values()).sort((e,t)=>e.priority-t.priority),s=[];let r=0;const i=1.2*this.frameTimeThreshold;for(const t of n){if(t.paused)continue;const n=performance.now();try{t.callback(e)||s.push(t.id),t.lastFrameTime=e}catch(e){console.error(`动画执行错误 (${t.id}):`,e),s.push(t.id)}if(r+=performance.now()-n,r>i){this.droppedFrames++;break}}s.forEach(e=>{this.animations.delete(e)}),this.lastTimestamp=e,this.frameCount++,this.animations.size>0?this.rafId=requestAnimationFrame(this.tick):this.stop()}}static getInstance(){return y.instance||(y.instance=new y),y.instance}schedule(e){e.startTime=performance.now(),this.animations.set(e.id,e),this.isRunning||this.start()}unschedule(e){this.animations.delete(e),0===this.animations.size&&this.stop()}pause(e){const t=this.animations.get(e);t&&(t.paused=!0)}resume(e){const t=this.animations.get(e);t&&(t.paused=!1)}pauseAll(){this.animations.forEach(e=>{e.paused=!0})}resumeAll(){this.animations.forEach(e=>{e.paused=!1})}start(){this.isRunning||(this.isRunning=!0,this.lastTimestamp=performance.now(),this.tick())}stop(){this.isRunning=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null)}updateFPS(e){const t=1e3/e;this.fpsHistory.push(t),this.fpsHistory.length>this.maxFPSHistory&&this.fpsHistory.shift()}getPerformanceMetrics(){const e=this.fpsHistory.length>0?this.fpsHistory.reduce((e,t)=>e+t,0)/this.fpsHistory.length:0;return{fps:Math.round(e),frameTime:this.fpsHistory.length>0?1e3/e:0,droppedFrames:this.droppedFrames,activeAnimations:this.animations.size}}getStatus(){return{isRunning:this.isRunning,frameCount:this.frameCount,...this.getPerformanceMetrics()}}resetStats(){this.frameCount=0,this.droppedFrames=0,this.fpsHistory.length=0}destroy(){this.stop(),this.animations.clear(),this.resetStats(),y.instance=null}}y.instance=null;class g{static generateId(e="anim"){return`${e}_${++this.idCounter}_${Date.now()}`}static createTransformAnimation(e,t,n,s,r=e=>e){const i=this.generateId("transform");let o=null;return{id:i,priority:1,callback:i=>{o||(o=i);const a=i-o,l=Math.min(a/s,1),c=r(l),h=t.x+(n.x-t.x)*c,u=t.y+(n.y-t.y)*c;return e.style.transform=`translate(${h}px, ${u}px)`,l<1}}}static createScrollAnimation(e,t,n,s){const r=this.generateId("scroll");let i=0,o=null;return{id:r,priority:1,callback:r=>{o||(o=r);const a=n*(r-o)/16.67;switch(t){case"left":case"up":i+=a,i>=s&&(i=0);break;case"right":case"down":i-=a,i<=-s&&(i=0)}return e.style.transform="left"===t||"right"===t?`translateX(${-i}px)`:`translateY(${-i}px)`,o=r,!0}}}}g.idCounter=0;const v=y.getInstance();class b{constructor(e){this.cache=new Map,this.capacity=e}get(e){if(this.cache.has(e)){const t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){const e=this.cache.keys().next().value;void 0!==e&&this.cache.delete(e)}this.cache.set(e,t)}clear(){this.cache.clear()}size(){return this.cache.size}}class w{constructor(e=100){this.resizeObserver=null,this.observedElements=new WeakSet,this.cacheTimeout=5e3,this.measurementCache=new b(e),this.textSizeCache=new b(2*e),"undefined"!=typeof ResizeObserver&&(this.resizeObserver=new ResizeObserver(e=>{e.forEach(e=>{const t=e.target,n=this.getElementKey(t);this.measurementCache.set(n,this.measureElement(t))})}))}getElementKey(e){var t;return`${e.tagName}_${e.className}_${e.id}_${null===(t=e.textContent)||void 0===t?void 0:t.slice(0,50)}`}getTextKey(e,t,n){return`${e}_${t}_${n||""}`}measureElement(e){const t=e.getBoundingClientRect();return{width:t.width,height:t.height,offsetWidth:e.offsetWidth,offsetHeight:e.offsetHeight,scrollWidth:e.scrollWidth,scrollHeight:e.scrollHeight,timestamp:Date.now()}}getElementMeasurement(e,t=!1){const n=this.getElementKey(e);if(!t){const e=this.measurementCache.get(n);if(e&&Date.now()-e.timestamp<this.cacheTimeout)return e}this.resizeObserver&&!this.observedElements.has(e)&&(this.resizeObserver.observe(e),this.observedElements.add(e));const s=this.measureElement(e);return this.measurementCache.set(n,s),s}measureText(e,t="ss-item",n){const s=n?JSON.stringify(n):"",r=this.getTextKey(e,t,s),i=this.textSizeCache.get(r);if(i)return i;const o=document.createElement("span");o.className=t,o.textContent=e,o.style.position="absolute",o.style.visibility="hidden",o.style.whiteSpace="nowrap",n&&Object.assign(o.style,n),document.body.appendChild(o);const a={width:o.offsetWidth,height:o.offsetHeight};return document.body.removeChild(o),this.textSizeCache.set(r,a),a}measureTextBatch(e,t="ss-item",n){const s=[],r=[];if(e.forEach((e,i)=>{const o=n?JSON.stringify(n):"",a=this.getTextKey(e,t,o),l=this.textSizeCache.get(a);l?s[i]=l:r.push({text:e,index:i})}),r.length>0){const e=document.createElement("div");e.style.position="absolute",e.style.visibility="hidden",e.style.whiteSpace="nowrap",document.body.appendChild(e),r.forEach(({text:r,index:i})=>{const o=document.createElement("span");o.className=t,o.textContent=r,n&&Object.assign(o.style,n),e.appendChild(o);const a={width:o.offsetWidth,height:o.offsetHeight};s[i]=a;const l=n?JSON.stringify(n):"",c=this.getTextKey(r,t,l);this.textSizeCache.set(c,a)}),document.body.removeChild(e)}return s}clearExpiredCache(){const e=new b(this.measurementCache.size());this.measurementCache.clear(),this.measurementCache=e}getCacheStats(){return{measurementCacheSize:this.measurementCache.size(),textCacheSize:this.textSizeCache.size(),observedElements:this.observedElements?"WeakSet (无法计数)":0,hasResizeObserver:!!this.resizeObserver}}destroy(){this.measurementCache.clear(),this.textSizeCache.clear(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null)}}class S{constructor(e){this.plugins=new Map,this.controller=e}register(e){if(this.plugins.has(e.id))console.warn(`Plugin with id "${e.id}" is already registered. Skipping.`);else try{e.apply(this.controller),this.plugins.set(e.id,e)}catch(t){console.error(`Failed to register plugin "${e.id}":`,t)}}unregister(e){const t=this.plugins.get(e);if(t)try{t.destroy&&t.destroy(),this.plugins.delete(e)}catch(t){console.error(`Failed to unregister plugin "${e}":`,t)}else console.warn(`Plugin with id "${e}" is not registered. Skipping.`)}getPlugin(e){return this.plugins.get(e)||null}getPlugins(){return Array.from(this.plugins.values())}destroyAll(){for(const[e,t]of this.plugins.entries())try{t.destroy&&t.destroy()}catch(t){console.error(`Failed to destroy plugin "${e}":`,t)}this.plugins.clear()}}const E=class{constructor(e,t){if(this.running=!1,this.rowStates=[],this.colStates=[],this.seamlessData=[],this.seamlessColData=[],!e)throw new Error("ScrollEngine: Container element is required");if(!t.data||!Array.isArray(t.data)||0===t.data.length)throw new Error("ScrollEngine: Data array is required and cannot be empty");this.container=e,this.options=this.mergeOptions(t),this.memoryManager=new f,this.domCache=new w,this.elementPool=new m(()=>document.createElement("span"),e=>{e.className="ss-item",e.textContent="",e.removeAttribute("style")}),this.pluginManager=new S(this),this.options.plugins&&this.options.plugins.length>0&&this.options.plugins.forEach(e=>{this.pluginManager.register(e)}),this.initialize()}mergeOptions(e){return{data:[],direction:"left",minCountToScroll:2,step:1,stepWait:0,delay:0,bezier:[.25,.1,.25,1],hoverStop:!0,wheelEnable:!1,singleLine:!1,rows:1,cols:1,onEvent:()=>{},plugins:[],performance:{enabled:!0},accessibility:{enabled:!0},dataDriven:!1,...e}}initialize(){try{this.setupContainer(),this.createScrollElements(),this.bindEvents(),this.layout(),this.shouldScroll()&&this.start()}catch(e){console.error("ScrollEngine initialization failed:",e),this.handleError(e)}}setupContainer(){this.container.style.overflow="hidden",this.container.style.position="relative"}createScrollElements(){"left"===this.options.direction||"right"===this.options.direction?this.createHorizontalElements():this.createVerticalElements()}createHorizontalElements(){const e=Math.max(1,this.options.rows);for(let t=0;t<e;t++){const n=this.createElement("div","scroll-seamless-row");this.setElementStyle(n,{position:"absolute",left:"0",top:100/e*t+"%",width:"100%",height:100/e+"%",overflow:"hidden",display:"flex",alignItems:"center"});const s=this.createElement("div","ss-content"),r=this.createElement("div","ss-content");this.setContentStyle(s,!0),this.setContentStyle(r,!0),s.style.left="0",n.appendChild(s),n.appendChild(r),this.container.appendChild(n),this.rowStates.push({content1:s,content2:r,position:0,animationId:null})}}createVerticalElements(){const e=Math.max(1,this.options.cols);for(let t=0;t<e;t++){const t=this.createElement("div","scroll-seamless-col");this.setElementStyle(t,{position:"relative",height:"100%",overflow:"hidden",width:100/e+"%",display:"inline-block",textAlign:"center"});const n=this.createElement("div","ss-content"),s=this.createElement("div","ss-content");this.setContentStyle(n,!1),this.setContentStyle(s,!1),n.style.top="0",t.appendChild(n),t.appendChild(s),this.container.appendChild(t),this.colStates.push({content1:n,content2:s,position:0,animationId:null})}}createElement(e,t){const n=document.createElement(e);return n.className=t,n}setElementStyle(e,t){Object.assign(e.style,t)}setContentStyle(e,t){const n={position:"absolute",top:"0",left:"0",boxSizing:"border-box",display:t?"inline-block":"block",whiteSpace:t?"nowrap":"normal"};t||(n.width="100%"),this.setElementStyle(e,n)}bindEvents(){this.options.hoverStop&&(this.memoryManager.addEventListener(this.container,"mouseenter",this.onMouseEnter.bind(this)),this.memoryManager.addEventListener(this.container,"mouseleave",this.onMouseLeave.bind(this))),this.options.wheelEnable&&this.memoryManager.addEventListener(this.container,"wheel",e=>{this.onWheel(e)},{passive:!1})}layout(){"left"===this.options.direction||"right"===this.options.direction?this.layoutHorizontal():this.layoutVertical(),this.renderContent()}layoutHorizontal(){this.seamlessData=[];for(let e=0;e<this.rowStates.length;e++){const t=this.rowStates[e].content1.parentElement;if(!t)continue;const n=this.domCache.getElementMeasurement(t).width,s=this.calculateSeamlessItems(n,!0);this.seamlessData[e]=s}}layoutVertical(){this.seamlessColData=[];for(let e=0;e<this.colStates.length;e++){const t=this.colStates[e].content1.parentElement;if(!t)continue;const n=this.domCache.getElementMeasurement(t).height,s=this.calculateSeamlessItems(n,!1);this.seamlessColData[e]=s}}calculateSeamlessItems(e,t){const n=[];let s=0;const r=3*e+50,i=this.domCache.measureTextBatch(this.options.data,"ss-item"),o=t?5:2;let a=0;for(;s<r&&a<20*this.options.data.length;){const e=a%this.options.data.length,r=this.options.data[e],l=i[e];n.push(r),s+=(t?l.width:l.height)+o,a++}return n}renderContent(){"left"===this.options.direction||"right"===this.options.direction?this.renderHorizontalContent():this.renderVerticalContent()}renderHorizontalContent(){for(let e=0;e<this.rowStates.length;e++){const t=this.rowStates[e],n=this.seamlessData[e]||[];this.renderStateContent(t,n)}}renderVerticalContent(){for(let e=0;e<this.colStates.length;e++){const t=this.colStates[e],n=this.seamlessColData[e]||[];this.renderStateContent(t,n)}}renderStateContent(e,t){e.content1.innerHTML="",e.content2.innerHTML="";const n="left"===this.options.direction||"right"===this.options.direction;t.forEach((t,s)=>{let r,i;if(this.options.renderItem){const n=this.rowStates.indexOf(e)>=0?this.rowStates.indexOf(e):void 0,o=this.colStates.indexOf(e)>=0?this.colStates.indexOf(e):void 0;r=this.options.renderItem(t,s,n,o),i=r.cloneNode(!0)}else r=this.elementPool.acquire(),i=this.elementPool.acquire(),r.textContent=t,i.textContent=t,n?(r.style.marginRight="10px",i.style.marginRight="10px",r.style.display="inline-block",i.style.display="inline-block"):(r.style.marginBottom="5px",i.style.marginBottom="5px",r.style.display="block",i.style.display="block");e.content1.appendChild(r),e.content2.appendChild(i)})}shouldScroll(){return this.options.data.length>=this.options.minCountToScroll}start(){var e,t;if(this.running)return;this.running=!0,null===(t=(e=this.options).onEvent)||void 0===t||t.call(e,"start",{direction:this.options.direction});("left"===this.options.direction||"right"===this.options.direction?this.rowStates:this.colStates).forEach((e,t)=>{const n=g.generateId("scroll");e.animationId=n;const s=this.createScrollAnimation(e,t);v.schedule(s)})}createScrollAnimation(e,t){const n="left"===this.options.direction||"right"===this.options.direction,s="right"===this.options.direction||"down"===this.options.direction,r=n?e.content1.scrollWidth:e.content1.scrollHeight;return n?e.content2.style.left=`${r}px`:e.content2.style.top=`${r}px`,e.position=0,n?(e.content1.style.transform="translateX(0)",e.content2.style.transform="translateX(0)",e.content2.style.left=`${r}px`):(e.content1.style.transform="translateY(0)",e.content2.style.transform="translateY(0)",e.content2.style.top=`${r}px`),{id:e.animationId,priority:1,callback:t=>{if(!this.running)return!1;const i=this.options.step;return s?(e.position-=i,e.position<=-r&&(e.position=0)):(e.position+=i,e.position>=r&&(e.position=0)),n?(e.content1.style.transform=`translateX(${s?e.position:-e.position}px)`,e.content2.style.transform=`translateX(${s?e.position:-e.position}px)`):(e.content1.style.transform=`translateY(${s?e.position:-e.position}px)`,e.content2.style.transform=`translateY(${s?e.position:-e.position}px)`),!0}}}stop(){var e,t;this.running&&(this.running=!1,null===(t=(e=this.options).onEvent)||void 0===t||t.call(e,"stop",{direction:this.options.direction}),[...this.rowStates,...this.colStates].forEach(e=>{e.animationId&&(v.unschedule(e.animationId),e.animationId=null)}))}destroy(){var e,t;this.stop(),this.pluginManager.destroyAll(),this.memoryManager.destroy(),this.domCache.destroy(),this.elementPool.clear(),this.container.innerHTML="",null===(t=(e=this.options).onEvent)||void 0===t||t.call(e,"destroy",{direction:this.options.direction})}updateData(){const e=this.running;e&&this.stop(),[...this.rowStates,...this.colStates].forEach(e=>{e.position=0,e.content1.style.transform="",e.content2.style.transform=""}),this.layout(),e&&this.shouldScroll()&&setTimeout(()=>this.start(),20)}setOptions(e){const t=this.running;this.stop(),this.options={...this.options,...e},this.layout(),t&&this.shouldScroll()&&this.start()}isRunning(){return this.running}getRenderMatrix(){return"left"===this.options.direction||"right"===this.options.direction?this.seamlessData:this.seamlessColData}getTransforms(){const e="left"===this.options.direction||"right"===this.options.direction;return(e?this.rowStates:this.colStates).map(t=>e?`translateX(${-t.position}px)`:`translateY(${-t.position}px)`)}addPlugin(e){this.pluginManager.register(e)}removePlugin(e){this.pluginManager.unregister(e)}getPosition(){const e="left"===this.options.direction||"right"===this.options.direction?this.rowStates:this.colStates;return 0===e.length?0:e[0].position}setPosition(e){const t="left"===this.options.direction||"right"===this.options.direction;(t?this.rowStates:this.colStates).forEach(n=>{n.position=e;const s=t?n.content1.scrollWidth:n.content1.scrollHeight,r=t?`translateX(${-e}px)`:`translateY(${-e}px)`,i=t?`translateX(${-e+s}px)`:`translateY(${-e+s}px)`;n.content1.style.transform=r,n.content2.style.transform=i})}getPerformance(){const e=this.pluginManager.getPlugin("performance");return e&&"getMetrics"in e?e.getMetrics():{fps:v.getPerformanceMetrics().fps,memory:null,timing:{renderTime:0,animationTime:0},elements:{total:this.container.querySelectorAll("*").length,visible:this.container.querySelectorAll(".ss-item").length}}}onMouseEnter(){this.options.hoverStop&&this.stop()}onMouseLeave(){this.options.hoverStop&&this.shouldScroll()&&this.start()}onWheel(e){this.options.wheelEnable&&e.preventDefault()}handleError(e){var t,n;console.error("ScrollEngine Error:",e),null===(n=(t=this.options).onEvent)||void 0===n||n.call(t,"error",{type:"error",direction:this.options.direction,error:e.message,stack:e.stack});try{this.stop(),this.rowStates.forEach(e=>{e.position=0,e.content1.style.transform="none",e.content2.style.transform="none"}),this.colStates.forEach(e=>{e.position=0,e.content1.style.transform="none",e.content2.style.transform="none"}),this.options.performance&&this.options.performance.autoRestart&&setTimeout(()=>{this.shouldScroll()&&this.start()},1e3)}catch(e){console.error("ScrollEngine Recovery Failed:",e)}}},x=["left","right","up","down"],C=(e,t)=>{const o=n(null),a=n(null),l=n(null),c="undefined"!=typeof window&&window.navigator&&window.navigator.userAgent&&window.navigator.userAgent.includes("jsdom"),[h,u]=s(c?[e.data||[]]:[]),[p,f]=s(c?["none","none"]:[]);r(t,()=>({start:()=>a.current&&a.current.start(),stop:()=>a.current&&a.current.stop(),destroy:()=>a.current&&a.current.destroy(),updateData:()=>{var e;null===(e=a.current)||void 0===e||e.updateData(),m()},setOptions:e=>{var t;return null===(t=a.current)||void 0===t?void 0:t.setOptions(e)},isRunning:()=>{var e;return null===(e=a.current)||void 0===e?void 0:e.isRunning()}}),[]);const m=()=>{if(c)return u([e.data||[]]),void f(["none","none"]);a.current&&(a.current.getRenderMatrix&&u(a.current.getRenderMatrix()),a.current.getTransforms&&f(a.current.getTransforms()))},y=()=>{o.current&&window.ResizeObserver&&(l.current=new ResizeObserver(()=>{a.current&&a.current.updateData(),m()}),l.current.observe(o.current))},g=()=>{l.current&&l.current.disconnect(),l.current=null};i(()=>{if(!c){if(o.current){const t=x.includes(e.direction)?e.direction:"left",n={...e,direction:t,dataDriven:!0};a.current=new E(o.current,n),!1===e.running&&a.current.stop(),setTimeout(()=>{m(),y()},0)}return()=>{var e;null===(e=a.current)||void 0===e||e.destroy(),g()}}},[]),i(()=>{c||a.current&&void 0!==e.running&&(e.running?a.current.start():a.current.stop())},[e.running]),i(()=>{if(c)return u([e.data||[]]),void f(["none","none"]);a.current&&a.current.updateData(),setTimeout(()=>{m(),g(),y()},0)},[e.data]);const v={position:"absolute",top:0,left:0,display:"left"===e.direction||"right"===e.direction?"inline-block":"block",whiteSpace:"left"===e.direction||"right"===e.direction?"nowrap":"normal",verticalAlign:"left"===e.direction||"right"===e.direction?"middle":"baseline",boxSizing:"border-box",padding:"left"===e.direction||"right"===e.direction?"0 5px":"5px 0"},b={display:"inline-block",marginRight:"10px",verticalAlign:"middle"},w=e.rows||1,S=e.cols||1,C=e=>({position:"absolute",left:0,top:100/w*e+"%",width:"100%",height:100/w+"%",overflow:"hidden",display:"flex",alignItems:"center"});return d.jsx("div",{ref:o,className:e.className,style:{width:"100%",height:"100%",overflow:"hidden",position:"relative",...e.style},children:"left"===e.direction||"right"===e.direction?h.map((t,n)=>d.jsxs("div",{className:"scroll-seamless-row",style:C(n),children:[d.jsx("div",{className:`ss-content ss-content-1 ${e.contentClassName||""}`,style:{...v,transform:p[2*n]},children:t.map((t,s)=>e.children?e.children(t,s,n,void 0):d.jsx("span",{className:e.itemClassName,style:b,children:t},s))}),d.jsx("div",{className:`ss-content ss-content-2 ${e.contentClassName||""}`,style:{...v,transform:p[2*n+1]},children:t.map((t,s)=>e.children?e.children(t,s,n,void 0):d.jsx("span",{className:e.itemClassName,style:b,children:t},`dup-${s}`))})]},n)):h.map((t,n)=>d.jsxs("div",{className:"scroll-seamless-col",style:{position:"relative",width:100/S+"%",height:"100%",display:"inline-block",overflow:"hidden",textAlign:"center"},children:[d.jsx("div",{className:`ss-content ss-content-1 ${e.contentClassName||""}`,style:{...v,transform:p[2*n]},children:t.map((t,s)=>e.children?e.children(t,s,void 0,n):d.jsx("span",{className:e.itemClassName,style:b,children:t},s))}),d.jsx("div",{className:`ss-content ss-content-2 ${e.contentClassName||""}`,style:{...v,transform:p[2*n+1]},children:t.map((t,s)=>e.children?e.children(t,s,void 0,n):d.jsx("span",{className:e.itemClassName,style:b,children:t},`dup-${s}`))})]},n))})};C.defaultProps={direction:"left"};const k=t(C);export{k as default}; //# sourceMappingURL=index.esm.js.map