scroll-seamless
Version:
A seamless scroll library for JS, Vue, and React.
12 lines (11 loc) • 29.9 kB
JavaScript
import t,{forwardRef as e,useRef as s,useState as n,useImperativeHandle as i,useEffect as r}from"react";var o,a={exports:{}},l={};var c,h,d={};
/**
* @license React
* react-jsx-runtime.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/function u(){return c||(c=1,"production"!==process.env.NODE_ENV&&function(){function e(t){if(null==t)return null;if("function"==typeof t)return t.$$typeof===k?null:t.displayName||t.name||null;if("string"==typeof t)return t;switch(t){case m:return"Fragment";case y:return"Profiler";case f:return"StrictMode";case S:return"Suspense";case w:return"SuspenseList";case C:return"Activity"}if("object"==typeof t)switch("number"==typeof t.tag&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),t.$$typeof){case p:return"Portal";case v:return(t.displayName||"Context")+".Provider";case g:return(t._context.displayName||"Context")+".Consumer";case b:var s=t.render;return(t=t.displayName)||(t=""!==(t=s.displayName||s.name||"")?"ForwardRef("+t+")":"ForwardRef"),t;case E:return null!==(s=t.displayName||null)?s:e(t.type)||"Memo";case x:s=t._payload,t=t._init;try{return e(t(s))}catch(t){}}return null}function s(t){return""+t}function n(t){try{s(t);var e=!1}catch(t){e=!0}if(e){var n=(e=console).error,i="function"==typeof Symbol&&Symbol.toStringTag&&t[Symbol.toStringTag]||t.constructor.name||"Object";return n.call(e,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",i),s(t)}}function i(t){if(t===m)return"<>";if("object"==typeof t&&null!==t&&t.$$typeof===x)return"<...>";try{var s=e(t);return s?"<"+s+">":"<...>"}catch(t){return"<...>"}}function r(){return Error("react-stack-top-frame")}function o(){var t=e(this.type);return N[t]||(N[t]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),void 0!==(t=this.props.ref)?t:null}function a(t,s,i,r,a,h,d,p){var m,f=s.children;if(void 0!==f)if(r)if(z(f)){for(r=0;r<f.length;r++)l(f[r]);Object.freeze&&Object.freeze(f)}else console.error("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 l(f);if(O.call(s,"key")){f=e(t);var y=Object.keys(s).filter(function(t){return"key"!==t});r=0<y.length?"{key: someKey, "+y.join(": ..., ")+": ...}":"{key: someKey}",M[f+r]||(y=0<y.length?"{"+y.join(": ..., ")+": ...}":"{}",console.error('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,f,y,f),M[f+r]=!0)}if(f=null,void 0!==i&&(n(i),f=""+i),function(t){if(O.call(t,"key")){var e=Object.getOwnPropertyDescriptor(t,"key").get;if(e&&e.isReactWarning)return!1}return void 0!==t.key}(s)&&(n(s.key),f=""+s.key),"key"in s)for(var g in i={},s)"key"!==g&&(i[g]=s[g]);else i=s;return f&&function(t,e){function s(){c||(c=!0,console.error("%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://react.dev/link/special-props)",e))}s.isReactWarning=!0,Object.defineProperty(t,"key",{get:s,configurable:!0})}(i,"function"==typeof t?t.displayName||t.name||"Unknown":t),function(t,e,s,n,i,r,a,l){return s=r.ref,t={$$typeof:u,type:t,key:e,props:r,_owner:i},null!==(void 0!==s?s:null)?Object.defineProperty(t,"ref",{enumerable:!1,get:o}):Object.defineProperty(t,"ref",{enumerable:!1,value:null}),t._store={},Object.defineProperty(t._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(t,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(t,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:a}),Object.defineProperty(t,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:l}),Object.freeze&&(Object.freeze(t.props),Object.freeze(t)),t}(t,f,h,0,null===(m=T.A)?null:m.getOwner(),i,d,p)}function l(t){"object"==typeof t&&null!==t&&t.$$typeof===u&&t._store&&(t._store.validated=1)}var c,h=t,u=Symbol.for("react.transitional.element"),p=Symbol.for("react.portal"),m=Symbol.for("react.fragment"),f=Symbol.for("react.strict_mode"),y=Symbol.for("react.profiler"),g=Symbol.for("react.consumer"),v=Symbol.for("react.context"),b=Symbol.for("react.forward_ref"),S=Symbol.for("react.suspense"),w=Symbol.for("react.suspense_list"),E=Symbol.for("react.memo"),x=Symbol.for("react.lazy"),C=Symbol.for("react.activity"),k=Symbol.for("react.client.reference"),T=h.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,O=Object.prototype.hasOwnProperty,z=Array.isArray,$=console.createTask?console.createTask:function(){return null},N={},I=(h={react_stack_bottom_frame:function(t){return t()}}).react_stack_bottom_frame.bind(h,r)(),j=$(i(r)),M={};d.Fragment=m,d.jsx=function(t,e,s,n,r){var o=1e4>T.recentlyCreatedOwnerStacks++;return a(t,e,s,!1,0,r,o?Error("react-stack-top-frame"):I,o?$(i(t)):j)},d.jsxs=function(t,e,s,n,r){var o=1e4>T.recentlyCreatedOwnerStacks++;return a(t,e,s,!0,0,r,o?Error("react-stack-top-frame"):I,o?$(i(t)):j)}}()),d}var p=(h||(h=1,"production"===process.env.NODE_ENV?a.exports=function(){if(o)return l;o=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function s(e,s,n){var i=null;if(void 0!==n&&(i=""+n),void 0!==s.key&&(i=""+s.key),"key"in s)for(var r in n={},s)"key"!==r&&(n[r]=s[r]);else n=s;return s=n.ref,{$$typeof:t,type:e,key:i,ref:void 0!==s?s:null,props:n}}return l.Fragment=e,l.jsx=s,l.jsxs=s,l}():a.exports=u()),a.exports);class m{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(t){this.isDestroyed||this.cleanupTasks.push(t)}addEventListener(t,e,s,n){if(this.isDestroyed)return;t.addEventListener(e,s,n),this.eventListeners.has(t)||this.eventListeners.set(t,new Map);const i=this.eventListeners.get(t);i.has(e)||i.set(e,[]),i.get(e).push(s)}removeEventListener(t,e,s){t.removeEventListener(e,s);const n=this.eventListeners.get(t);if(n){const t=n.get(e);if(t){const e=t.indexOf(s);e>-1&&t.splice(e,1)}}}createMutationObserver(t,e,s){if(this.isDestroyed)throw new Error("MemoryManager已销毁,无法创建新的Observer");const n=new MutationObserver(t);return n.observe(e,s),this.observers.push(n),n}setTimeout(t,e){if(this.isDestroyed)return-1;const s=window.setTimeout(()=>{this.timers.delete(s),t()},e);return this.timers.add(s),s}setInterval(t,e){if(this.isDestroyed)return-1;const s=window.setInterval(t,e);return this.intervals.add(s),s}clearTimeout(t){window.clearTimeout(t),this.timers.delete(t)}clearInterval(t){window.clearInterval(t),this.intervals.delete(t)}requestAnimationFrame(t){if(this.isDestroyed)return-1;const e=requestAnimationFrame(s=>{this.rafIds.delete(e),t(s)});return this.rafIds.add(e),e}cancelAnimationFrame(t){cancelAnimationFrame(t),this.rafIds.delete(t)}getMemoryStats(){return{cleanupTasks:this.cleanupTasks.length,eventListeners:Array.from(this.eventListeners.values()).reduce((t,e)=>t+Array.from(e.values()).reduce((t,e)=>t+e.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(t=>{try{t()}catch(t){console.warn("清理任务执行失败:",t)}}),this.cleanupTasks.length=0;for(const[t,e]of this.eventListeners)for(const[s,n]of e)n.forEach(e=>{try{t.removeEventListener(s,e)}catch(t){console.warn("移除事件监听器失败:",t)}});this.eventListeners.clear(),this.observers.forEach(t=>{try{t.disconnect()}catch(t){console.warn("断开Observer失败:",t)}}),this.observers.length=0,this.timers.forEach(t=>window.clearTimeout(t)),this.timers.clear(),this.intervals.forEach(t=>window.clearInterval(t)),this.intervals.clear(),this.rafIds.forEach(t=>cancelAnimationFrame(t)),this.rafIds.clear()}}}class f{constructor(t,e,s=5,n=50){this.pool=[],this.created=0,this.factory=t,this.reset=e,this.maxSize=n;for(let t=0;t<s;t++)this.pool.push(this.factory()),this.created++}acquire(){return this.pool.length>0?this.pool.pop():(this.created++,this.factory())}release(t){this.pool.length<this.maxSize&&(this.reset(t),this.pool.push(t))}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 t=performance.now(),e=t-this.lastTimestamp;if(this.updateFPS(e),e<.8*this.frameTimeThreshold)return void(this.rafId=requestAnimationFrame(this.tick));const s=Array.from(this.animations.values()).sort((t,e)=>t.priority-e.priority),n=[];let i=0;const r=1.2*this.frameTimeThreshold;for(const e of s){if(e.paused)continue;const s=performance.now();try{e.callback(t)||n.push(e.id),e.lastFrameTime=t}catch(t){console.error(`动画执行错误 (${e.id}):`,t),n.push(e.id)}if(i+=performance.now()-s,i>r){this.droppedFrames++;break}}n.forEach(t=>{this.animations.delete(t)}),this.lastTimestamp=t,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(t){t.startTime=performance.now(),this.animations.set(t.id,t),this.isRunning||this.start()}unschedule(t){this.animations.delete(t),0===this.animations.size&&this.stop()}pause(t){const e=this.animations.get(t);e&&(e.paused=!0)}resume(t){const e=this.animations.get(t);e&&(e.paused=!1)}pauseAll(){this.animations.forEach(t=>{t.paused=!0})}resumeAll(){this.animations.forEach(t=>{t.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(t){const e=1e3/t;this.fpsHistory.push(e),this.fpsHistory.length>this.maxFPSHistory&&this.fpsHistory.shift()}getPerformanceMetrics(){const t=this.fpsHistory.length>0?this.fpsHistory.reduce((t,e)=>t+e,0)/this.fpsHistory.length:0;return{fps:Math.round(t),frameTime:this.fpsHistory.length>0?1e3/t: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(t="anim"){return`${t}_${++this.idCounter}_${Date.now()}`}static createTransformAnimation(t,e,s,n,i=t=>t){const r=this.generateId("transform");let o=null;return{id:r,priority:1,callback:r=>{o||(o=r);const a=r-o,l=Math.min(a/n,1),c=i(l),h=e.x+(s.x-e.x)*c,d=e.y+(s.y-e.y)*c;return t.style.transform=`translate(${h}px, ${d}px)`,l<1}}}static createScrollAnimation(t,e,s,n){const i=this.generateId("scroll");let r=0,o=null;return{id:i,priority:1,callback:i=>{o||(o=i);const a=s*(i-o)/16.67;switch(e){case"left":case"up":r+=a,r>=n&&(r=0);break;case"right":case"down":r-=a,r<=-n&&(r=0)}return t.style.transform="left"===e||"right"===e?`translateX(${-r}px)`:`translateY(${-r}px)`,o=i,!0}}}}g.idCounter=0;const v=y.getInstance();class b{constructor(t){this.cache=new Map,this.capacity=t}get(t){if(this.cache.has(t)){const e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}}set(t,e){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.capacity){const t=this.cache.keys().next().value;void 0!==t&&this.cache.delete(t)}this.cache.set(t,e)}clear(){this.cache.clear()}size(){return this.cache.size}}class S{constructor(t=100){this.resizeObserver=null,this.observedElements=new WeakSet,this.cacheTimeout=5e3,this.measurementCache=new b(t),this.textSizeCache=new b(2*t),"undefined"!=typeof ResizeObserver&&(this.resizeObserver=new ResizeObserver(t=>{t.forEach(t=>{const e=t.target,s=this.getElementKey(e);this.measurementCache.set(s,this.measureElement(e))})}))}getElementKey(t){var e;return`${t.tagName}_${t.className}_${t.id}_${null===(e=t.textContent)||void 0===e?void 0:e.slice(0,50)}`}getTextKey(t,e,s){return`${t}_${e}_${s||""}`}measureElement(t){const e=t.getBoundingClientRect();return{width:e.width,height:e.height,offsetWidth:t.offsetWidth,offsetHeight:t.offsetHeight,scrollWidth:t.scrollWidth,scrollHeight:t.scrollHeight,timestamp:Date.now()}}getElementMeasurement(t,e=!1){const s=this.getElementKey(t);if(!e){const t=this.measurementCache.get(s);if(t&&Date.now()-t.timestamp<this.cacheTimeout)return t}this.resizeObserver&&!this.observedElements.has(t)&&(this.resizeObserver.observe(t),this.observedElements.add(t));const n=this.measureElement(t);return this.measurementCache.set(s,n),n}measureText(t,e="ss-item",s){const n=s?JSON.stringify(s):"",i=this.getTextKey(t,e,n),r=this.textSizeCache.get(i);if(r)return r;const o=document.createElement("span");o.className=e,o.textContent=t,o.style.position="absolute",o.style.visibility="hidden",o.style.whiteSpace="nowrap",s&&Object.assign(o.style,s),document.body.appendChild(o);const a={width:o.offsetWidth,height:o.offsetHeight};return document.body.removeChild(o),this.textSizeCache.set(i,a),a}measureTextBatch(t,e="ss-item",s){const n=[],i=[];if(t.forEach((t,r)=>{const o=s?JSON.stringify(s):"",a=this.getTextKey(t,e,o),l=this.textSizeCache.get(a);l?n[r]=l:i.push({text:t,index:r})}),i.length>0){const t=document.createElement("div");t.style.position="absolute",t.style.visibility="hidden",t.style.whiteSpace="nowrap",document.body.appendChild(t),i.forEach(({text:i,index:r})=>{const o=document.createElement("span");o.className=e,o.textContent=i,s&&Object.assign(o.style,s),t.appendChild(o);const a={width:o.offsetWidth,height:o.offsetHeight};n[r]=a;const l=s?JSON.stringify(s):"",c=this.getTextKey(i,e,l);this.textSizeCache.set(c,a)}),document.body.removeChild(t)}return n}clearExpiredCache(){const t=new b(this.measurementCache.size());this.measurementCache.clear(),this.measurementCache=t}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 w{constructor(t){this.plugins=new Map,this.controller=t}register(t){if(this.plugins.has(t.id))console.warn(`Plugin with id "${t.id}" is already registered. Skipping.`);else try{t.apply(this.controller),this.plugins.set(t.id,t)}catch(e){console.error(`Failed to register plugin "${t.id}":`,e)}}unregister(t){const e=this.plugins.get(t);if(e)try{e.destroy&&e.destroy(),this.plugins.delete(t)}catch(e){console.error(`Failed to unregister plugin "${t}":`,e)}else console.warn(`Plugin with id "${t}" is not registered. Skipping.`)}getPlugin(t){return this.plugins.get(t)||null}getPlugins(){return Array.from(this.plugins.values())}destroyAll(){for(const[t,e]of this.plugins.entries())try{e.destroy&&e.destroy()}catch(e){console.error(`Failed to destroy plugin "${t}":`,e)}this.plugins.clear()}}const E=class{constructor(t,e){if(this.running=!1,this.rowStates=[],this.colStates=[],this.seamlessData=[],this.seamlessColData=[],!t)throw new Error("ScrollEngine: Container element is required");if(!e.data||!Array.isArray(e.data)||0===e.data.length)throw new Error("ScrollEngine: Data array is required and cannot be empty");this.container=t,this.options=this.mergeOptions(e),this.memoryManager=new m,this.domCache=new S,this.elementPool=new f(()=>document.createElement("span"),t=>{t.className="ss-item",t.textContent="",t.removeAttribute("style")}),this.pluginManager=new w(this),this.options.plugins&&this.options.plugins.length>0&&this.options.plugins.forEach(t=>{this.pluginManager.register(t)}),this.initialize()}mergeOptions(t){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,...t}}initialize(){try{this.setupContainer(),this.createScrollElements(),this.bindEvents(),this.layout(),this.shouldScroll()&&this.start()}catch(t){console.error("ScrollEngine initialization failed:",t),this.handleError(t)}}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 t=Math.max(1,this.options.rows);for(let e=0;e<t;e++){const s=this.createElement("div","scroll-seamless-row");this.setElementStyle(s,{position:"absolute",left:"0",top:100/t*e+"%",width:"100%",height:100/t+"%",overflow:"hidden",display:"flex",alignItems:"center"});const n=this.createElement("div","ss-content"),i=this.createElement("div","ss-content");this.setContentStyle(n,!0),this.setContentStyle(i,!0),n.style.left="0",s.appendChild(n),s.appendChild(i),this.container.appendChild(s),this.rowStates.push({content1:n,content2:i,position:0,animationId:null})}}createVerticalElements(){const t=Math.max(1,this.options.cols);for(let e=0;e<t;e++){const e=this.createElement("div","scroll-seamless-col");this.setElementStyle(e,{position:"relative",height:"100%",overflow:"hidden",width:100/t+"%",display:"inline-block",textAlign:"center"});const s=this.createElement("div","ss-content"),n=this.createElement("div","ss-content");this.setContentStyle(s,!1),this.setContentStyle(n,!1),s.style.top="0",e.appendChild(s),e.appendChild(n),this.container.appendChild(e),this.colStates.push({content1:s,content2:n,position:0,animationId:null})}}createElement(t,e){const s=document.createElement(t);return s.className=e,s}setElementStyle(t,e){Object.assign(t.style,e)}setContentStyle(t,e){const s={position:"absolute",top:"0",left:"0",boxSizing:"border-box",display:e?"inline-block":"block",whiteSpace:e?"nowrap":"normal"};e||(s.width="100%"),this.setElementStyle(t,s)}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",t=>{this.onWheel(t)},{passive:!1})}layout(){"left"===this.options.direction||"right"===this.options.direction?this.layoutHorizontal():this.layoutVertical(),this.renderContent()}layoutHorizontal(){this.seamlessData=[];for(let t=0;t<this.rowStates.length;t++){const e=this.rowStates[t].content1.parentElement;if(!e)continue;const s=this.domCache.getElementMeasurement(e).width,n=this.calculateSeamlessItems(s,!0);this.seamlessData[t]=n}}layoutVertical(){this.seamlessColData=[];for(let t=0;t<this.colStates.length;t++){const e=this.colStates[t].content1.parentElement;if(!e)continue;const s=this.domCache.getElementMeasurement(e).height,n=this.calculateSeamlessItems(s,!1);this.seamlessColData[t]=n}}calculateSeamlessItems(t,e){const s=[];let n=0;const i=3*t+50,r=this.domCache.measureTextBatch(this.options.data,"ss-item"),o=e?5:2;let a=0;for(;n<i&&a<20*this.options.data.length;){const t=a%this.options.data.length,i=this.options.data[t],l=r[t];s.push(i),n+=(e?l.width:l.height)+o,a++}return s}renderContent(){"left"===this.options.direction||"right"===this.options.direction?this.renderHorizontalContent():this.renderVerticalContent()}renderHorizontalContent(){for(let t=0;t<this.rowStates.length;t++){const e=this.rowStates[t],s=this.seamlessData[t]||[];this.renderStateContent(e,s)}}renderVerticalContent(){for(let t=0;t<this.colStates.length;t++){const e=this.colStates[t],s=this.seamlessColData[t]||[];this.renderStateContent(e,s)}}renderStateContent(t,e){t.content1.innerHTML="",t.content2.innerHTML="";const s="left"===this.options.direction||"right"===this.options.direction;e.forEach((e,n)=>{let i,r;if(this.options.renderItem){const s=this.rowStates.indexOf(t)>=0?this.rowStates.indexOf(t):void 0,o=this.colStates.indexOf(t)>=0?this.colStates.indexOf(t):void 0;i=this.options.renderItem(e,n,s,o),r=i.cloneNode(!0)}else i=this.elementPool.acquire(),r=this.elementPool.acquire(),i.textContent=e,r.textContent=e,s?(i.style.marginRight="10px",r.style.marginRight="10px",i.style.display="inline-block",r.style.display="inline-block"):(i.style.marginBottom="5px",r.style.marginBottom="5px",i.style.display="block",r.style.display="block");t.content1.appendChild(i),t.content2.appendChild(r)})}shouldScroll(){return this.options.data.length>=this.options.minCountToScroll}start(){var t,e;if(this.running)return;this.running=!0,null===(e=(t=this.options).onEvent)||void 0===e||e.call(t,"start",{direction:this.options.direction});("left"===this.options.direction||"right"===this.options.direction?this.rowStates:this.colStates).forEach((t,e)=>{void 0===t.position&&(t.position=0);const s=g.generateId("scroll");t.animationId=s;const n=this.createScrollAnimation(t,e);v.schedule(n)})}createScrollAnimation(t,e){const s="left"===this.options.direction||"right"===this.options.direction,n="right"===this.options.direction||"down"===this.options.direction,i=s?t.content1.scrollWidth:t.content1.scrollHeight;return s?t.content2.style.left=`${i}px`:t.content2.style.top=`${i}px`,s?(t.content1.style.transform="translateX(0)",t.content2.style.transform="translateX(0)",t.content2.style.left=`${i}px`):(t.content1.style.transform="translateY(0)",t.content2.style.transform="translateY(0)",t.content2.style.top=`${i}px`),{id:t.animationId,priority:1,callback:e=>{if(!this.running)return!1;const r=this.options.step;return n?(t.position-=r,t.position<=-i&&(t.position=0)):(t.position+=r,t.position>=i&&(t.position=0)),s?(t.content1.style.transform=`translateX(${n?t.position:-t.position}px)`,t.content2.style.transform=`translateX(${n?t.position:-t.position}px)`):(t.content1.style.transform=`translateY(${n?t.position:-t.position}px)`,t.content2.style.transform=`translateY(${n?t.position:-t.position}px)`),!0}}}stop(){var t,e;this.running&&(this.running=!1,null===(e=(t=this.options).onEvent)||void 0===e||e.call(t,"stop",{direction:this.options.direction}),[...this.rowStates,...this.colStates].forEach(t=>{t.animationId&&(v.unschedule(t.animationId),t.animationId=null)}))}pause(){var t,e;this.running&&([...this.rowStates,...this.colStates].forEach(t=>{t.animationId&&v.pause(t.animationId)}),null===(e=(t=this.options).onEvent)||void 0===e||e.call(t,"pause",{direction:this.options.direction}))}resume(){var t,e;this.running&&([...this.rowStates,...this.colStates].forEach(t=>{t.animationId&&v.resume(t.animationId)}),null===(e=(t=this.options).onEvent)||void 0===e||e.call(t,"resume",{direction:this.options.direction}))}destroy(){var t,e;this.stop(),this.pluginManager.destroyAll(),this.memoryManager.destroy(),this.domCache.destroy(),this.elementPool.clear(),this.container.innerHTML="",null===(e=(t=this.options).onEvent)||void 0===e||e.call(t,"destroy",{direction:this.options.direction})}updateData(){const t=this.running;t&&this.stop(),[...this.rowStates,...this.colStates].forEach(t=>{t.position=0,t.content1.style.transform="",t.content2.style.transform=""}),this.layout(),t&&this.shouldScroll()&&setTimeout(()=>this.start(),20)}setOptions(t){const e=this.running;this.stop(),this.options={...this.options,...t},this.layout(),e&&this.shouldScroll()&&this.start()}isRunning(){return this.running}getRenderMatrix(){return"left"===this.options.direction||"right"===this.options.direction?this.seamlessData:this.seamlessColData}getTransforms(){const t="left"===this.options.direction||"right"===this.options.direction;return(t?this.rowStates:this.colStates).map(e=>t?`translateX(${-e.position}px)`:`translateY(${-e.position}px)`)}addPlugin(t){this.pluginManager.register(t)}removePlugin(t){this.pluginManager.unregister(t)}getPosition(){const t="left"===this.options.direction||"right"===this.options.direction?this.rowStates:this.colStates;return 0===t.length?0:t[0].position}setPosition(t){const e="left"===this.options.direction||"right"===this.options.direction;(e?this.rowStates:this.colStates).forEach(s=>{s.position=t;const n=e?s.content1.scrollWidth:s.content1.scrollHeight,i=e?`translateX(${-t}px)`:`translateY(${-t}px)`,r=e?`translateX(${-t+n}px)`:`translateY(${-t+n}px)`;s.content1.style.transform=i,s.content2.style.transform=r})}getPerformance(){const t=this.pluginManager.getPlugin("performance");return t&&"getMetrics"in t?t.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.pause()}onMouseLeave(){this.options.hoverStop&&this.shouldScroll()&&this.resume()}onWheel(t){this.options.wheelEnable&&t.preventDefault()}handleError(t){var e,s;console.error("ScrollEngine Error:",t),null===(s=(e=this.options).onEvent)||void 0===s||s.call(e,"error",{type:"error",direction:this.options.direction,error:t.message,stack:t.stack});try{this.stop(),this.rowStates.forEach(t=>{t.position=0,t.content1.style.transform="none",t.content2.style.transform="none"}),this.colStates.forEach(t=>{t.position=0,t.content1.style.transform="none",t.content2.style.transform="none"}),this.options.performance&&this.options.performance.autoRestart&&setTimeout(()=>{this.shouldScroll()&&this.start()},1e3)}catch(t){console.error("ScrollEngine Recovery Failed:",t)}}},x=["left","right","up","down"],C=(t,e)=>{const o=s(null),a=s(null),l=s(null),c="undefined"!=typeof window&&window.navigator&&window.navigator.userAgent&&window.navigator.userAgent.includes("jsdom"),[h,d]=n(c?[t.data||[]]:[]),[u,m]=n(c?["none","none"]:[]);i(e,()=>({start:()=>a.current&&a.current.start(),stop:()=>a.current&&a.current.stop(),pause:()=>a.current&&a.current.pause(),resume:()=>a.current&&a.current.resume(),destroy:()=>a.current&&a.current.destroy(),updateData:()=>{var t;null===(t=a.current)||void 0===t||t.updateData(),f()},setOptions:t=>{var e;return null===(e=a.current)||void 0===e?void 0:e.setOptions(t)},isRunning:()=>{var t;return null===(t=a.current)||void 0===t?void 0:t.isRunning()}}),[]);const f=()=>{if(c)return d([t.data||[]]),void m(["none","none"]);a.current&&(a.current.getRenderMatrix&&d(a.current.getRenderMatrix()),a.current.getTransforms&&m(a.current.getTransforms()))},y=()=>{o.current&&window.ResizeObserver&&(l.current=new ResizeObserver(()=>{a.current&&a.current.updateData(),f()}),l.current.observe(o.current))},g=()=>{l.current&&l.current.disconnect(),l.current=null};r(()=>{if(!c){if(o.current){const e=x.includes(t.direction)?t.direction:"left",s={...t,direction:e,dataDriven:!0};a.current=new E(o.current,s),!1===t.running&&a.current.stop(),setTimeout(()=>{f(),y()},0)}return()=>{var t;null===(t=a.current)||void 0===t||t.destroy(),g()}}},[]),r(()=>{c||a.current&&void 0!==t.running&&(t.running?a.current.start():a.current.stop())},[t.running]),r(()=>{if(c)return d([t.data||[]]),void m(["none","none"]);a.current&&a.current.updateData(),setTimeout(()=>{f(),g(),y()},0)},[t.data]);const v={position:"absolute",top:0,left:0,display:"left"===t.direction||"right"===t.direction?"inline-block":"block",whiteSpace:"left"===t.direction||"right"===t.direction?"nowrap":"normal",verticalAlign:"left"===t.direction||"right"===t.direction?"middle":"baseline",boxSizing:"border-box",padding:"left"===t.direction||"right"===t.direction?"0 5px":"5px 0"},b={display:"inline-block",marginRight:"10px",verticalAlign:"middle"},S=t.rows||1,w=t.cols||1,C=t=>({position:"absolute",left:0,top:100/S*t+"%",width:"100%",height:100/S+"%",overflow:"hidden",display:"flex",alignItems:"center"});return p.jsx("div",{ref:o,className:t.className,style:{width:"100%",height:"100%",overflow:"hidden",position:"relative",...t.style},children:"left"===t.direction||"right"===t.direction?h.map((e,s)=>p.jsxs("div",{className:"scroll-seamless-row",style:C(s),children:[p.jsx("div",{className:`ss-content ss-content-1 ${t.contentClassName||""}`,style:{...v,transform:u[2*s]},children:e.map((e,n)=>t.children?t.children(e,n,s,void 0):p.jsx("span",{className:t.itemClassName,style:b,children:e},n))}),p.jsx("div",{className:`ss-content ss-content-2 ${t.contentClassName||""}`,style:{...v,transform:u[2*s+1]},children:e.map((e,n)=>t.children?t.children(e,n,s,void 0):p.jsx("span",{className:t.itemClassName,style:b,children:e},`dup-${n}`))})]},s)):h.map((e,s)=>p.jsxs("div",{className:"scroll-seamless-col",style:{position:"relative",width:100/w+"%",height:"100%",display:"inline-block",overflow:"hidden",textAlign:"center"},children:[p.jsx("div",{className:`ss-content ss-content-1 ${t.contentClassName||""}`,style:{...v,transform:u[2*s]},children:e.map((e,n)=>t.children?t.children(e,n,void 0,s):p.jsx("span",{className:t.itemClassName,style:b,children:e},n))}),p.jsx("div",{className:`ss-content ss-content-2 ${t.contentClassName||""}`,style:{...v,transform:u[2*s+1]},children:e.map((e,n)=>t.children?t.children(e,n,void 0,s):p.jsx("span",{className:t.itemClassName,style:b,children:e},`dup-${n}`))})]},s))})};C.defaultProps={direction:"left"};const k=e(C);export{k as default};
//# sourceMappingURL=index.esm.js.map