marquee-content 4.6.1 → 5.0.0-dev.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2024 ux-ui.pro
3
+ Copyright (c) 2026 ux-ui.pro
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
18
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
19
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
20
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,66 +1,158 @@
1
- <div align="center">
2
- <br>
1
+ # marquee-content
3
2
 
4
- <h1>marquee-content</h1>
3
+ A lightweight marquee Web Component for continuous scrolling content with Shadow DOM style overrides.
5
4
 
6
- <p><sup>MarqueeContent provides a set of tools for creating dynamic and adaptive ticker animations on web pages using GSAP and ScrollTrigger. It offers seamless integration with media queries, automatic element cloning for continuous scrolling effects, and efficient handling of resize events. Additionally, it supports customizable animation directions and skew effects, ensuring smooth and visually appealing ticker animations across different screen sizes.</sup></p>
5
+ - Works with plain HTML via custom element registration.
6
+ - Supports `rtl`, `ltr`, and `scroll` direction modes.
7
+ - Supports `pause-on-hover`, viewport pause, reduced motion, and responsive speed.
8
+ - Supports CSS overrides via `styleOverrides`.
9
+ - 6kB gzipped.
10
+ - [Demo](https://codepen.io/ux-ui/pen/dygzqYm).
7
11
 
8
12
  [![npm](https://img.shields.io/npm/v/marquee-content.svg?colorB=brightgreen)](https://www.npmjs.com/package/marquee-content)
9
13
  [![GitHub package version](https://img.shields.io/github/package-json/v/ux-ui-pro/marquee-content.svg)](https://github.com/ux-ui-pro/marquee-content)
10
14
  [![NPM Downloads](https://img.shields.io/npm/dm/marquee-content.svg?style=flat)](https://www.npmjs.org/package/marquee-content)
11
15
 
12
- <sup>1.5kB gzipped</sup>
16
+ ## Install
13
17
 
14
- <a href="https://codepen.io/ux-ui/full/dygzqYm">Demo</a>
18
+ ```bash
19
+ npm i marquee-content
20
+ ```
21
+
22
+ ## Usage
23
+
24
+ ```ts
25
+ import { initMarqueeContents } from 'marquee-content';
26
+
27
+ initMarqueeContents();
28
+ ```
15
29
 
16
- </div>
17
- <br>
30
+ ```html
31
+ <marquee-content direction="scroll" speed="120" min-group-width-ratio="1.1">
32
+ <span>News</span>
33
+ <span>Promotions</span>
34
+ <span>24/7 Delivery</span>
35
+ <span>Discounts up to 40%</span>
36
+ </marquee-content>
37
+ ```
18
38
 
19
- &#10148; **Install**
20
- ```console
21
- yarn add gsap
22
- yarn add marquee-content
39
+ ### Vue 3 + Vite
40
+
41
+ Vue must treat `marquee-content` as a Custom Element. Add `isCustomElement` to Vue plugin config:
42
+
43
+ ```ts
44
+ // vite.config.ts
45
+ import { defineConfig } from 'vite';
46
+ import vue from '@vitejs/plugin-vue';
47
+
48
+ export default defineConfig({
49
+ plugins: [
50
+ vue({
51
+ template: {
52
+ compilerOptions: {
53
+ isCustomElement: (tag) => tag === 'marquee-content',
54
+ },
55
+ },
56
+ }),
57
+ ],
58
+ });
23
59
  ```
24
- <br>
25
60
 
26
- &#10148; **Import**
27
- ```javascript
28
- import gsap from 'gsap';
29
- import ScrollTrigger from 'gsap/ScrollTrigger';
30
- import MarqueeContent from 'marquee-content';
61
+ Then initialize the component once on app startup:
62
+
63
+ ```ts
64
+ import { initMarqueeContents } from 'marquee-content';
31
65
 
32
- gsap.registerPlugin(ScrollTrigger);
66
+ initMarqueeContents();
33
67
  ```
34
- <br>
35
68
 
36
- &#10148; **Usage**
37
- ```javascript
38
- const marquee = new MarqueeContent({
39
- element: '.marquee',
69
+ If this config is missing, Vue can compile `<marquee-content>` as a Vue component and the Web Component may receive no source nodes (empty/0x0 track).
70
+
71
+ ### Style overrides
72
+
73
+ ```ts
74
+ import MarqueeOverrides from './marquee-content.overrides.css?raw';
75
+ import { initMarqueeContents } from 'marquee-content';
76
+
77
+ initMarqueeContents({
78
+ styleOverrides: MarqueeOverrides,
40
79
  });
80
+ ```
81
+
82
+ ```css
83
+ /* marquee-content.overrides.css */
84
+ :host {
85
+ --marquee-content-gap: 2rem;
86
+ }
87
+
88
+ :host([pause-on-hover]:not([pause-on-hover="false"])) {
89
+ cursor: default;
90
+ }
91
+
92
+ .marquee-content__group > * {
93
+ white-space: nowrap;
94
+ }
41
95
 
42
- marquee.init();
96
+ .marquee-content__track {
97
+ will-change: transform;
98
+ }
43
99
  ```
44
- <br>
45
100
 
46
- &#10148; **Options**
101
+ ## Options
102
+
103
+ | Attribute | Type | Default | Description |
104
+ |:--|:--|:--|:--|
105
+ | `speed` | `number` | `90` | Base speed in px/sec. |
106
+ | `direction` | `'rtl' \| 'ltr' \| 'scroll'` | `'rtl'` | Marquee direction mode. |
107
+ | `min-group-width-ratio` | `number` | `1.05` | Minimum content group width relative to container. |
108
+ | `responsive-speed` | `boolean` | `true` | Enables speed scaling by container width. |
109
+ | `reference-width` | `number` | `1280` | Reference width used for responsive speed factor. |
110
+ | `min-speed-factor` | `number` | `0.55` | Lower bound for responsive speed multiplier. |
111
+ | `max-speed-factor` | `number` | `1` | Upper bound for responsive speed multiplier. |
112
+ | `pause-on-hover` | `boolean` | `false` | Pauses animation while hovered. |
113
+ | `pause-when-out-of-view` | `boolean` | `true` | Pauses animation when not visible in viewport. |
114
+ | `recalculate-after-fonts-ready` | `boolean` | `true` | Rebuilds marquee when document fonts are ready. |
115
+ | `scroll-velocity-factor` | `number` | `400` | Normalizes scroll velocity for `direction="scroll"`. |
116
+ | `scroll-min-extra-speed` | `number` | `0.15` | Minimum scroll boost threshold. |
117
+ | `scroll-max-extra-speed` | `number` | `3` | Maximum absolute scroll boost. |
118
+ | `scroll-inertia-duration` | `number` | `1600` | Inertia duration (ms) for scroll boost fade-out. |
119
+ | `debug` | `boolean` | `false` | Enables debug logs in console. |
120
+
121
+ ### Programmatic update
122
+
123
+ ```ts
124
+ import type { MarqueeContent } from 'marquee-content';
125
+
126
+ const marquee = document.querySelector<MarqueeContent>('marquee-content');
127
+
128
+ if (marquee) {
129
+ marquee.update({
130
+ direction: 'scroll',
131
+ speed: 120,
132
+ pauseOnHover: true,
133
+ });
134
+
135
+ marquee.refresh();
136
+ }
137
+ ```
138
+
139
+ ## Methods
47
140
 
48
- | Option | Type | Default | Description |
49
- |:----------|:-----------------------:|:-----------:|:--------------------------------------------------------------------------------------------|
50
- | `element` | `string \| HTMLElement` | `.marquee` | The DOM element for the animation. Can be a CSS selector (string) or an HTMLElement object. |
51
- <br>
141
+ ```ts
142
+ import type { MarqueeContent } from 'marquee-content';
52
143
 
53
- &#10148; **Settings**
144
+ const marquee = document.querySelector<MarqueeContent>('marquee-content');
54
145
 
55
- | data-* | Default | Description |
56
- |:--------------------|:-------:|:----------------------------------------------------------------------------------------------------------------------|
57
- | `data-mc-speed` | `20` | Sets the speed of the marquee animation. Lower values make the animation faster, while higher values make it slower. |
58
- | `data-mc-direction` | `rtl` | Scroll direction. Options: `rtl` (default), `ltr` (left to right), `auto` (changes direction based on scrolling). |
59
- | `data-mc-skew` | `null` | Tilts the component along the Y axis. Accepts positive or negative values. |
60
- | `data-mc-min` | `null` | Minimum width for the animation to play. |
61
- | `data-mc-max` | `null` | Maximum width for the animation to play. |
62
- <br>
146
+ marquee?.update({
147
+ speed: 110,
148
+ direction: 'rtl',
149
+ });
150
+
151
+ marquee?.refresh();
152
+ marquee?.adoptStyleOverrides(':host { --marquee-content-gap: 1.25rem; }');
153
+ marquee?.adoptStyles(':host { color: #fff; }');
154
+ ```
63
155
 
64
- &#10148; **License**
156
+ ## License
65
157
 
66
- marquee-content is released under MIT license.
158
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,71 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=`:host {
2
+ --marquee-content-gap: 2rem;
3
+ --marquee-content-distance: 0px;
4
+ --marquee-content-duration: 20s;
5
+
6
+ display: block;
7
+ overflow: hidden;
8
+ width: 100%;
9
+ color: inherit;
10
+ font: inherit;
11
+
12
+ /*
13
+ По умолчанию компонент не ловит pointer events.
14
+ Это удобно для декоративной бегущей строки.
15
+ Если включить pause-on-hover, pointer-events включатся автоматически.
16
+ */
17
+ pointer-events: none;
18
+ }
19
+
20
+ :host([pause-on-hover]:not([pause-on-hover="false"])) {
21
+ pointer-events: auto;
22
+ }
23
+
24
+ :host([hidden]) {
25
+ display: none;
26
+ }
27
+
28
+ .marquee-content__source {
29
+ display: none;
30
+ }
31
+
32
+ .marquee-content__viewport {
33
+ overflow: hidden;
34
+ width: 100%;
35
+ }
36
+
37
+ .marquee-content__track {
38
+ display: flex;
39
+ width: max-content;
40
+ transform: translate3d(0, 0, 0);
41
+ will-change: transform;
42
+ }
43
+
44
+ .marquee-content__group {
45
+ display: flex;
46
+ flex: 0 0 auto;
47
+ align-items: center;
48
+ gap: var(--marquee-content-gap);
49
+ padding-inline-end: var(--marquee-content-gap);
50
+ white-space: nowrap;
51
+ color: inherit;
52
+ font: inherit;
53
+ }
54
+
55
+ .marquee-content__group > * {
56
+ flex: 0 0 auto;
57
+ }
58
+
59
+ @media (prefers-reduced-motion: reduce) {
60
+ .marquee-content__track {
61
+ transform: none !important;
62
+ }
63
+ }
64
+ `;function t(e){if(typeof CSSStyleSheet>`u`||typeof CSSStyleSheet.prototype.replaceSync!=`function`)return null;try{let t=new CSSStyleSheet;return t.replaceSync(e),t}catch{return null}}function n(e){try{return Array.from(e.cssRules).map(e=>e.cssText).join(`
65
+ `)}catch{return``}}function r(e){return e?typeof e==`string`?{sheet:t(e),cssText:e}:{sheet:e,cssText:n(e)}:{sheet:null,cssText:``}}function i(e){return typeof CSSStyleSheet<`u`&&`adoptedStyleSheets`in e&&typeof CSSStyleSheet.prototype.replaceSync==`function`}var a=`marquee-content`,o={speed:90,direction:`rtl`,minGroupWidthRatio:1.05,responsiveSpeed:!0,referenceWidth:1280,minSpeedFactor:.55,maxSpeedFactor:1,pauseOnHover:!1,pauseWhenOutOfView:!0,recalculateAfterFontsReady:!0,scrollVelocityFactor:400,scrollMinExtraSpeed:.15,scrollMaxExtraSpeed:3,scrollInertiaDuration:1600,debug:!1},s=[`speed`,`direction`,`min-group-width-ratio`,`responsive-speed`,`reference-width`,`min-speed-factor`,`max-speed-factor`,`pause-on-hover`,`pause-when-out-of-view`,`recalculate-after-fonts-ready`,`scroll-velocity-factor`,`scroll-min-extra-speed`,`scroll-max-extra-speed`,`scroll-inertia-duration`,`debug`],c={speed:`speed`,direction:`direction`,minGroupWidthRatio:`min-group-width-ratio`,responsiveSpeed:`responsive-speed`,referenceWidth:`reference-width`,minSpeedFactor:`min-speed-factor`,maxSpeedFactor:`max-speed-factor`,pauseOnHover:`pause-on-hover`,pauseWhenOutOfView:`pause-when-out-of-view`,recalculateAfterFontsReady:`recalculate-after-fonts-ready`,scrollVelocityFactor:`scroll-velocity-factor`,scrollMinExtraSpeed:`scroll-min-extra-speed`,scrollMaxExtraSpeed:`scroll-max-extra-speed`,scrollInertiaDuration:`scroll-inertia-duration`,debug:`debug`},l=[`--marquee-content-distance`,`--marquee-content-duration`],u=`
66
+ <slot class="marquee-content__source"></slot>
67
+
68
+ <div class="marquee-content__viewport" part="viewport">
69
+ <div class="marquee-content__track" part="track"></div>
70
+ </div>
71
+ `,d=class t extends HTMLElement{static get observedAttributes(){return[...s]}static instances=new Set;static stylesheetEntry=r(e);static styleOverridesEntry=r(null);static configureStyles(n={}){`stylesheet`in n&&(t.stylesheetEntry=r(n.stylesheet??e)),`styleOverrides`in n&&(t.styleOverridesEntry=r(n.styleOverrides)),t.instances.forEach(e=>{e.applyAllStyles()})}static setStylesheet(e){t.configureStyles({stylesheet:e})}static setStyleOverrides(e){t.configureStyles({styleOverrides:e})}shadow;sourceSlot;track;options={...o};sourceNodes=[];resizeObserver=null;mutationObserver=null;intersectionObserver=null;abortController=null;reducedMotionMediaQuery=null;animationFrameId=null;rebuildFrameId=null;lastFrameTime=null;mounted=!1;isHovered=!1;isInViewport=!0;reducedMotion=!1;distance=0;offset=0;emptySourceRebuildCount=0;hasWarnedMissingSourceNodes=!1;scrollDirectionFactor=1;scrollBoostStartValue=0;scrollBoostStartedAt=0;lastScrollY=0;lastScrollTime=0;constructor(){super(),this.shadow=this.attachShadow({mode:`open`}),this.applyAllStyles();let e=document.createElement(`template`);e.innerHTML=u,this.shadow.appendChild(e.content.cloneNode(!0));let t=this.shadow.querySelector(`slot.marquee-content__source`),n=this.shadow.querySelector(`.marquee-content__track`);if(!t)throw Error(`[MarqueeContent] Source slot was not found.`);if(!n)throw Error(`[MarqueeContent] Track element was not found.`);this.sourceSlot=t,this.track=n}connectedCallback(){this.mounted||(t.instances.add(this),this.mounted=!0,this.abortController=new AbortController,this.options=this.resolveOptions(),this.lastScrollY=this.getScrollY(),this.lastScrollTime=performance.now(),this.sourceSlot.addEventListener(`slotchange`,this.handleSlotChange,{signal:this.abortController.signal}),this.shadow.addEventListener(`load`,this.scheduleRebuild,{capture:!0,signal:this.abortController.signal}),this.addEventListener(`pointerenter`,this.handlePointerEnter,{signal:this.abortController.signal}),this.addEventListener(`pointerleave`,this.handlePointerLeave,{signal:this.abortController.signal}),window.addEventListener(`scroll`,this.handleScroll,{passive:!0,signal:this.abortController.signal}),window.addEventListener(`orientationchange`,this.scheduleRebuild,{signal:this.abortController.signal}),typeof ResizeObserver<`u`?(this.resizeObserver=new ResizeObserver(this.scheduleRebuild),this.resizeObserver.observe(this)):window.addEventListener(`resize`,this.scheduleRebuild,{signal:this.abortController.signal}),`IntersectionObserver`in window&&(this.intersectionObserver=new IntersectionObserver(this.handleIntersectionChange),this.intersectionObserver.observe(this)),this.setupReducedMotionWatcher(),this.watchSourceNodes(),this.rebuild(),this.options.recalculateAfterFontsReady&&this.rebuildAfterFontsReady())}disconnectedCallback(){this.teardown(),t.instances.delete(this)}attributeChangedCallback(e,t,n){t!==n&&(this.options=this.resolveOptions(),this.mounted&&this.scheduleRebuild())}get speed(){return this.options.speed}set speed(e){this.setNullableAttribute(`speed`,e)}get direction(){return this.options.direction}set direction(e){this.setNullableAttribute(`direction`,e)}get minGroupWidthRatio(){return this.options.minGroupWidthRatio}set minGroupWidthRatio(e){this.setNullableAttribute(`min-group-width-ratio`,e)}get responsiveSpeed(){return this.options.responsiveSpeed}set responsiveSpeed(e){this.setNullableAttribute(`responsive-speed`,e)}get referenceWidth(){return this.options.referenceWidth}set referenceWidth(e){this.setNullableAttribute(`reference-width`,e)}get minSpeedFactor(){return this.options.minSpeedFactor}set minSpeedFactor(e){this.setNullableAttribute(`min-speed-factor`,e)}get maxSpeedFactor(){return this.options.maxSpeedFactor}set maxSpeedFactor(e){this.setNullableAttribute(`max-speed-factor`,e)}get pauseOnHover(){return this.options.pauseOnHover}set pauseOnHover(e){this.setNullableAttribute(`pause-on-hover`,e)}get pauseWhenOutOfView(){return this.options.pauseWhenOutOfView}set pauseWhenOutOfView(e){this.setNullableAttribute(`pause-when-out-of-view`,e)}get recalculateAfterFontsReady(){return this.options.recalculateAfterFontsReady}set recalculateAfterFontsReady(e){this.setNullableAttribute(`recalculate-after-fonts-ready`,e)}get scrollVelocityFactor(){return this.options.scrollVelocityFactor}set scrollVelocityFactor(e){this.setNullableAttribute(`scroll-velocity-factor`,e)}get scrollMinExtraSpeed(){return this.options.scrollMinExtraSpeed}set scrollMinExtraSpeed(e){this.setNullableAttribute(`scroll-min-extra-speed`,e)}get scrollMaxExtraSpeed(){return this.options.scrollMaxExtraSpeed}set scrollMaxExtraSpeed(e){this.setNullableAttribute(`scroll-max-extra-speed`,e)}get scrollInertiaDuration(){return this.options.scrollInertiaDuration}set scrollInertiaDuration(e){this.setNullableAttribute(`scroll-inertia-duration`,e)}get debug(){return this.options.debug}set debug(e){this.setNullableAttribute(`debug`,e)}update(e={}){Object.entries(e).forEach(([e,t])=>{let n=c[e];n&&this.setNullableAttribute(n,t)}),this.options=this.resolveOptions(),this.scheduleRebuild()}refresh(){this.scheduleRebuild()}adoptStyles(e){t.setStylesheet(e)}adoptStyleOverrides(e){t.setStyleOverrides(e)}applyAllStyles(){let e=t.stylesheetEntry,n=t.styleOverridesEntry;if(i(this.shadow)){let t=[];e.sheet&&t.push(e.sheet),n.sheet&&t.push(n.sheet),this.shadow.adoptedStyleSheets=t,this.removeFallbackStyleElements();return}this.applyFallbackStyleElement(`base`,e.cssText),this.applyFallbackStyleElement(`overrides`,n.cssText)}applyFallbackStyleElement(e,t){let n=`data-marquee-content-style-${e}`,r=this.shadow.querySelector(`style[${n}]`);if(!t){r?.remove();return}r||(r=document.createElement(`style`),r.setAttribute(n,``),this.shadow.prepend(r)),r.textContent!==t&&(r.textContent=t)}removeFallbackStyleElements(){this.shadow.querySelectorAll(`style[data-marquee-content-style-base], style[data-marquee-content-style-overrides]`).forEach(e=>{e.remove()})}teardown(){this.mounted&&(this.mounted=!1,this.stopAnimationLoop(),this.cancelScheduledRebuild(),this.resizeObserver?.disconnect(),this.mutationObserver?.disconnect(),this.intersectionObserver?.disconnect(),this.removeReducedMotionWatcher(),this.abortController?.abort(),this.resizeObserver=null,this.mutationObserver=null,this.intersectionObserver=null,this.abortController=null,this.track.replaceChildren(),this.removeAttribute(`data-marquee-content-ready`),this.removeAttribute(`data-marquee-content-pause-on-hover`),l.forEach(e=>{this.style.removeProperty(e)}),this.distance=0,this.offset=0,this.lastFrameTime=null)}handleSlotChange=()=>{this.watchSourceNodes(),this.scheduleRebuild()};handlePointerEnter=()=>{this.isHovered=!0,this.updateAnimationLoopState()};handlePointerLeave=()=>{this.isHovered=!1,this.updateAnimationLoopState()};handleIntersectionChange=e=>{let t=e[0];t&&(this.isInViewport=t.isIntersecting,this.updateAnimationLoopState())};handleReducedMotionChange=e=>{this.reducedMotion=e.matches,this.reducedMotion?this.track.style.transform=`none`:this.applyTransform(),this.updateAnimationLoopState()};handleScroll=()=>{if(this.options.direction!==`scroll`)return;let e=performance.now(),t=this.getScrollY(),n=t-this.lastScrollY,r=Math.max((e-this.lastScrollTime)/1e3,.016);if(this.lastScrollY=t,this.lastScrollTime=e,Math.abs(n)<.5)return;let i=n/r;this.scrollDirectionFactor=i>=0?1:-1;let a=this.clamp(i/this.options.scrollVelocityFactor,-this.options.scrollMaxExtraSpeed,this.options.scrollMaxExtraSpeed);Math.abs(a)>=this.options.scrollMinExtraSpeed?(this.scrollBoostStartValue=a,this.scrollBoostStartedAt=e):this.scrollBoostStartValue=0,this.updateAnimationLoopState(),this.options.debug&&console.info(`[MarqueeContent] Scroll update`,{velocity:i,directionFactor:this.scrollDirectionFactor,extraSpeed:a})};scheduleRebuild=()=>{this.mounted&&(this.cancelScheduledRebuild(),this.rebuildFrameId=requestAnimationFrame(()=>{this.rebuildFrameId=null,this.rebuild()}))};cancelScheduledRebuild(){this.rebuildFrameId!==null&&(cancelAnimationFrame(this.rebuildFrameId),this.rebuildFrameId=null)}rebuild(){if(!this.mounted)return;this.options=this.resolveOptions(),this.removeAttribute(`data-marquee-content-ready`),this.options.pauseOnHover?this.setAttribute(`data-marquee-content-pause-on-hover`,`true`):this.removeAttribute(`data-marquee-content-pause-on-hover`);let e=this.clientWidth;if(e<=0){this.distance=0,this.track.replaceChildren(),this.updateAnimationLoopState();return}if(this.sourceNodes=this.getSourceNodes(),this.sourceNodes.length===0){this.emptySourceRebuildCount+=1,this.warnAboutMissingSourceNodes(),this.distance=0,this.track.replaceChildren(),this.updateAnimationLoopState();return}this.emptySourceRebuildCount=0,this.hasWarnedMissingSourceNodes=!1;let t=this.createGroup(),n=e*this.options.minGroupWidthRatio;this.track.replaceChildren(t),this.expandGroupToWidth(t,n);let r=t.cloneNode(!0);if(r.setAttribute(`aria-hidden`,`true`),this.track.appendChild(r),this.distance=t.scrollWidth,this.offset=this.normalizeOffset(this.offset),this.distance<=0){this.track.replaceChildren(),this.updateAnimationLoopState();return}let i=this.getCurrentSpeed(e),a=this.distance/i;this.style.setProperty(`--marquee-content-distance`,`${this.distance}px`),this.style.setProperty(`--marquee-content-duration`,`${a}s`),this.reducedMotion?this.track.style.transform=`none`:this.applyTransform(),this.setAttribute(`data-marquee-content-ready`,`true`),this.updateAnimationLoopState(),this.options.debug&&console.info(`[MarqueeContent] Rebuilt`,{containerWidth:e,distance:this.distance,baseSpeed:this.options.speed,currentSpeed:i,duration:a,direction:this.options.direction,responsiveSpeed:this.options.responsiveSpeed})}warnAboutMissingSourceNodes(){this.hasWarnedMissingSourceNodes||this.emptySourceRebuildCount<2||(this.hasWarnedMissingSourceNodes=!0,console.warn([`[MarqueeContent] No source nodes were detected for <marquee-content>.`,`If you use Vue + Vite, configure compilerOptions.isCustomElement for "marquee-content",`,`otherwise Vue may treat it as a Vue component and slot content will not be exposed to the Web Component.`].join(` `)))}createGroup(){let e=document.createElement(`div`);return e.className=`marquee-content__group`,e.setAttribute(`part`,`group`),this.appendSourceNodes(e),e}expandGroupToWidth(e,t){let n=0;for(;e.scrollWidth<t&&n<100;){let t=e.scrollWidth;if(this.appendSourceNodes(e),e.scrollWidth<=t)break;n+=1}}appendSourceNodes(e){let t=document.createDocumentFragment();this.sourceNodes.forEach(e=>{t.append(this.cloneSourceNode(e))}),e.appendChild(t)}cloneSourceNode(e){let t=e.cloneNode(!0);if(t instanceof Element){let e=t.getAttribute(`part`);t.setAttribute(`part`,e?`${e} item`:`item`)}return t}getSourceNodes(){return this.sourceSlot.assignedNodes({flatten:!0}).filter(e=>e.nodeType===Node.TEXT_NODE?!!e.textContent?.trim():e.nodeType===Node.ELEMENT_NODE)}watchSourceNodes(){this.mutationObserver?.disconnect(),`MutationObserver`in window&&(this.mutationObserver=new MutationObserver(this.scheduleRebuild),this.getSourceNodes().forEach(e=>{if(e.nodeType===Node.ELEMENT_NODE){this.mutationObserver?.observe(e,{attributes:!0,childList:!0,characterData:!0,subtree:!0});return}e.nodeType===Node.TEXT_NODE&&this.mutationObserver?.observe(e,{characterData:!0})}))}setupReducedMotionWatcher(){if(!(`matchMedia`in window))return;if(this.reducedMotionMediaQuery=window.matchMedia(`(prefers-reduced-motion: reduce)`),this.reducedMotion=this.reducedMotionMediaQuery.matches,typeof this.reducedMotionMediaQuery.addEventListener==`function`){this.reducedMotionMediaQuery.addEventListener(`change`,this.handleReducedMotionChange,{signal:this.abortController?.signal});return}let e=this.reducedMotionMediaQuery;typeof e.addListener==`function`&&e.addListener(this.handleReducedMotionChange)}removeReducedMotionWatcher(){if(this.reducedMotionMediaQuery){if(typeof this.reducedMotionMediaQuery.removeEventListener==`function`)this.reducedMotionMediaQuery.removeEventListener(`change`,this.handleReducedMotionChange);else{let e=this.reducedMotionMediaQuery;typeof e.removeListener==`function`&&e.removeListener(this.handleReducedMotionChange)}this.reducedMotionMediaQuery=null}}updateAnimationLoopState(){if(!this.mounted||this.distance<=0||this.reducedMotion||!this.canAnimate()){this.stopAnimationLoop();return}this.startAnimationLoop()}canAnimate(){return!(this.options.pauseOnHover&&this.isHovered||this.options.pauseWhenOutOfView&&!this.isInViewport)}startAnimationLoop(){this.animationFrameId===null&&(this.lastFrameTime=performance.now(),this.animationFrameId=requestAnimationFrame(this.tick))}stopAnimationLoop(){if(this.animationFrameId===null){this.lastFrameTime=null;return}cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null,this.lastFrameTime=null}tick=e=>{if(this.animationFrameId=null,!this.mounted||this.distance<=0||this.reducedMotion||!this.canAnimate()){this.stopAnimationLoop();return}let t=this.lastFrameTime??e,n=Math.min((e-t)/1e3,.064);this.lastFrameTime=e;let r=this.getCurrentSpeed(this.clientWidth),i=this.getCurrentTimeScale(e);this.offset=this.normalizeOffset(this.offset+r*i*n),this.applyTransform(),this.animationFrameId=requestAnimationFrame(this.tick)};getCurrentTimeScale(e){if(this.options.direction===`rtl`)return 1;if(this.options.direction===`ltr`)return-1;let t=this.getScrollBoost(e);return this.clamp(this.scrollDirectionFactor+t,-1-this.options.scrollMaxExtraSpeed,1+this.options.scrollMaxExtraSpeed)}getScrollBoost(e){if(this.scrollBoostStartValue===0)return 0;let t=this.options.scrollInertiaDuration;if(t<=0)return this.scrollBoostStartValue=0,0;let n=this.clamp((e-this.scrollBoostStartedAt)/t,0,1);if(n>=1)return this.scrollBoostStartValue=0,0;let r=this.easeOutCubic(n);return this.scrollBoostStartValue*(1-r)}applyTransform(){this.track.style.transform=`translate3d(${-this.offset}px, 0, 0)`}normalizeOffset(e){if(this.distance<=0)return 0;let t=e%this.distance;return t<0?t+this.distance:t}getCurrentSpeed(e){if(!this.options.responsiveSpeed)return this.options.speed;let t=this.clamp(e/this.options.referenceWidth,this.options.minSpeedFactor,this.options.maxSpeedFactor);return this.options.speed*t}resolveOptions(){let e=this.num(`min-speed-factor`,o.minSpeedFactor,.1,2),t=this.num(`max-speed-factor`,o.maxSpeedFactor,.1,3);return{speed:this.num(`speed`,o.speed,10,500),direction:this.parseDirection(this.getAttribute(`direction`),o.direction),minGroupWidthRatio:this.num(`min-group-width-ratio`,o.minGroupWidthRatio,1,5),responsiveSpeed:this.parseBoolean(this.getAttribute(`responsive-speed`),o.responsiveSpeed),referenceWidth:this.num(`reference-width`,o.referenceWidth,320,1e4),minSpeedFactor:Math.min(e,t),maxSpeedFactor:Math.max(e,t),pauseOnHover:this.parseBoolean(this.getAttribute(`pause-on-hover`),o.pauseOnHover),pauseWhenOutOfView:this.parseBoolean(this.getAttribute(`pause-when-out-of-view`),o.pauseWhenOutOfView),recalculateAfterFontsReady:this.parseBoolean(this.getAttribute(`recalculate-after-fonts-ready`),o.recalculateAfterFontsReady),scrollVelocityFactor:this.num(`scroll-velocity-factor`,o.scrollVelocityFactor,50,5e3),scrollMinExtraSpeed:this.num(`scroll-min-extra-speed`,o.scrollMinExtraSpeed,0,5),scrollMaxExtraSpeed:this.num(`scroll-max-extra-speed`,o.scrollMaxExtraSpeed,0,10),scrollInertiaDuration:this.num(`scroll-inertia-duration`,o.scrollInertiaDuration,0,5e3),debug:this.parseBoolean(this.getAttribute(`debug`),o.debug)}}num(e,t,n,r){return this.clamp(this.parseNumber(this.getAttribute(e),t),n,r)}parseNumber(e,t){if(e===null||e.trim()===``)return t;let n=Number(e);return Number.isFinite(n)?n:t}parseBoolean(e,t){if(e===null)return t;let n=e.trim().toLowerCase();return n===``||[`true`,`1`,`yes`,`on`].includes(n)?!0:[`false`,`0`,`no`,`off`].includes(n)?!1:t}parseDirection(e,t){return e===`rtl`||e===`ltr`||e===`scroll`?e:t}setNullableAttribute(e,t){if(t==null){this.removeAttribute(e);return}this.setAttribute(e,String(t))}getScrollY(){return window.scrollY||window.pageYOffset||0}clamp(e,t,n){return Math.min(Math.max(e,t),n)}easeOutCubic(e){return 1-(1-e)**3}rebuildAfterFontsReady(){let e=document.fonts;e?.ready&&e.ready.then(this.scheduleRebuild).catch(()=>void 0)}};function f(e=a,t={}){typeof window>`u`||!window.customElements||(d.configureStyles(t),window.customElements.get(e)||window.customElements.define(e,d))}function p(e={}){let{tagName:t=a,...n}=e;f(t,n)}f(),exports.MARQUEE_CONTENT_TAG=a,exports.MarqueeContent=d,exports.createConstructableStyleSheet=t,exports.cssStyleSheetToText=n,exports.defineMarqueeContent=f,exports.initMarqueeContents=p,exports.marqueeContentCssText=e,exports.normalizeStyleInput=r;
package/dist/index.d.ts CHANGED
@@ -1,28 +1,4 @@
1
- import { gsap } from 'gsap';
2
- import { ScrollTrigger } from 'gsap/ScrollTrigger';
3
- interface MarqueeOptions {
4
- element?: string | HTMLElement;
5
- }
6
- export default class MarqueeContent {
7
- private static _gsap;
8
- private static _ScrollTrigger;
9
- private gsapInstance;
10
- private timeline?;
11
- private matchMedia;
12
- private element;
13
- private resizeObserver;
14
- private animationFrame?;
15
- constructor({ element }?: MarqueeOptions);
16
- static registerGSAP(gsapInstance: typeof gsap, scrollTriggerInstance: typeof ScrollTrigger): void;
17
- private static debounce;
18
- init(): void;
19
- destroy(): void;
20
- private setup;
21
- private update;
22
- private createAnimation;
23
- private clearTimeline;
24
- private setBreakpoints;
25
- private cloneElements;
26
- private applySkew;
27
- }
28
- export {};
1
+ export type { DefineMarqueeContentOptions, InitMarqueeContentsOptions, MarqueeContentDirection, MarqueeContentOptions, MarqueeContentResolvedOptions, } from './marquee-content';
2
+ export { defineMarqueeContent, initMarqueeContents, MARQUEE_CONTENT_TAG, MarqueeContent, } from './marquee-content';
3
+ export type { MarqueeContentStyleEntry, MarqueeContentStyleInput, } from './styles';
4
+ export { createConstructableStyleSheet, cssStyleSheetToText, marqueeContentCssText, normalizeStyleInput, } from './styles';