kavan-smoother 0.0.0-stage → 0.1.0
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 +21 -0
- package/README.md +162 -2
- package/dist/index.d.ts +135 -0
- package/dist/index.js +1 -0
- package/dist/kavan-smoother.global.min.js +1 -0
- package/dist/react.d.ts +9 -0
- package/dist/react.js +1 -0
- package/package.json +62 -4
- package/src/index.ts +531 -0
- package/src/react.tsx +34 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kavan Gami
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,163 @@
|
|
|
1
|
-
#
|
|
1
|
+
# kavan-smoother
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Lightweight smooth scrolling for websites. **About 3 KB gzipped, no dependencies.**
|
|
4
|
+
|
|
5
|
+
The browser keeps its real scroll position. Only the mouse wheel and trackpad get eased, so `position: sticky`, IntersectionObserver, GSAP ScrollTrigger, keyboard scrolling and find-in-page all keep working. Touch scrolling stays native unless you opt in.
|
|
6
|
+
|
|
7
|
+
It follows the same model as [Lenis](https://github.com/darkroomengineering/lenis) and uses the same method names, so moving a project across is quick.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install kavan-smoother
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Use
|
|
16
|
+
|
|
17
|
+
### Any bundler (Vite, Next.js, Astro, Nuxt…)
|
|
18
|
+
|
|
19
|
+
```js
|
|
20
|
+
import { Smoother } from 'kavan-smoother'
|
|
21
|
+
|
|
22
|
+
const smoother = new Smoother({
|
|
23
|
+
lerp: 0.1, // lower = floatier
|
|
24
|
+
anchors: { offset: -96 }, // animate #hash links, minus a fixed header
|
|
25
|
+
})
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
### Plain HTML, WordPress, Shopify (CDN)
|
|
29
|
+
|
|
30
|
+
```html
|
|
31
|
+
<script src="https://cdn.jsdelivr.net/npm/kavan-smoother@0.1.0/dist/kavan-smoother.global.min.js"></script>
|
|
32
|
+
<script>
|
|
33
|
+
const smoother = new Smoother({ lerp: 0.1 })
|
|
34
|
+
</script>
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### With GSAP ScrollTrigger
|
|
38
|
+
|
|
39
|
+
Let GSAP's ticker drive the frames, so the scroll and your scroll animations update together:
|
|
40
|
+
|
|
41
|
+
```js
|
|
42
|
+
import { Smoother } from 'kavan-smoother'
|
|
43
|
+
import { gsap } from 'gsap'
|
|
44
|
+
import { ScrollTrigger } from 'gsap/ScrollTrigger'
|
|
45
|
+
|
|
46
|
+
const smoother = new Smoother({ autoRaf: false })
|
|
47
|
+
smoother.on('scroll', ScrollTrigger.update)
|
|
48
|
+
gsap.ticker.add((time) => smoother.raf(time * 1000))
|
|
49
|
+
gsap.ticker.lagSmoothing(0)
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### React / Next.js
|
|
53
|
+
|
|
54
|
+
```tsx
|
|
55
|
+
// app/providers/smooth-scroll.tsx
|
|
56
|
+
'use client'
|
|
57
|
+
import { useEffect, type ReactNode } from 'react'
|
|
58
|
+
import { SmootherProvider, useSmoother } from 'kavan-smoother/react'
|
|
59
|
+
import { gsap } from 'gsap'
|
|
60
|
+
import { ScrollTrigger } from 'gsap/ScrollTrigger'
|
|
61
|
+
|
|
62
|
+
export function SmoothScroll({ children }: { children: ReactNode }) {
|
|
63
|
+
return (
|
|
64
|
+
<SmootherProvider options={{ autoRaf: false, anchors: { offset: -96 } }}>
|
|
65
|
+
<GsapBridge />
|
|
66
|
+
{children}
|
|
67
|
+
</SmootherProvider>
|
|
68
|
+
)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function GsapBridge() {
|
|
72
|
+
const smoother = useSmoother(ScrollTrigger.update)
|
|
73
|
+
useEffect(() => {
|
|
74
|
+
if (!smoother) return
|
|
75
|
+
const tick = (t: number) => smoother.raf(t * 1000)
|
|
76
|
+
gsap.ticker.add(tick)
|
|
77
|
+
gsap.ticker.lagSmoothing(0)
|
|
78
|
+
ScrollTrigger.refresh()
|
|
79
|
+
return () => gsap.ticker.remove(tick)
|
|
80
|
+
}, [smoother])
|
|
81
|
+
return null
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Not using GSAP? Leave out `GsapBridge` and `autoRaf: false`; the smoother runs its own frame loop.
|
|
86
|
+
|
|
87
|
+
Anywhere inside the provider:
|
|
88
|
+
|
|
89
|
+
```tsx
|
|
90
|
+
const smoother = useSmoother()
|
|
91
|
+
smoother?.scrollTo('#contact', { offset: -80 })
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Options
|
|
95
|
+
|
|
96
|
+
| Option | Default | What it does |
|
|
97
|
+
| --- | --- | --- |
|
|
98
|
+
| `lerp` | `0.1` | Share of the remaining distance covered per 60 fps frame (0–1). Frame-rate independent. |
|
|
99
|
+
| `duration` | – | Seconds per wheel animation. Setting it switches from lerp to easing mode. |
|
|
100
|
+
| `easing` | expo-out | Easing function for duration mode. |
|
|
101
|
+
| `smoothWheel` | `true` | Ease the mouse wheel and trackpad. |
|
|
102
|
+
| `wheelMultiplier` | `1` | Wheel distance multiplier. |
|
|
103
|
+
| `syncTouch` | `false` | Ease touch too, with momentum. Off keeps native touch scrolling. |
|
|
104
|
+
| `syncTouchLerp` | `0.075` | Lerp used for the momentum glide after a touch ends. |
|
|
105
|
+
| `touchMultiplier` | `1` | Touch distance multiplier. |
|
|
106
|
+
| `touchInertiaExponent` | `1.7` | How strongly release speed turns into momentum. |
|
|
107
|
+
| `nestedScroll` | `true` | Scrollable children (menus, modals, code blocks) scroll themselves. |
|
|
108
|
+
| `anchors` | `false` | Animate same-page `#hash` links. Pass scrollTo options, e.g. `{ offset: -96 }`. |
|
|
109
|
+
| `autoRaf` | `true` | Run its own `requestAnimationFrame` loop. Set `false` when GSAP drives `raf()`. |
|
|
110
|
+
| `respectReducedMotion` | `true` | Jump instead of animating when the visitor asks for reduced motion. |
|
|
111
|
+
| `wrapper` | `window` | A scroll container element instead of the window. |
|
|
112
|
+
| `content` | `<html>` | The element whose height sets the scroll limit. |
|
|
113
|
+
|
|
114
|
+
## Methods
|
|
115
|
+
|
|
116
|
+
| Method | What it does |
|
|
117
|
+
| --- | --- |
|
|
118
|
+
| `scrollTo(target, options)` | `target`: a number, `'#id'`, a CSS selector, an element, `'top'` or `'bottom'`. Options: `offset`, `immediate`, `lock`, `force`, `lerp`, `duration`, `easing`, `onComplete`. |
|
|
119
|
+
| `stop()` / `start()` | Freeze the page (modal, mobile menu) and release it. |
|
|
120
|
+
| `on('scroll', fn)` | Runs every scroll frame. Returns an unsubscribe function. |
|
|
121
|
+
| `off('scroll', fn)` | Removes a listener. |
|
|
122
|
+
| `raf(timeMs)` | Advance one frame from your own loop. |
|
|
123
|
+
| `resize()` | Re-measure. Usually automatic (ResizeObserver). |
|
|
124
|
+
| `destroy()` | Remove all listeners and classes. |
|
|
125
|
+
|
|
126
|
+
Read-only: `scroll`, `targetScroll`, `animatedScroll`, `velocity`, `direction`, `progress`, `limit`, `isScrolling` (`false` / `'native'` / `'smooth'`), `isSmooth`, `isStopped`, `isLocked`.
|
|
127
|
+
|
|
128
|
+
## HTML attributes
|
|
129
|
+
|
|
130
|
+
| Attribute | Effect |
|
|
131
|
+
| --- | --- |
|
|
132
|
+
| `data-smoother-prevent` | Wheel and touch inside this element are left to the browser. |
|
|
133
|
+
| `data-smoother-prevent-wheel` | Only wheel input is left to the browser. |
|
|
134
|
+
| `data-smoother-prevent-touch` | Only touch input is left to the browser. |
|
|
135
|
+
|
|
136
|
+
## CSS classes on `<html>`
|
|
137
|
+
|
|
138
|
+
`smoother`, `smoother-scrolling`, `smoother-smooth`, `smoother-stopped`, `smoother-locked`. The required CSS (4 rules) is injected automatically; there is no stylesheet to import.
|
|
139
|
+
|
|
140
|
+
## Moving from Lenis
|
|
141
|
+
|
|
142
|
+
| Lenis | kavan-smoother |
|
|
143
|
+
| --- | --- |
|
|
144
|
+
| `import Lenis from 'lenis'` | `import { Smoother } from 'kavan-smoother'` |
|
|
145
|
+
| `import 'lenis/dist/lenis.css'` | remove it |
|
|
146
|
+
| `<ReactLenis root>` / `useLenis` | `<SmootherProvider>` / `useSmoother` |
|
|
147
|
+
| `data-lenis-prevent` | `data-smoother-prevent` |
|
|
148
|
+
| `.lenis-stopped` etc. | `.smoother-stopped` etc. |
|
|
149
|
+
|
|
150
|
+
`scrollTo`, `stop`, `start`, `raf` and the `scroll` event work the same. Not included: horizontal scrolling, infinite scrolling, the snap add-on, `autoToggle`.
|
|
151
|
+
|
|
152
|
+
## Development
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
npm install
|
|
156
|
+
npx playwright install chromium # once, for the tests
|
|
157
|
+
npm run build # dist/ + size report
|
|
158
|
+
npm test # 25 behaviour checks in Chromium
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## License
|
|
162
|
+
|
|
163
|
+
MIT. Inspired by Lenis by darkroom.engineering (MIT).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* kavan-smoother: a lightweight, dependency-free smooth scroller.
|
|
3
|
+
*
|
|
4
|
+
* Same model as Lenis 1.3: the page keeps its native scroll, wheel input is
|
|
5
|
+
* intercepted, a virtual position is animated toward a target every frame and
|
|
6
|
+
* written back with scrollTo(). Because the real scroll position changes,
|
|
7
|
+
* position: sticky, IntersectionObserver and GSAP ScrollTrigger keep working.
|
|
8
|
+
*
|
|
9
|
+
* Vertical only. Members prefixed with "_" are internal (mangled when minified).
|
|
10
|
+
*/
|
|
11
|
+
export type Easing = (t: number) => number;
|
|
12
|
+
export type ScrollState = false | 'native' | 'smooth';
|
|
13
|
+
export interface SmootherOptions {
|
|
14
|
+
/** Scroll container. Default: window */
|
|
15
|
+
wrapper?: Window | HTMLElement;
|
|
16
|
+
/** Element whose height sets the scroll limit. Default: <html> */
|
|
17
|
+
content?: HTMLElement;
|
|
18
|
+
/** Catch-up per 60 fps frame, 0–1. Lower = floatier. Default 0.1 */
|
|
19
|
+
lerp?: number;
|
|
20
|
+
/** Seconds per wheel animation. Setting it switches from lerp to easing mode */
|
|
21
|
+
duration?: number;
|
|
22
|
+
/** Easing for duration mode. Default: expo-out */
|
|
23
|
+
easing?: Easing;
|
|
24
|
+
/** Smooth the mouse wheel / trackpad. Default true */
|
|
25
|
+
smoothWheel?: boolean;
|
|
26
|
+
wheelMultiplier?: number;
|
|
27
|
+
/** Smooth touch too (fingers drive the animation, with inertia). Default false = native touch */
|
|
28
|
+
syncTouch?: boolean;
|
|
29
|
+
syncTouchLerp?: number;
|
|
30
|
+
touchMultiplier?: number;
|
|
31
|
+
touchInertiaExponent?: number;
|
|
32
|
+
/** Let scrollable children (menus, modals, code blocks) scroll themselves. Default true */
|
|
33
|
+
nestedScroll?: boolean;
|
|
34
|
+
/** Animate same-page #hash links. Pass an object for scrollTo options */
|
|
35
|
+
anchors?: boolean | SmootherScrollToOptions;
|
|
36
|
+
/** Run its own requestAnimationFrame loop. Set false when gsap.ticker drives raf(). Default true */
|
|
37
|
+
autoRaf?: boolean;
|
|
38
|
+
/** Jump instead of animating when the OS asks for reduced motion. Default true */
|
|
39
|
+
respectReducedMotion?: boolean;
|
|
40
|
+
}
|
|
41
|
+
export interface SmootherScrollToOptions {
|
|
42
|
+
offset?: number;
|
|
43
|
+
/** Jump with no animation */
|
|
44
|
+
immediate?: boolean;
|
|
45
|
+
/** Ignore user input until the animation finishes */
|
|
46
|
+
lock?: boolean;
|
|
47
|
+
/** Scroll even while stopped */
|
|
48
|
+
force?: boolean;
|
|
49
|
+
lerp?: number;
|
|
50
|
+
duration?: number;
|
|
51
|
+
easing?: Easing;
|
|
52
|
+
onComplete?: (d: Smoother) => void;
|
|
53
|
+
/** Internal: false when the call comes from user input */
|
|
54
|
+
programmatic?: boolean;
|
|
55
|
+
}
|
|
56
|
+
type ScrollListener = (d: Smoother) => void;
|
|
57
|
+
export declare const expoOut: Easing;
|
|
58
|
+
export declare class Smoother {
|
|
59
|
+
options: Required<Omit<SmootherOptions, 'duration' | 'easing' | 'wrapper' | 'content'>> & Pick<SmootherOptions, 'duration' | 'easing'> & {
|
|
60
|
+
wrapper: Window | HTMLElement;
|
|
61
|
+
content: HTMLElement;
|
|
62
|
+
};
|
|
63
|
+
/** Where the scroll is heading */
|
|
64
|
+
targetScroll: number;
|
|
65
|
+
/** Where the scroll is this frame */
|
|
66
|
+
animatedScroll: number;
|
|
67
|
+
velocity: number;
|
|
68
|
+
direction: -1 | 0 | 1;
|
|
69
|
+
isTouching: boolean;
|
|
70
|
+
private _state;
|
|
71
|
+
private _stopped;
|
|
72
|
+
private _locked;
|
|
73
|
+
private _skipNative;
|
|
74
|
+
private _time;
|
|
75
|
+
private _raf;
|
|
76
|
+
private _velTimer?;
|
|
77
|
+
private _resizeTimer?;
|
|
78
|
+
private _ro?;
|
|
79
|
+
private _height;
|
|
80
|
+
private _scrollHeight;
|
|
81
|
+
private _touch;
|
|
82
|
+
private _lastDelta;
|
|
83
|
+
private _listeners;
|
|
84
|
+
private _styleCache;
|
|
85
|
+
private _rm;
|
|
86
|
+
private _tw;
|
|
87
|
+
constructor(o?: SmootherOptions);
|
|
88
|
+
/** Advance one frame. Call from your own loop (e.g. gsap.ticker) when autoRaf is false */
|
|
89
|
+
raf: (time: number) => void;
|
|
90
|
+
/** Scroll to a number, '#id', a CSS selector, an element, or 'top' / 'bottom' */
|
|
91
|
+
scrollTo(target: number | string | Element, o?: SmootherScrollToOptions): undefined;
|
|
92
|
+
/** Block all scrolling (modals, menus) */
|
|
93
|
+
stop(): void;
|
|
94
|
+
start(): void;
|
|
95
|
+
/** Re-measure after layout changes the observers can't see */
|
|
96
|
+
resize(): void;
|
|
97
|
+
/** Listen to every scroll frame. Returns an unsubscribe function */
|
|
98
|
+
on(_event: 'scroll', fn: ScrollListener): () => undefined;
|
|
99
|
+
off(_event: 'scroll', fn: ScrollListener): void;
|
|
100
|
+
destroy(): void;
|
|
101
|
+
get limit(): number;
|
|
102
|
+
get actualScroll(): number;
|
|
103
|
+
get scroll(): number;
|
|
104
|
+
get progress(): number;
|
|
105
|
+
get isScrolling(): ScrollState;
|
|
106
|
+
get isSmooth(): boolean;
|
|
107
|
+
get isStopped(): boolean;
|
|
108
|
+
get isLocked(): boolean;
|
|
109
|
+
private _onWheel;
|
|
110
|
+
private _onTouch;
|
|
111
|
+
/** The decision chain every wheel/touch event goes through */
|
|
112
|
+
private _input;
|
|
113
|
+
/** True when the event should be left to a child: opt-out attributes or a scrollable child */
|
|
114
|
+
private _prevented;
|
|
115
|
+
/** Can this child scroll further in the wheel's direction? Styles cached for 2 s */
|
|
116
|
+
private _canScroll;
|
|
117
|
+
/** Keyboard, scrollbar drag, native touch, find-in-page: copy the browser's position in */
|
|
118
|
+
private _onNative;
|
|
119
|
+
private _onClick;
|
|
120
|
+
private _onPointer;
|
|
121
|
+
private _onResize;
|
|
122
|
+
private _advance;
|
|
123
|
+
private _resolve;
|
|
124
|
+
private _set;
|
|
125
|
+
private _measure;
|
|
126
|
+
private _reset;
|
|
127
|
+
private _skipNextNative;
|
|
128
|
+
private _emit;
|
|
129
|
+
private get _root();
|
|
130
|
+
private _setState;
|
|
131
|
+
private _setStopped;
|
|
132
|
+
private _setLocked;
|
|
133
|
+
private _classes;
|
|
134
|
+
}
|
|
135
|
+
export default Smoother;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=100/6,s=(t,s,i)=>Math.max(t,Math.min(s,i));export const expoOut=t=>Math.min(1,1.001-2**(-10*t));export class Smoother{constructor(s={}){this.velocity=0,this.direction=0,this.isTouching=!1,this.i=!1,this.h=!1,this.u=!1,this.m=!1,this.l=0,this.p=0,this.M=0,this._=0,this.S={x:0,y:0},this.T=0,this.k=new Set,this.L=new WeakMap,this.F=matchMedia("(prefers-reduced-motion: reduce)"),this.A={on:!1,v:0,from:0,to:0,t:0,lerp:void 0,dur:void 0,ease:void 0,cb:void 0},this.raf=t=>{const s=(t-(this.l||t))/1e3;this.l=t,this.R(s),this.options.autoRaf&&(this.p=requestAnimationFrame(this.raf))},this.C=s=>{const i=1===s.deltaMode?t:2===s.deltaMode?innerHeight:1;this.H(s.deltaX*i,s.deltaY*i*this.options.wheelMultiplier,s)},this.O=t=>{const s=t.targetTouches[0]??t.changedTouches[0];if(!s)return;let i=0,h=0;"touchstart"===t.type?this.T=0:"touchmove"===t.type?(i=-(s.clientX-this.S.x)*this.options.touchMultiplier,h=this.T=-(s.clientY-this.S.y)*this.options.touchMultiplier):h=this.T,this.S={x:s.clientX,y:s.clientY},this.H(i,h,t)},this.q=()=>{if(clearTimeout(this.j),this.m&&(this.m=!1,Math.abs(this.actualScroll-this.animatedScroll)<1))return;if("smooth"===this.i)return;const t=this.animatedScroll;this.animatedScroll=this.targetScroll=this.actualScroll,this.velocity=this.animatedScroll-t,this.direction=Math.sign(this.velocity),this.h||this.I("native"),this.N(),0!==this.velocity&&(this.j=setTimeout(()=>{this.velocity=0,this.I(!1),this.N()},400))},this.U=t=>{if(t.defaultPrevented||t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;const s=t.composedPath().find(t=>t instanceof HTMLAnchorElement&&!!t.href);if(!s)return;const i=new URL(s.href);if(!i.hash||i.host!==location.host||i.pathname!==location.pathname)return;t.preventDefault();const h="object"==typeof this.options.anchors?this.options.anchors:{};this.scrollTo(decodeURIComponent(i.hash),h);try{location.hash!==i.hash&&history.pushState(null,"",i.hash)}catch{}},this.W=t=>{1===t.button&&this.Y()},this.$=()=>{clearTimeout(this.B),this.B=setTimeout(()=>this.D(),250)};const i=s.wrapper&&s.wrapper!==document.documentElement?s.wrapper:window;if(this.options={wrapper:i,content:s.content??document.documentElement,lerp:s.lerp??.1,duration:s.duration,easing:s.easing,smoothWheel:s.smoothWheel??!0,wheelMultiplier:s.wheelMultiplier??1,syncTouch:s.syncTouch??!1,syncTouchLerp:s.syncTouchLerp??.075,touchMultiplier:s.touchMultiplier??1,touchInertiaExponent:s.touchInertiaExponent??1.7,nestedScroll:s.nestedScroll??!0,anchors:s.anchors??!1,autoRaf:s.autoRaf??!0,respectReducedMotion:s.respectReducedMotion??!0},!document.getElementById("smoother-css")){const t=document.createElement("style");t.id="smoother-css",t.textContent="html.smoother,html.smoother body{height:auto}.smoother.smoother-stopped{overflow:clip}.smoother [data-smoother-prevent],.smoother [data-smoother-prevent-wheel],.smoother [data-smoother-prevent-touch]{overscroll-behavior:contain}.smoother.smoother-smooth iframe{pointer-events:none}",document.head.appendChild(t)}this.D(),this.targetScroll=this.animatedScroll=this.actualScroll,this.G();const h=i,e={passive:!1};h.addEventListener("scroll",this.q,{passive:!0}),h.addEventListener("wheel",this.C,e),h.addEventListener("pointerdown",this.W),this.options.anchors&&h.addEventListener("click",this.U),this.options.syncTouch&&(h.addEventListener("touchstart",this.O,e),h.addEventListener("touchmove",this.O,e),h.addEventListener("touchend",this.O,e)),addEventListener("resize",this.$),this.J=new ResizeObserver(this.$),this.J.observe(i===window?this.options.content:i),this.options.autoRaf&&(this.p=requestAnimationFrame(this.raf))}scrollTo(t,i={}){const h=i.programmatic??!0;let{immediate:e,lerp:o=(h?this.options.lerp:void 0)}=i,r=i.duration??(h?this.options.duration:void 0),n=i.easing??(h?this.options.easing:void 0);if(this.options.respectReducedMotion&&this.F.matches&&(h?e=!0:(o=1,r=n=void 0)),(this.h||this.u)&&!i.force)return;const c=this.K(t);if(null===c)return;const u=s(0,c+(i.offset??0),this.limit);if(u===this.targetScroll)return void i.onComplete?.(this);if(e)return this.animatedScroll=this.targetScroll=u,this.P(u),this.Y(),this.V(),this.N(),void i.onComplete?.(this);h||(this.targetScroll=u),"number"!=typeof r||n?n&&"number"!=typeof r&&(r=1):n=expoOut,i.lock&&this.X(!0),this.I("smooth");const a=this.A;Object.assign(a,{on:!0,v:this.animatedScroll,from:this.animatedScroll,to:u,t:0,lerp:o,dur:r,ease:n}),a.cb=(t,s)=>{this.I("smooth"),this.velocity=t-this.animatedScroll,this.direction=Math.sign(this.velocity),this.animatedScroll=t,this.P(t),h&&(this.targetScroll=t),s?(this.Y(),this.N(),i.onComplete?.(this),this.V()):this.N()}}stop(){this.h||(this.Y(),this.Z(!0),this.N())}start(){this.h&&(this.Y(),this.Z(!1),this.N())}resize(){this.D(),this.animatedScroll=this.targetScroll=this.actualScroll,this.N()}on(t,s){return this.k.add(s),()=>{this.k.delete(s)}}off(t,s){this.k.delete(s)}destroy(){const t=this.options.wrapper;t.removeEventListener("scroll",this.q),t.removeEventListener("wheel",this.C),t.removeEventListener("pointerdown",this.W),t.removeEventListener("click",this.U),t.removeEventListener("touchstart",this.O),t.removeEventListener("touchmove",this.O),t.removeEventListener("touchend",this.O),removeEventListener("resize",this.$),this.J?.disconnect(),cancelAnimationFrame(this.p),clearTimeout(this.j),clearTimeout(this.B),this.k.clear(),this.tt.classList.remove("smoother","smoother-scrolling","smoother-smooth","smoother-stopped","smoother-locked")}get limit(){return Math.max(0,this._-this.M)}get actualScroll(){const t=this.options.wrapper;return t===window?scrollY:t.scrollTop}get scroll(){return this.animatedScroll}get progress(){return 0===this.limit?1:this.animatedScroll/this.limit}get isScrolling(){return this.i}get isSmooth(){return"smooth"===this.i}get isStopped(){return this.h}get isLocked(){return this.u}H(t,s,i){if(i.ctrlKey)return;const h=i.type.startsWith("touch");if(this.isTouching="touchstart"===i.type||"touchmove"===i.type,0===t&&0===s)return void(!h||"touchstart"!==i.type||this.h||this.u||this.Y());if(0===s)return;if(this.limit<=0)return;if(this.st(i,s,h))return;if(this.h||this.u)return void(i.cancelable&&i.preventDefault());if(!(h?this.options.syncTouch:this.options.smoothWheel))return this.I("native"),void(this.A.on=!1);i.cancelable&&i.preventDefault();const e="touchend"===i.type,o=e?Math.sign(s)*Math.abs(this.velocity)**this.options.touchInertiaExponent:s;this.scrollTo(this.targetScroll+o,{programmatic:!1,...h?{lerp:e?this.options.syncTouchLerp:1}:{lerp:this.options.lerp,duration:this.options.duration,easing:this.options.easing}})}st(t,s,i){const h=t.composedPath(),e=h.indexOf(this.tt);for(const t of e<0?h:h.slice(0,e))if(t instanceof HTMLElement){if(t.hasAttribute("data-smoother-prevent"))return!0;if(t.hasAttribute(i?"data-smoother-prevent-touch":"data-smoother-prevent-wheel"))return!0;if(this.options.nestedScroll&&this.it(t,s))return!0}return!1}it(t,s){const i=performance.now();let h=this.L.get(t);if(!h||i-h.t>2e3){const s=getComputedStyle(t);h={t:i,o:/^(auto|scroll|overlay)$/.test(s.overflowY),c:"auto"!==s.overscrollBehaviorY},this.L.set(t,h)}if(!h.o)return!1;const e=t.scrollHeight-t.clientHeight;return!(e<=0||!h.c&&!(s>0?t.scrollTop<e-1:t.scrollTop>0))}R(t){const i=this.A;if(!i.on)return;let h=!1;if(i.dur&&i.ease){i.t+=t;const e=s(0,i.t/i.dur,1);h=e>=1,i.v=i.from+(i.to-i.from)*(h?1:i.ease(e))}else i.lerp?(i.v=((t,s,i,h)=>t+(s-t)*(1-Math.exp(-i*h)))(i.v,i.to,60*i.lerp,t),Math.round(i.v)===Math.round(i.to)&&(i.v=i.to,h=!0)):(i.v=i.to,h=!0);h&&(i.on=!1),i.cb?.(i.v,h)}K(t){if("number"==typeof t)return t;if("top"===t||"start"===t||"#"===t)return 0;if("bottom"===t||"end"===t)return this.limit;const s="string"==typeof t?"#"===t[0]?document.getElementById(t.slice(1)):document.querySelector(t):t;if(!s)return"#top"===t?0:null;const i=this.options.wrapper,h=i===window?0:i.getBoundingClientRect().top,e=parseFloat(getComputedStyle(s).scrollMarginTop)||0,o=parseFloat(getComputedStyle(this.tt).scrollPaddingTop)||0;return s.getBoundingClientRect().top-h+this.actualScroll-e-o}P(t){this.options.wrapper.scrollTo({top:t,behavior:"instant"})}D(){const t=this.options.wrapper;t===window?(this.M=innerHeight,this._=this.options.content.scrollHeight):(this.M=t.clientHeight,this._=t.scrollHeight)}Y(){this.X(!1),this.I(!1),this.animatedScroll=this.targetScroll=this.actualScroll,this.velocity=0,this.A.on=!1}V(){this.m=!0,requestAnimationFrame(()=>this.m=!1)}N(){this.k.forEach(t=>t(this))}get tt(){const t=this.options.wrapper;return t===window?document.documentElement:t}I(t){this.i!==t&&(this.i=t,this.G())}Z(t){this.h!==t&&(this.h=t,this.G())}X(t){this.u!==t&&(this.u=t,this.G())}G(){const t=this.tt.classList;t.add("smoother"),t.toggle("smoother-scrolling",!!this.i),t.toggle("smoother-smooth","smooth"===this.i),t.toggle("smoother-stopped",this.h),t.toggle("smoother-locked",this.u)}}export default Smoother;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(()=>{const t=100/6,s=(t,s,i)=>Math.max(t,Math.min(s,i)),i=t=>Math.min(1,1.001-2**(-10*t));class h{constructor(s={}){this.velocity=0,this.direction=0,this.isTouching=!1,this.i=!1,this.h=!1,this.u=!1,this.m=!1,this.l=0,this.p=0,this.M=0,this._=0,this.S={x:0,y:0},this.T=0,this.k=new Set,this.L=new WeakMap,this.F=matchMedia("(prefers-reduced-motion: reduce)"),this.A={on:!1,v:0,from:0,to:0,t:0,lerp:void 0,dur:void 0,ease:void 0,cb:void 0},this.raf=t=>{const s=(t-(this.l||t))/1e3;this.l=t,this.R(s),this.options.autoRaf&&(this.p=requestAnimationFrame(this.raf))},this.C=s=>{const i=1===s.deltaMode?t:2===s.deltaMode?innerHeight:1;this.H(s.deltaX*i,s.deltaY*i*this.options.wheelMultiplier,s)},this.q=t=>{const s=t.targetTouches[0]??t.changedTouches[0];if(!s)return;let i=0,h=0;"touchstart"===t.type?this.T=0:"touchmove"===t.type?(i=-(s.clientX-this.S.x)*this.options.touchMultiplier,h=this.T=-(s.clientY-this.S.y)*this.options.touchMultiplier):h=this.T,this.S={x:s.clientX,y:s.clientY},this.H(i,h,t)},this.j=()=>{if(clearTimeout(this.I),this.m&&(this.m=!1,Math.abs(this.actualScroll-this.animatedScroll)<1))return;if("smooth"===this.i)return;const t=this.animatedScroll;this.animatedScroll=this.targetScroll=this.actualScroll,this.velocity=this.animatedScroll-t,this.direction=Math.sign(this.velocity),this.h||this.N("native"),this.O(),0!==this.velocity&&(this.I=setTimeout(()=>{this.velocity=0,this.N(!1),this.O()},400))},this.U=t=>{if(t.defaultPrevented||t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;const s=t.composedPath().find(t=>t instanceof HTMLAnchorElement&&!!t.href);if(!s)return;const i=new URL(s.href);if(!i.hash||i.host!==location.host||i.pathname!==location.pathname)return;t.preventDefault();const h="object"==typeof this.options.anchors?this.options.anchors:{};this.scrollTo(decodeURIComponent(i.hash),h);try{location.hash!==i.hash&&history.pushState(null,"",i.hash)}catch{}},this.W=t=>{1===t.button&&this.Y()},this.$=()=>{clearTimeout(this.B),this.B=setTimeout(()=>this.D(),250)};const i=s.wrapper&&s.wrapper!==document.documentElement?s.wrapper:window;if(this.options={wrapper:i,content:s.content??document.documentElement,lerp:s.lerp??.1,duration:s.duration,easing:s.easing,smoothWheel:s.smoothWheel??!0,wheelMultiplier:s.wheelMultiplier??1,syncTouch:s.syncTouch??!1,syncTouchLerp:s.syncTouchLerp??.075,touchMultiplier:s.touchMultiplier??1,touchInertiaExponent:s.touchInertiaExponent??1.7,nestedScroll:s.nestedScroll??!0,anchors:s.anchors??!1,autoRaf:s.autoRaf??!0,respectReducedMotion:s.respectReducedMotion??!0},!document.getElementById("smoother-css")){const t=document.createElement("style");t.id="smoother-css",t.textContent="html.smoother,html.smoother body{height:auto}.smoother.smoother-stopped{overflow:clip}.smoother [data-smoother-prevent],.smoother [data-smoother-prevent-wheel],.smoother [data-smoother-prevent-touch]{overscroll-behavior:contain}.smoother.smoother-smooth iframe{pointer-events:none}",document.head.appendChild(t)}this.D(),this.targetScroll=this.animatedScroll=this.actualScroll,this.G();const h=i,e={passive:!1};h.addEventListener("scroll",this.j,{passive:!0}),h.addEventListener("wheel",this.C,e),h.addEventListener("pointerdown",this.W),this.options.anchors&&h.addEventListener("click",this.U),this.options.syncTouch&&(h.addEventListener("touchstart",this.q,e),h.addEventListener("touchmove",this.q,e),h.addEventListener("touchend",this.q,e)),addEventListener("resize",this.$),this.J=new ResizeObserver(this.$),this.J.observe(i===window?this.options.content:i),this.options.autoRaf&&(this.p=requestAnimationFrame(this.raf))}scrollTo(t,h={}){const e=h.programmatic??!0;let{immediate:o,lerp:r=(e?this.options.lerp:void 0)}=h,n=h.duration??(e?this.options.duration:void 0),c=h.easing??(e?this.options.easing:void 0);if(this.options.respectReducedMotion&&this.F.matches&&(e?o=!0:(r=1,n=c=void 0)),(this.h||this.u)&&!h.force)return;const u=this.K(t);if(null===u)return;const a=s(0,u+(h.offset??0),this.limit);if(a===this.targetScroll)return void h.onComplete?.(this);if(o)return this.animatedScroll=this.targetScroll=a,this.P(a),this.Y(),this.V(),this.O(),void h.onComplete?.(this);e||(this.targetScroll=a),"number"!=typeof n||c?c&&"number"!=typeof n&&(n=1):c=i,h.lock&&this.X(!0),this.N("smooth");const m=this.A;Object.assign(m,{on:!0,v:this.animatedScroll,from:this.animatedScroll,to:a,t:0,lerp:r,dur:n,ease:c}),m.cb=(t,s)=>{this.N("smooth"),this.velocity=t-this.animatedScroll,this.direction=Math.sign(this.velocity),this.animatedScroll=t,this.P(t),e&&(this.targetScroll=t),s?(this.Y(),this.O(),h.onComplete?.(this),this.V()):this.O()}}stop(){this.h||(this.Y(),this.Z(!0),this.O())}start(){this.h&&(this.Y(),this.Z(!1),this.O())}resize(){this.D(),this.animatedScroll=this.targetScroll=this.actualScroll,this.O()}on(t,s){return this.k.add(s),()=>{this.k.delete(s)}}off(t,s){this.k.delete(s)}destroy(){const t=this.options.wrapper;t.removeEventListener("scroll",this.j),t.removeEventListener("wheel",this.C),t.removeEventListener("pointerdown",this.W),t.removeEventListener("click",this.U),t.removeEventListener("touchstart",this.q),t.removeEventListener("touchmove",this.q),t.removeEventListener("touchend",this.q),removeEventListener("resize",this.$),this.J?.disconnect(),cancelAnimationFrame(this.p),clearTimeout(this.I),clearTimeout(this.B),this.k.clear(),this.tt.classList.remove("smoother","smoother-scrolling","smoother-smooth","smoother-stopped","smoother-locked")}get limit(){return Math.max(0,this._-this.M)}get actualScroll(){const t=this.options.wrapper;return t===window?scrollY:t.scrollTop}get scroll(){return this.animatedScroll}get progress(){return 0===this.limit?1:this.animatedScroll/this.limit}get isScrolling(){return this.i}get isSmooth(){return"smooth"===this.i}get isStopped(){return this.h}get isLocked(){return this.u}H(t,s,i){if(i.ctrlKey)return;const h=i.type.startsWith("touch");if(this.isTouching="touchstart"===i.type||"touchmove"===i.type,0===t&&0===s)return void(!h||"touchstart"!==i.type||this.h||this.u||this.Y());if(0===s)return;if(this.limit<=0)return;if(this.st(i,s,h))return;if(this.h||this.u)return void(i.cancelable&&i.preventDefault());if(!(h?this.options.syncTouch:this.options.smoothWheel))return this.N("native"),void(this.A.on=!1);i.cancelable&&i.preventDefault();const e="touchend"===i.type,o=e?Math.sign(s)*Math.abs(this.velocity)**this.options.touchInertiaExponent:s;this.scrollTo(this.targetScroll+o,{programmatic:!1,...h?{lerp:e?this.options.syncTouchLerp:1}:{lerp:this.options.lerp,duration:this.options.duration,easing:this.options.easing}})}st(t,s,i){const h=t.composedPath(),e=h.indexOf(this.tt);for(const t of e<0?h:h.slice(0,e))if(t instanceof HTMLElement){if(t.hasAttribute("data-smoother-prevent"))return!0;if(t.hasAttribute(i?"data-smoother-prevent-touch":"data-smoother-prevent-wheel"))return!0;if(this.options.nestedScroll&&this.it(t,s))return!0}return!1}it(t,s){const i=performance.now();let h=this.L.get(t);if(!h||i-h.t>2e3){const s=getComputedStyle(t);h={t:i,o:/^(auto|scroll|overlay)$/.test(s.overflowY),c:"auto"!==s.overscrollBehaviorY},this.L.set(t,h)}if(!h.o)return!1;const e=t.scrollHeight-t.clientHeight;return!(e<=0||!h.c&&!(s>0?t.scrollTop<e-1:t.scrollTop>0))}R(t){const i=this.A;if(!i.on)return;let h=!1;if(i.dur&&i.ease){i.t+=t;const e=s(0,i.t/i.dur,1);h=e>=1,i.v=i.from+(i.to-i.from)*(h?1:i.ease(e))}else i.lerp?(i.v=((t,s,i,h)=>t+(s-t)*(1-Math.exp(-i*h)))(i.v,i.to,60*i.lerp,t),Math.round(i.v)===Math.round(i.to)&&(i.v=i.to,h=!0)):(i.v=i.to,h=!0);h&&(i.on=!1),i.cb?.(i.v,h)}K(t){if("number"==typeof t)return t;if("top"===t||"start"===t||"#"===t)return 0;if("bottom"===t||"end"===t)return this.limit;const s="string"==typeof t?"#"===t[0]?document.getElementById(t.slice(1)):document.querySelector(t):t;if(!s)return"#top"===t?0:null;const i=this.options.wrapper,h=i===window?0:i.getBoundingClientRect().top,e=parseFloat(getComputedStyle(s).scrollMarginTop)||0,o=parseFloat(getComputedStyle(this.tt).scrollPaddingTop)||0;return s.getBoundingClientRect().top-h+this.actualScroll-e-o}P(t){this.options.wrapper.scrollTo({top:t,behavior:"instant"})}D(){const t=this.options.wrapper;t===window?(this.M=innerHeight,this._=this.options.content.scrollHeight):(this.M=t.clientHeight,this._=t.scrollHeight)}Y(){this.X(!1),this.N(!1),this.animatedScroll=this.targetScroll=this.actualScroll,this.velocity=0,this.A.on=!1}V(){this.m=!0,requestAnimationFrame(()=>this.m=!1)}O(){this.k.forEach(t=>t(this))}get tt(){const t=this.options.wrapper;return t===window?document.documentElement:t}N(t){this.i!==t&&(this.i=t,this.G())}Z(t){this.h!==t&&(this.h=t,this.G())}X(t){this.u!==t&&(this.u=t,this.G())}G(){const t=this.tt.classList;t.add("smoother"),t.toggle("smoother-scrolling",!!this.i),t.toggle("smoother-smooth","smooth"===this.i),t.toggle("smoother-stopped",this.h),t.toggle("smoother-locked",this.u)}}window.Smoother=h,h.expoOut=i})();
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type ReactNode } from 'react';
|
|
2
|
+
import { Smoother, type SmootherOptions } from './index.js';
|
|
3
|
+
/** Wrap the app once (app/layout.tsx). Creates one Smoother instance for the window. */
|
|
4
|
+
export declare function SmootherProvider({ options, children }: {
|
|
5
|
+
options?: SmootherOptions;
|
|
6
|
+
children: ReactNode;
|
|
7
|
+
}): import("react").JSX.Element;
|
|
8
|
+
/** The live instance (null on the first render). Pass a stable callback to run on every scroll frame. */
|
|
9
|
+
export declare function useSmoother(onScroll?: (d: Smoother) => void): Smoother | null;
|
package/dist/react.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use client";import{jsx as r}from"react/jsx-runtime";import{createContext as o,useContext as n,useEffect as t,useState as e}from"react";import{Smoother as i}from"./index.js";const s=o(null);export function SmootherProvider({options:o,children:n}){const[u,c]=e(null),l=JSON.stringify(o??{});return t(()=>{const r=new i(o);return c(r),()=>{r.destroy(),c(null)}},[l]),r(s.Provider,{value:u,children:n})}export function useSmoother(r){const o=n(s);return t(()=>{if(o&&r)return o.on("scroll",r)},[o,r]),o}
|
package/package.json
CHANGED
|
@@ -1,6 +1,64 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "kavan-smoother",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Lightweight smooth scroll (about 3 KB gzipped). Native scroll stays native, the wheel gets eased. Works with GSAP ScrollTrigger, React and Next.js.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"smooth-scroll",
|
|
7
|
+
"smooth scroll",
|
|
8
|
+
"scroll",
|
|
9
|
+
"lenis",
|
|
10
|
+
"lerp",
|
|
11
|
+
"gsap",
|
|
12
|
+
"scrolltrigger",
|
|
13
|
+
"react",
|
|
14
|
+
"nextjs"
|
|
15
|
+
],
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"author": "Kavan Gami",
|
|
18
|
+
"type": "module",
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"main": "./dist/index.js",
|
|
21
|
+
"module": "./dist/index.js",
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"unpkg": "./dist/kavan-smoother.global.min.js",
|
|
24
|
+
"jsdelivr": "./dist/kavan-smoother.global.min.js",
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"import": "./dist/index.js",
|
|
29
|
+
"default": "./dist/index.js"
|
|
30
|
+
},
|
|
31
|
+
"./react": {
|
|
32
|
+
"types": "./dist/react.d.ts",
|
|
33
|
+
"import": "./dist/react.js",
|
|
34
|
+
"default": "./dist/react.js"
|
|
35
|
+
},
|
|
36
|
+
"./global": "./dist/kavan-smoother.global.min.js",
|
|
37
|
+
"./package.json": "./package.json"
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"dist",
|
|
41
|
+
"src"
|
|
42
|
+
],
|
|
43
|
+
"scripts": {
|
|
44
|
+
"build": "node scripts/build.mjs",
|
|
45
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
46
|
+
"test": "node test/run.mjs",
|
|
47
|
+
"prepublishOnly": "npm run typecheck && npm run build"
|
|
48
|
+
},
|
|
49
|
+
"peerDependencies": {
|
|
50
|
+
"react": ">=18"
|
|
51
|
+
},
|
|
52
|
+
"peerDependenciesMeta": {
|
|
53
|
+
"react": {
|
|
54
|
+
"optional": true
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
"devDependencies": {
|
|
58
|
+
"@types/react": "^19.3.0",
|
|
59
|
+
"playwright": "^1.65.0",
|
|
60
|
+
"react": "^19.3.1",
|
|
61
|
+
"terser": "^5.36.0",
|
|
62
|
+
"typescript": "^5.9.3"
|
|
63
|
+
}
|
|
64
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,531 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* kavan-smoother: a lightweight, dependency-free smooth scroller.
|
|
3
|
+
*
|
|
4
|
+
* Same model as Lenis 1.3: the page keeps its native scroll, wheel input is
|
|
5
|
+
* intercepted, a virtual position is animated toward a target every frame and
|
|
6
|
+
* written back with scrollTo(). Because the real scroll position changes,
|
|
7
|
+
* position: sticky, IntersectionObserver and GSAP ScrollTrigger keep working.
|
|
8
|
+
*
|
|
9
|
+
* Vertical only. Members prefixed with "_" are internal (mangled when minified).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export type Easing = (t: number) => number
|
|
13
|
+
export type ScrollState = false | 'native' | 'smooth'
|
|
14
|
+
|
|
15
|
+
export interface SmootherOptions {
|
|
16
|
+
/** Scroll container. Default: window */
|
|
17
|
+
wrapper?: Window | HTMLElement
|
|
18
|
+
/** Element whose height sets the scroll limit. Default: <html> */
|
|
19
|
+
content?: HTMLElement
|
|
20
|
+
/** Catch-up per 60 fps frame, 0–1. Lower = floatier. Default 0.1 */
|
|
21
|
+
lerp?: number
|
|
22
|
+
/** Seconds per wheel animation. Setting it switches from lerp to easing mode */
|
|
23
|
+
duration?: number
|
|
24
|
+
/** Easing for duration mode. Default: expo-out */
|
|
25
|
+
easing?: Easing
|
|
26
|
+
/** Smooth the mouse wheel / trackpad. Default true */
|
|
27
|
+
smoothWheel?: boolean
|
|
28
|
+
wheelMultiplier?: number
|
|
29
|
+
/** Smooth touch too (fingers drive the animation, with inertia). Default false = native touch */
|
|
30
|
+
syncTouch?: boolean
|
|
31
|
+
syncTouchLerp?: number
|
|
32
|
+
touchMultiplier?: number
|
|
33
|
+
touchInertiaExponent?: number
|
|
34
|
+
/** Let scrollable children (menus, modals, code blocks) scroll themselves. Default true */
|
|
35
|
+
nestedScroll?: boolean
|
|
36
|
+
/** Animate same-page #hash links. Pass an object for scrollTo options */
|
|
37
|
+
anchors?: boolean | SmootherScrollToOptions
|
|
38
|
+
/** Run its own requestAnimationFrame loop. Set false when gsap.ticker drives raf(). Default true */
|
|
39
|
+
autoRaf?: boolean
|
|
40
|
+
/** Jump instead of animating when the OS asks for reduced motion. Default true */
|
|
41
|
+
respectReducedMotion?: boolean
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface SmootherScrollToOptions {
|
|
45
|
+
offset?: number
|
|
46
|
+
/** Jump with no animation */
|
|
47
|
+
immediate?: boolean
|
|
48
|
+
/** Ignore user input until the animation finishes */
|
|
49
|
+
lock?: boolean
|
|
50
|
+
/** Scroll even while stopped */
|
|
51
|
+
force?: boolean
|
|
52
|
+
lerp?: number
|
|
53
|
+
duration?: number
|
|
54
|
+
easing?: Easing
|
|
55
|
+
onComplete?: (d: Smoother) => void
|
|
56
|
+
/** Internal: false when the call comes from user input */
|
|
57
|
+
programmatic?: boolean
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
type ScrollListener = (d: Smoother) => void
|
|
61
|
+
|
|
62
|
+
const LINE = 100 / 6 // px per "line" when a mouse reports deltaMode 1 (Firefox)
|
|
63
|
+
const clamp = (min: number, v: number, max: number) => Math.max(min, Math.min(v, max))
|
|
64
|
+
/** Frame-rate independent lerp: the same feel at 60 Hz and 144 Hz */
|
|
65
|
+
const damp = (a: number, b: number, lambda: number, dt: number) =>
|
|
66
|
+
a + (b - a) * (1 - Math.exp(-lambda * dt))
|
|
67
|
+
export const expoOut: Easing = (t) => Math.min(1, 1.001 - 2 ** (-10 * t))
|
|
68
|
+
|
|
69
|
+
const CSS =
|
|
70
|
+
'html.smoother,html.smoother body{height:auto}' +
|
|
71
|
+
'.smoother.smoother-stopped{overflow:clip}' +
|
|
72
|
+
'.smoother [data-smoother-prevent],.smoother [data-smoother-prevent-wheel],.smoother [data-smoother-prevent-touch]{overscroll-behavior:contain}' +
|
|
73
|
+
'.smoother.smoother-smooth iframe{pointer-events:none}'
|
|
74
|
+
|
|
75
|
+
export class Smoother {
|
|
76
|
+
options: Required<Omit<SmootherOptions, 'duration' | 'easing' | 'wrapper' | 'content'>> &
|
|
77
|
+
Pick<SmootherOptions, 'duration' | 'easing'> & { wrapper: Window | HTMLElement; content: HTMLElement }
|
|
78
|
+
|
|
79
|
+
/** Where the scroll is heading */
|
|
80
|
+
targetScroll: number
|
|
81
|
+
/** Where the scroll is this frame */
|
|
82
|
+
animatedScroll: number
|
|
83
|
+
velocity = 0
|
|
84
|
+
direction: -1 | 0 | 1 = 0
|
|
85
|
+
isTouching = false
|
|
86
|
+
|
|
87
|
+
private _state: ScrollState = false
|
|
88
|
+
private _stopped = false
|
|
89
|
+
private _locked = false
|
|
90
|
+
private _skipNative = false
|
|
91
|
+
private _time = 0
|
|
92
|
+
private _raf = 0
|
|
93
|
+
private _velTimer?: ReturnType<typeof setTimeout>
|
|
94
|
+
private _resizeTimer?: ReturnType<typeof setTimeout>
|
|
95
|
+
private _ro?: ResizeObserver
|
|
96
|
+
private _height = 0
|
|
97
|
+
private _scrollHeight = 0
|
|
98
|
+
private _touch = { x: 0, y: 0 }
|
|
99
|
+
private _lastDelta = 0
|
|
100
|
+
private _listeners = new Set<ScrollListener>()
|
|
101
|
+
private _styleCache = new WeakMap<Element, { t: number; o: boolean; c: boolean }>()
|
|
102
|
+
private _rm = matchMedia('(prefers-reduced-motion: reduce)')
|
|
103
|
+
|
|
104
|
+
// the tween: one number moved toward a target, by lerp or by duration + easing
|
|
105
|
+
private _tw = {
|
|
106
|
+
on: false,
|
|
107
|
+
v: 0,
|
|
108
|
+
from: 0,
|
|
109
|
+
to: 0,
|
|
110
|
+
t: 0,
|
|
111
|
+
lerp: undefined as number | undefined,
|
|
112
|
+
dur: undefined as number | undefined,
|
|
113
|
+
ease: undefined as Easing | undefined,
|
|
114
|
+
cb: undefined as ((v: number, done: boolean) => void) | undefined,
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
constructor(o: SmootherOptions = {}) {
|
|
118
|
+
const wrapper = !o.wrapper || o.wrapper === document.documentElement ? window : o.wrapper
|
|
119
|
+
this.options = {
|
|
120
|
+
wrapper,
|
|
121
|
+
content: o.content ?? document.documentElement,
|
|
122
|
+
lerp: o.lerp ?? 0.1,
|
|
123
|
+
duration: o.duration,
|
|
124
|
+
easing: o.easing,
|
|
125
|
+
smoothWheel: o.smoothWheel ?? true,
|
|
126
|
+
wheelMultiplier: o.wheelMultiplier ?? 1,
|
|
127
|
+
syncTouch: o.syncTouch ?? false,
|
|
128
|
+
syncTouchLerp: o.syncTouchLerp ?? 0.075,
|
|
129
|
+
touchMultiplier: o.touchMultiplier ?? 1,
|
|
130
|
+
touchInertiaExponent: o.touchInertiaExponent ?? 1.7,
|
|
131
|
+
nestedScroll: o.nestedScroll ?? true,
|
|
132
|
+
anchors: o.anchors ?? false,
|
|
133
|
+
autoRaf: o.autoRaf ?? true,
|
|
134
|
+
respectReducedMotion: o.respectReducedMotion ?? true,
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (!document.getElementById('smoother-css')) {
|
|
138
|
+
const s = document.createElement('style')
|
|
139
|
+
s.id = 'smoother-css'
|
|
140
|
+
s.textContent = CSS
|
|
141
|
+
document.head.appendChild(s)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
this._measure()
|
|
145
|
+
this.targetScroll = this.animatedScroll = this.actualScroll
|
|
146
|
+
this._classes()
|
|
147
|
+
|
|
148
|
+
const w = wrapper as HTMLElement // Window and HTMLElement share the listener API
|
|
149
|
+
const active = { passive: false }
|
|
150
|
+
w.addEventListener('scroll', this._onNative, { passive: true })
|
|
151
|
+
w.addEventListener('wheel', this._onWheel, active)
|
|
152
|
+
w.addEventListener('pointerdown', this._onPointer)
|
|
153
|
+
if (this.options.anchors) w.addEventListener('click', this._onClick)
|
|
154
|
+
if (this.options.syncTouch) {
|
|
155
|
+
w.addEventListener('touchstart', this._onTouch, active)
|
|
156
|
+
w.addEventListener('touchmove', this._onTouch, active)
|
|
157
|
+
w.addEventListener('touchend', this._onTouch, active)
|
|
158
|
+
}
|
|
159
|
+
addEventListener('resize', this._onResize)
|
|
160
|
+
this._ro = new ResizeObserver(this._onResize)
|
|
161
|
+
this._ro.observe(wrapper === window ? this.options.content : (wrapper as HTMLElement))
|
|
162
|
+
|
|
163
|
+
if (this.options.autoRaf) this._raf = requestAnimationFrame(this.raf)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/* ---------- public API ---------- */
|
|
167
|
+
|
|
168
|
+
/** Advance one frame. Call from your own loop (e.g. gsap.ticker) when autoRaf is false */
|
|
169
|
+
raf = (time: number) => {
|
|
170
|
+
const dt = (time - (this._time || time)) / 1000
|
|
171
|
+
this._time = time
|
|
172
|
+
this._advance(dt)
|
|
173
|
+
if (this.options.autoRaf) this._raf = requestAnimationFrame(this.raf)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Scroll to a number, '#id', a CSS selector, an element, or 'top' / 'bottom' */
|
|
177
|
+
scrollTo(target: number | string | Element, o: SmootherScrollToOptions = {}) {
|
|
178
|
+
const p = o.programmatic ?? true
|
|
179
|
+
let { immediate, lerp = p ? this.options.lerp : undefined } = o
|
|
180
|
+
let duration = o.duration ?? (p ? this.options.duration : undefined)
|
|
181
|
+
let easing = o.easing ?? (p ? this.options.easing : undefined)
|
|
182
|
+
|
|
183
|
+
if (this.options.respectReducedMotion && this._rm.matches) {
|
|
184
|
+
if (p) immediate = true
|
|
185
|
+
else (lerp = 1), (duration = easing = undefined)
|
|
186
|
+
}
|
|
187
|
+
if ((this._stopped || this._locked) && !o.force) return
|
|
188
|
+
|
|
189
|
+
const resolved = this._resolve(target)
|
|
190
|
+
if (resolved === null) return
|
|
191
|
+
const y = clamp(0, resolved + (o.offset ?? 0), this.limit)
|
|
192
|
+
|
|
193
|
+
if (y === this.targetScroll) return void o.onComplete?.(this)
|
|
194
|
+
|
|
195
|
+
if (immediate) {
|
|
196
|
+
this.animatedScroll = this.targetScroll = y
|
|
197
|
+
this._set(y)
|
|
198
|
+
this._reset()
|
|
199
|
+
this._skipNextNative()
|
|
200
|
+
this._emit()
|
|
201
|
+
return void o.onComplete?.(this)
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
if (!p) this.targetScroll = y
|
|
205
|
+
// giving only one of duration / easing still switches to time-based mode
|
|
206
|
+
if (typeof duration === 'number' && !easing) easing = expoOut
|
|
207
|
+
else if (easing && typeof duration !== 'number') duration = 1
|
|
208
|
+
|
|
209
|
+
if (o.lock) this._setLocked(true)
|
|
210
|
+
this._setState('smooth')
|
|
211
|
+
const tw = this._tw
|
|
212
|
+
Object.assign(tw, { on: true, v: this.animatedScroll, from: this.animatedScroll, to: y, t: 0, lerp, dur: duration, ease: easing })
|
|
213
|
+
tw.cb = (v, done) => {
|
|
214
|
+
this._setState('smooth')
|
|
215
|
+
this.velocity = v - this.animatedScroll
|
|
216
|
+
this.direction = Math.sign(this.velocity) as -1 | 0 | 1
|
|
217
|
+
this.animatedScroll = v
|
|
218
|
+
this._set(v)
|
|
219
|
+
// for API calls the target follows the animation, so a wheel tick interrupts it
|
|
220
|
+
if (p) this.targetScroll = v
|
|
221
|
+
if (done) {
|
|
222
|
+
this._reset()
|
|
223
|
+
this._emit()
|
|
224
|
+
o.onComplete?.(this)
|
|
225
|
+
this._skipNextNative()
|
|
226
|
+
} else this._emit()
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** Block all scrolling (modals, menus) */
|
|
231
|
+
stop() {
|
|
232
|
+
if (this._stopped) return
|
|
233
|
+
this._reset()
|
|
234
|
+
this._setStopped(true)
|
|
235
|
+
this._emit()
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
start() {
|
|
239
|
+
if (!this._stopped) return
|
|
240
|
+
this._reset()
|
|
241
|
+
this._setStopped(false)
|
|
242
|
+
this._emit()
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Re-measure after layout changes the observers can't see */
|
|
246
|
+
resize() {
|
|
247
|
+
this._measure()
|
|
248
|
+
this.animatedScroll = this.targetScroll = this.actualScroll
|
|
249
|
+
this._emit()
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Listen to every scroll frame. Returns an unsubscribe function */
|
|
253
|
+
on(_event: 'scroll', fn: ScrollListener) {
|
|
254
|
+
this._listeners.add(fn)
|
|
255
|
+
return () => void this._listeners.delete(fn)
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
off(_event: 'scroll', fn: ScrollListener) {
|
|
259
|
+
this._listeners.delete(fn)
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
destroy() {
|
|
263
|
+
const w = this.options.wrapper as HTMLElement
|
|
264
|
+
w.removeEventListener('scroll', this._onNative)
|
|
265
|
+
w.removeEventListener('wheel', this._onWheel)
|
|
266
|
+
w.removeEventListener('pointerdown', this._onPointer)
|
|
267
|
+
w.removeEventListener('click', this._onClick)
|
|
268
|
+
w.removeEventListener('touchstart', this._onTouch)
|
|
269
|
+
w.removeEventListener('touchmove', this._onTouch)
|
|
270
|
+
w.removeEventListener('touchend', this._onTouch)
|
|
271
|
+
removeEventListener('resize', this._onResize)
|
|
272
|
+
this._ro?.disconnect()
|
|
273
|
+
cancelAnimationFrame(this._raf)
|
|
274
|
+
clearTimeout(this._velTimer)
|
|
275
|
+
clearTimeout(this._resizeTimer)
|
|
276
|
+
this._listeners.clear()
|
|
277
|
+
this._root.classList.remove('smoother', 'smoother-scrolling', 'smoother-smooth', 'smoother-stopped', 'smoother-locked')
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
get limit() {
|
|
281
|
+
return Math.max(0, this._scrollHeight - this._height)
|
|
282
|
+
}
|
|
283
|
+
get actualScroll() {
|
|
284
|
+
const w = this.options.wrapper
|
|
285
|
+
return w === window ? scrollY : (w as HTMLElement).scrollTop
|
|
286
|
+
}
|
|
287
|
+
get scroll() {
|
|
288
|
+
return this.animatedScroll
|
|
289
|
+
}
|
|
290
|
+
get progress() {
|
|
291
|
+
return this.limit === 0 ? 1 : this.animatedScroll / this.limit
|
|
292
|
+
}
|
|
293
|
+
get isScrolling() {
|
|
294
|
+
return this._state
|
|
295
|
+
}
|
|
296
|
+
get isSmooth() {
|
|
297
|
+
return this._state === 'smooth'
|
|
298
|
+
}
|
|
299
|
+
get isStopped() {
|
|
300
|
+
return this._stopped
|
|
301
|
+
}
|
|
302
|
+
get isLocked() {
|
|
303
|
+
return this._locked
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/* ---------- input ---------- */
|
|
307
|
+
|
|
308
|
+
private _onWheel = (e: WheelEvent) => {
|
|
309
|
+
const m = e.deltaMode === 1 ? LINE : e.deltaMode === 2 ? innerHeight : 1
|
|
310
|
+
this._input(e.deltaX * m, e.deltaY * m * this.options.wheelMultiplier, e)
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
private _onTouch = (e: TouchEvent) => {
|
|
314
|
+
const t = e.targetTouches[0] ?? e.changedTouches[0]
|
|
315
|
+
if (!t) return
|
|
316
|
+
let dx = 0
|
|
317
|
+
let dy = 0
|
|
318
|
+
if (e.type === 'touchstart') this._lastDelta = 0
|
|
319
|
+
else if (e.type === 'touchmove') {
|
|
320
|
+
dx = -(t.clientX - this._touch.x) * this.options.touchMultiplier
|
|
321
|
+
dy = this._lastDelta = -(t.clientY - this._touch.y) * this.options.touchMultiplier
|
|
322
|
+
} else dy = this._lastDelta // touchend replays the last move, turned into inertia below
|
|
323
|
+
this._touch = { x: t.clientX, y: t.clientY }
|
|
324
|
+
this._input(dx, dy, e)
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** The decision chain every wheel/touch event goes through */
|
|
328
|
+
private _input(dx: number, dy: number, e: WheelEvent | TouchEvent) {
|
|
329
|
+
if (e.ctrlKey) return // trackpad pinch-zoom arrives as ctrl + wheel
|
|
330
|
+
const touch = e.type.startsWith('touch')
|
|
331
|
+
this.isTouching = e.type === 'touchstart' || e.type === 'touchmove'
|
|
332
|
+
|
|
333
|
+
if (dx === 0 && dy === 0) {
|
|
334
|
+
// a tap stops a touch glide, like native iOS
|
|
335
|
+
if (touch && e.type === 'touchstart' && !this._stopped && !this._locked) this._reset()
|
|
336
|
+
return
|
|
337
|
+
}
|
|
338
|
+
if (dy === 0) return // horizontal-only swipe: leave it for browser back/forward
|
|
339
|
+
if (this.limit <= 0) return // nothing to scroll (e.g. an embedded iframe): let it reach the parent
|
|
340
|
+
if (this._prevented(e, dy, touch)) return
|
|
341
|
+
if (this._stopped || this._locked) return void (e.cancelable && e.preventDefault())
|
|
342
|
+
|
|
343
|
+
if (!(touch ? this.options.syncTouch : this.options.smoothWheel)) {
|
|
344
|
+
this._setState('native')
|
|
345
|
+
this._tw.on = false
|
|
346
|
+
return
|
|
347
|
+
}
|
|
348
|
+
if (e.cancelable) e.preventDefault()
|
|
349
|
+
|
|
350
|
+
const end = e.type === 'touchend'
|
|
351
|
+
const delta = end ? Math.sign(dy) * Math.abs(this.velocity) ** this.options.touchInertiaExponent : dy
|
|
352
|
+
|
|
353
|
+
this.scrollTo(this.targetScroll + delta, {
|
|
354
|
+
programmatic: false,
|
|
355
|
+
...(touch
|
|
356
|
+
? { lerp: end ? this.options.syncTouchLerp : 1 }
|
|
357
|
+
: { lerp: this.options.lerp, duration: this.options.duration, easing: this.options.easing }),
|
|
358
|
+
})
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** True when the event should be left to a child: opt-out attributes or a scrollable child */
|
|
362
|
+
private _prevented(e: Event, dy: number, touch: boolean) {
|
|
363
|
+
const path = e.composedPath()
|
|
364
|
+
const end = path.indexOf(this._root)
|
|
365
|
+
for (const n of end < 0 ? path : path.slice(0, end)) {
|
|
366
|
+
if (!(n instanceof HTMLElement)) continue
|
|
367
|
+
if (n.hasAttribute('data-smoother-prevent')) return true
|
|
368
|
+
if (n.hasAttribute(touch ? 'data-smoother-prevent-touch' : 'data-smoother-prevent-wheel')) return true
|
|
369
|
+
if (this.options.nestedScroll && this._canScroll(n, dy)) return true
|
|
370
|
+
}
|
|
371
|
+
return false
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** Can this child scroll further in the wheel's direction? Styles cached for 2 s */
|
|
375
|
+
private _canScroll(n: HTMLElement, dy: number) {
|
|
376
|
+
const now = performance.now()
|
|
377
|
+
let c = this._styleCache.get(n)
|
|
378
|
+
if (!c || now - c.t > 2000) {
|
|
379
|
+
const s = getComputedStyle(n)
|
|
380
|
+
c = { t: now, o: /^(auto|scroll|overlay)$/.test(s.overflowY), c: s.overscrollBehaviorY !== 'auto' }
|
|
381
|
+
this._styleCache.set(n, c)
|
|
382
|
+
}
|
|
383
|
+
if (!c.o) return false
|
|
384
|
+
const max = n.scrollHeight - n.clientHeight
|
|
385
|
+
if (max <= 0) return false
|
|
386
|
+
if (c.c) return true // overscroll-behavior: contain means the page never takes over
|
|
387
|
+
return dy > 0 ? n.scrollTop < max - 1 : n.scrollTop > 0
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** Keyboard, scrollbar drag, native touch, find-in-page: copy the browser's position in */
|
|
391
|
+
private _onNative = () => {
|
|
392
|
+
clearTimeout(this._velTimer)
|
|
393
|
+
// skip only the echo of our own last write; a real scroll in the same frame still syncs
|
|
394
|
+
if (this._skipNative) {
|
|
395
|
+
this._skipNative = false
|
|
396
|
+
if (Math.abs(this.actualScroll - this.animatedScroll) < 1) return
|
|
397
|
+
}
|
|
398
|
+
if (this._state === 'smooth') return // our own scrollTo() writes, ignore them
|
|
399
|
+
|
|
400
|
+
const last = this.animatedScroll
|
|
401
|
+
this.animatedScroll = this.targetScroll = this.actualScroll
|
|
402
|
+
this.velocity = this.animatedScroll - last
|
|
403
|
+
this.direction = Math.sign(this.velocity) as -1 | 0 | 1
|
|
404
|
+
if (!this._stopped) this._setState('native')
|
|
405
|
+
this._emit()
|
|
406
|
+
if (this.velocity !== 0)
|
|
407
|
+
this._velTimer = setTimeout(() => {
|
|
408
|
+
this.velocity = 0
|
|
409
|
+
this._setState(false)
|
|
410
|
+
this._emit()
|
|
411
|
+
}, 400)
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
private _onClick = (e: MouseEvent) => {
|
|
415
|
+
if (e.defaultPrevented || e.button || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return
|
|
416
|
+
const a = e.composedPath().find((n): n is HTMLAnchorElement => n instanceof HTMLAnchorElement && !!n.href)
|
|
417
|
+
if (!a) return
|
|
418
|
+
const url = new URL(a.href)
|
|
419
|
+
if (!url.hash || url.host !== location.host || url.pathname !== location.pathname) return
|
|
420
|
+
e.preventDefault() // stop the browser's instant jump from fighting the animation
|
|
421
|
+
const opts = typeof this.options.anchors === 'object' ? this.options.anchors : {}
|
|
422
|
+
this.scrollTo(decodeURIComponent(url.hash), opts)
|
|
423
|
+
try {
|
|
424
|
+
if (location.hash !== url.hash) history.pushState(null, '', url.hash)
|
|
425
|
+
} catch {}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// middle-click autoscroll is native: hand control back
|
|
429
|
+
private _onPointer = (e: PointerEvent) => {
|
|
430
|
+
if (e.button === 1) this._reset()
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
private _onResize = () => {
|
|
434
|
+
clearTimeout(this._resizeTimer)
|
|
435
|
+
this._resizeTimer = setTimeout(() => this._measure(), 250)
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/* ---------- internals ---------- */
|
|
439
|
+
|
|
440
|
+
private _advance(dt: number) {
|
|
441
|
+
const tw = this._tw
|
|
442
|
+
if (!tw.on) return
|
|
443
|
+
let done = false
|
|
444
|
+
if (tw.dur && tw.ease) {
|
|
445
|
+
tw.t += dt
|
|
446
|
+
const p = clamp(0, tw.t / tw.dur, 1)
|
|
447
|
+
done = p >= 1
|
|
448
|
+
tw.v = tw.from + (tw.to - tw.from) * (done ? 1 : tw.ease(p))
|
|
449
|
+
} else if (tw.lerp) {
|
|
450
|
+
tw.v = damp(tw.v, tw.to, tw.lerp * 60, dt)
|
|
451
|
+
if (Math.round(tw.v) === Math.round(tw.to)) (tw.v = tw.to), (done = true)
|
|
452
|
+
} else (tw.v = tw.to), (done = true)
|
|
453
|
+
if (done) tw.on = false
|
|
454
|
+
tw.cb?.(tw.v, done)
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
private _resolve(t: number | string | Element): number | null {
|
|
458
|
+
if (typeof t === 'number') return t
|
|
459
|
+
if (t === 'top' || t === 'start' || t === '#') return 0
|
|
460
|
+
if (t === 'bottom' || t === 'end') return this.limit
|
|
461
|
+
// getElementById accepts any valid id; querySelector rejects ids like "#2024"
|
|
462
|
+
const n = typeof t === 'string' ? (t[0] === '#' ? document.getElementById(t.slice(1)) : document.querySelector(t)) : t
|
|
463
|
+
if (!n) return t === '#top' ? 0 : null
|
|
464
|
+
const w = this.options.wrapper
|
|
465
|
+
const wrapTop = w === window ? 0 : (w as HTMLElement).getBoundingClientRect().top
|
|
466
|
+
const margin = parseFloat(getComputedStyle(n).scrollMarginTop) || 0
|
|
467
|
+
const padding = parseFloat(getComputedStyle(this._root).scrollPaddingTop) || 0
|
|
468
|
+
// the rect is measured at the browser's real position, so add that (not the animated value)
|
|
469
|
+
return n.getBoundingClientRect().top - wrapTop + this.actualScroll - margin - padding
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
private _set(y: number) {
|
|
473
|
+
// 'instant' ignores any CSS scroll-behavior: smooth on the page
|
|
474
|
+
this.options.wrapper.scrollTo({ top: y, behavior: 'instant' as ScrollBehavior })
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
private _measure() {
|
|
478
|
+
const w = this.options.wrapper
|
|
479
|
+
if (w === window) {
|
|
480
|
+
this._height = innerHeight
|
|
481
|
+
this._scrollHeight = this.options.content.scrollHeight
|
|
482
|
+
} else {
|
|
483
|
+
this._height = (w as HTMLElement).clientHeight
|
|
484
|
+
this._scrollHeight = (w as HTMLElement).scrollHeight
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
private _reset() {
|
|
489
|
+
this._setLocked(false)
|
|
490
|
+
this._setState(false)
|
|
491
|
+
this.animatedScroll = this.targetScroll = this.actualScroll
|
|
492
|
+
this.velocity = 0
|
|
493
|
+
this._tw.on = false
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// one native scroll event follows our final write; don't report it twice
|
|
497
|
+
private _skipNextNative() {
|
|
498
|
+
this._skipNative = true
|
|
499
|
+
requestAnimationFrame(() => (this._skipNative = false))
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
private _emit() {
|
|
503
|
+
this._listeners.forEach((fn) => fn(this))
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
private get _root() {
|
|
507
|
+
const w = this.options.wrapper
|
|
508
|
+
return (w === window ? document.documentElement : w) as HTMLElement
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
private _setState(s: ScrollState) {
|
|
512
|
+
if (this._state !== s) (this._state = s), this._classes()
|
|
513
|
+
}
|
|
514
|
+
private _setStopped(b: boolean) {
|
|
515
|
+
if (this._stopped !== b) (this._stopped = b), this._classes()
|
|
516
|
+
}
|
|
517
|
+
private _setLocked(b: boolean) {
|
|
518
|
+
if (this._locked !== b) (this._locked = b), this._classes()
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
private _classes() {
|
|
522
|
+
const c = this._root.classList
|
|
523
|
+
c.add('smoother')
|
|
524
|
+
c.toggle('smoother-scrolling', !!this._state)
|
|
525
|
+
c.toggle('smoother-smooth', this._state === 'smooth')
|
|
526
|
+
c.toggle('smoother-stopped', this._stopped)
|
|
527
|
+
c.toggle('smoother-locked', this._locked)
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
export default Smoother
|
package/src/react.tsx
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
'use client'
|
|
2
|
+
|
|
3
|
+
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
|
|
4
|
+
import { Smoother, type SmootherOptions } from './index.js'
|
|
5
|
+
|
|
6
|
+
const SmootherContext = createContext<Smoother | null>(null)
|
|
7
|
+
|
|
8
|
+
/** Wrap the app once (app/layout.tsx). Creates one Smoother instance for the window. */
|
|
9
|
+
export function SmootherProvider({ options, children }: { options?: SmootherOptions; children: ReactNode }) {
|
|
10
|
+
const [smoother, setSmoother] = useState<Smoother | null>(null)
|
|
11
|
+
// re-create only when serialisable options change (functions such as easing are not compared)
|
|
12
|
+
const key = JSON.stringify(options ?? {})
|
|
13
|
+
|
|
14
|
+
useEffect(() => {
|
|
15
|
+
const d = new Smoother(options)
|
|
16
|
+
setSmoother(d)
|
|
17
|
+
return () => {
|
|
18
|
+
d.destroy()
|
|
19
|
+
setSmoother(null)
|
|
20
|
+
}
|
|
21
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
22
|
+
}, [key])
|
|
23
|
+
|
|
24
|
+
return <SmootherContext.Provider value={smoother}>{children}</SmootherContext.Provider>
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The live instance (null on the first render). Pass a stable callback to run on every scroll frame. */
|
|
28
|
+
export function useSmoother(onScroll?: (d: Smoother) => void) {
|
|
29
|
+
const smoother = useContext(SmootherContext)
|
|
30
|
+
useEffect(() => {
|
|
31
|
+
if (smoother && onScroll) return smoother.on('scroll', onScroll)
|
|
32
|
+
}, [smoother, onScroll])
|
|
33
|
+
return smoother
|
|
34
|
+
}
|