scroll-direction-manager 2.0.0 → 2.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/README.md CHANGED
@@ -1,52 +1,132 @@
1
1
  # ScrollDirectionManager
2
2
 
3
- The ScrollDirectionManager is a utility package that simplifies tracking the scroll direction (up, down, or initial) of a web page. It provides an easy-to-use class that manages the scroll event listener and calculates the current scroll direction based on the scroll position and an optional initial offset.
3
+ `scroll-direction-manager` is a lightweight, zero-dependency utility package that simplifies tracking the scroll direction (`"up"`, `"down"`, or `"initial"`) of a web page. It ships with both a framework-agnostic `ScrollDirectionManager` class and a dedicated React hook entry point (`scroll-direction-manager/react`).
4
4
 
5
- This package is particularly useful when building responsive user interfaces that need to adapt or perform specific actions based on the user's scroll behavior. For example, you could use it to show or hide a sticky header, control the visibility of scroll-to-top buttons, or trigger animations based on the scroll direction.
5
+ It is particularly useful for responsive navigation bars and sticky headers that hide on scroll down, reappear with a scrolled state on scroll up, and reset when near the top of the page.
6
6
 
7
7
  ## Key Features
8
8
 
9
- - **Scroll Direction Detection**: Accurately determines the current scroll direction (up, down, or initial) based on the scroll position and an optional initial offset.
10
- - **Callback Function**: Allows you to pass a callback function that gets called whenever the scroll direction changes, enabling you to update your UI or perform custom logic accordingly.
11
- - **Customizable Initial Offset**: Allows you to set a custom initial offset value to adjust the sensitivity of the scroll direction detection.
12
- - **Lightweight and Easy to Use**: Designed with a simple and intuitive API, making it easy to integrate into your projects.
9
+ - **React Hook (`useScrollDirection`)**: Exposed via `scroll-direction-manager/react` so vanilla projects stay 100% React-free. Returns `{ direction, isUp, isDown, isInitial }` and automatically manages listener lifecycle.
10
+ - **Scroll Direction Detection**: Accurately determines the current scroll direction (`"up"`, `"down"`, or `"initial"`) based on `window.scrollY` and an optional `initialOffset` threshold.
11
+ - **Callback Support**: Pass an optional `onDirectionChange` callback that fires only when the scroll direction state transitions.
12
+ - **Zero External Runtime Dependencies**: Uses native browser event listeners with SSR safety (`typeof window !== "undefined"`).
13
13
 
14
14
  ## Installation
15
15
 
16
- Install the package via npm:
17
-
18
16
  ```sh
19
17
  npm install scroll-direction-manager
20
18
  ```
21
19
 
22
- ## Usage
20
+ ## React Usage
21
+
22
+ Import the `useScrollDirection` hook from `scroll-direction-manager/react` to declaratively track scroll direction in your React components:
23
23
 
24
- Basic example of use:
24
+ ```tsx
25
+ import { useScrollDirection } from "scroll-direction-manager/react";
26
+
27
+ export function Navbar() {
28
+ const { direction, isUp, isDown, isInitial } = useScrollDirection({
29
+ initialOffset: 120,
30
+ });
31
+
32
+ return (
33
+ <header
34
+ className={[
35
+ "navbar",
36
+ isDown ? "navbar--hidden" : "",
37
+ isUp ? "navbar--scrolled" : "",
38
+ isInitial ? "navbar--top" : "",
39
+ ]
40
+ .filter(Boolean)
41
+ .join(" ")}
42
+ data-scroll-direction={direction}
43
+ >
44
+ <nav>My Navigation</nav>
45
+ </header>
46
+ );
47
+ }
48
+ ```
49
+
50
+ ## Vanilla TypeScript / JavaScript Usage
25
51
 
26
52
  ```typescript
27
- import ScrollDirectionManager from 'scroll-direction-manager';
28
- import type ScrollDirection from 'scroll-direction-manager';
29
-
30
- let element = document.querySelector('[data-element="some-element"]');
31
-
32
- let scrollDirectionInstance = new ScrollDirectionManager({
33
- initialOffset: 145,
34
- onDirectionChange: navOnScroll,
35
- });
36
-
37
- function navOnScroll(direction: ScrollDirection) => {
38
- if (element) {
39
- if (direction === "initial" || direction === "up") {
40
- element.classList.remove("hide");
41
-
42
- if (direction === "up") {
43
- element.classList.add("scrolled");
44
- } else {
45
- element.classList.remove("scrolled");
46
- }
47
- } else {
48
- element.classList.add("hide");
49
- }
53
+ import {
54
+ ScrollDirectionManager,
55
+ type ScrollDirection,
56
+ } from "scroll-direction-manager";
57
+
58
+ const element = document.querySelector('[data-element="some-element"]');
59
+
60
+ const navOnScroll = (direction: ScrollDirection) => {
61
+ if (!element) return;
62
+
63
+ if (direction === "initial" || direction === "up") {
64
+ element.classList.remove("hide");
65
+
66
+ if (direction === "up") {
67
+ element.classList.add("scrolled");
68
+ } else {
69
+ element.classList.remove("scrolled");
50
70
  }
71
+ } else {
72
+ element.classList.add("hide");
73
+ }
51
74
  };
75
+
76
+ const scrollDirectionInstance = new ScrollDirectionManager({
77
+ initialOffset: 145,
78
+ onDirectionChange: navOnScroll,
79
+ });
80
+
81
+ // Clean up when no longer needed:
82
+ // scrollDirectionInstance.dispose();
52
83
  ```
84
+
85
+ ## API Reference
86
+
87
+ ### `useScrollDirection(options?: UseScrollDirectionOptions): UseScrollDirectionResult`
88
+
89
+ Imported from `"scroll-direction-manager/react"`.
90
+
91
+ #### Options (`UseScrollDirectionOptions` / `ScrollDirectionManagerOptions`)
92
+
93
+ | Option | Type | Default | Description |
94
+ | --- | --- | --- | --- |
95
+ | `initialOffset` | `number` | `120` | Scroll threshold in pixels (`window.scrollY`). At or below this offset, direction is always `"initial"`. |
96
+ | `onDirectionChange` | `(direction: ScrollDirection) => void` | `undefined` | Optional callback invoked whenever the scroll direction changes. |
97
+
98
+ #### Return Value (`UseScrollDirectionResult`)
99
+
100
+ | Property | Type | Description |
101
+ | --- | --- | --- |
102
+ | `direction` | `"initial" \| "up" \| "down"` | Current scroll direction state. |
103
+ | `isInitial` | `boolean` | `true` when `direction === "initial"` (at or above `initialOffset`). |
104
+ | `isUp` | `boolean` | `true` when `direction === "up"` (scrolling up below `initialOffset`). |
105
+ | `isDown` | `boolean` | `true` when `direction === "down"` (scrolling down below `initialOffset`). |
106
+
107
+ ### `ScrollDirectionManager`
108
+
109
+ Imported from `"scroll-direction-manager"`.
110
+
111
+ - `new ScrollDirectionManager(options?: ScrollDirectionManagerOptions)`: Starts listening to `window` scroll events.
112
+ - `getDirection(): ScrollDirection`: Returns the current scroll direction (`"initial" | "up" | "down"`).
113
+ - `dispose(): void`: Removes the `window` scroll event listener.
114
+
115
+ ## Notes for AI Agents / LLMs
116
+
117
+ When integrating or modifying `scroll-direction-manager`, keep these rules in mind:
118
+
119
+ 1. **Entry Points & Named Exports**:
120
+ - React: `import { useScrollDirection } from "scroll-direction-manager/react";`
121
+ - Vanilla JS/TS: `import { ScrollDirectionManager, type ScrollDirection } from "scroll-direction-manager";`
122
+ - Keep React imports isolated to the `/react` subpath so non-React consumers do not need `react` installed.
123
+ 2. **State Semantics (`"initial"` vs `"up"` vs `"down"`)**:
124
+ - While `window.scrollY <= initialOffset` (default `120`px), the direction is strictly `"initial"`, even if the user scrolls slightly down or up within that top region.
125
+ - `"down"` and `"up"` are only emitted when `window.scrollY > initialOffset`.
126
+ - For sticky headers/navbars: show the header in its default/transparent style when `isInitial` (`direction === "initial"`), hide it when `isDown` (`direction === "down"`), and show it with an elevated/compact backdrop when `isUp` (`direction === "up"`).
127
+ 3. **SSR & Next.js Compatibility**:
128
+ - `ScrollDirectionManager` guards all `window` access with `typeof window !== "undefined"`, making it safe to import on the server.
129
+ - `scroll-direction-manager/react` includes the `"use client";` directive; in Next.js App Router, add `"use client";` at the top of any component file that calls `useScrollDirection`.
130
+ 4. **Cleanup & Re-renders**:
131
+ - In React, `useScrollDirection` automatically calls `manager.dispose()` on unmount and holds `onDirectionChange` in a ref so inline callbacks do not reset scroll tracking across renders.
132
+ - In Vanilla JS or non-React frameworks, always call `instance.dispose()` during component teardown to prevent memory leaks.
@@ -1,5 +1,5 @@
1
1
  export type ScrollDirection = "initial" | "up" | "down";
2
- type ScrollDirectionManagerOptions = {
2
+ export type ScrollDirectionManagerOptions = {
3
3
  initialOffset?: number;
4
4
  onDirectionChange?: (direction: ScrollDirection) => void;
5
5
  };
@@ -9,9 +9,9 @@ export declare class ScrollDirectionManager {
9
9
  private scrollDirection;
10
10
  private readonly initialOffset;
11
11
  private scrollListener;
12
- constructor({ initialOffset, onDirectionChange, }: ScrollDirectionManagerOptions);
12
+ constructor({ initialOffset, onDirectionChange, }?: ScrollDirectionManagerOptions);
13
13
  private readonly setupSubscriptions;
14
14
  private readonly handleScrollDirection;
15
+ getDirection(): ScrollDirection;
15
16
  dispose(): void;
16
17
  }
17
- export {};
@@ -3,19 +3,23 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ScrollDirectionManager = void 0;
4
4
  var ScrollDirectionManager = /** @class */ (function () {
5
5
  function ScrollDirectionManager(_a) {
6
- var initialOffset = _a.initialOffset, onDirectionChange = _a.onDirectionChange;
6
+ var _b = _a === void 0 ? {} : _a, initialOffset = _b.initialOffset, onDirectionChange = _b.onDirectionChange;
7
7
  var _this = this;
8
8
  this.onDirectionChange = undefined;
9
9
  this.scrollDirection = "initial";
10
10
  this.initialOffset = 120;
11
11
  this.scrollListener = null;
12
12
  this.setupSubscriptions = function () {
13
+ if (typeof window === "undefined")
14
+ return;
13
15
  // Setting up the scroll event listener
14
16
  _this.scrollListener = _this.handleScrollDirection.bind(_this);
15
17
  window.addEventListener("scroll", _this.scrollListener);
16
18
  };
17
19
  this.handleScrollDirection = function () {
18
20
  var _a;
21
+ if (typeof window === "undefined")
22
+ return;
19
23
  var position = window.scrollY;
20
24
  var direction = "initial";
21
25
  if (position > _this.initialOffset) {
@@ -33,14 +37,17 @@ var ScrollDirectionManager = /** @class */ (function () {
33
37
  _this.scrollDirection = direction;
34
38
  };
35
39
  this.scrollPosition = 0;
36
- if (initialOffset)
40
+ if (initialOffset !== undefined)
37
41
  this.initialOffset = initialOffset;
38
42
  this.onDirectionChange = onDirectionChange;
39
43
  this.setupSubscriptions();
40
44
  }
45
+ ScrollDirectionManager.prototype.getDirection = function () {
46
+ return this.scrollDirection;
47
+ };
41
48
  ScrollDirectionManager.prototype.dispose = function () {
42
49
  // Remove the event listener when disposing
43
- if (this.scrollListener) {
50
+ if (typeof window !== "undefined" && this.scrollListener) {
44
51
  window.removeEventListener("scroll", this.scrollListener);
45
52
  this.scrollListener = null;
46
53
  }
@@ -1,2 +1,2 @@
1
1
  export { ScrollDirectionManager } from "./ScrollDirectionManager";
2
- export type { ScrollDirection } from "./ScrollDirectionManager";
2
+ export type { ScrollDirection, ScrollDirectionManagerOptions, } from "./ScrollDirectionManager";
@@ -0,0 +1,3 @@
1
+ export { useScrollDirection } from "./useScrollDirection";
2
+ export type { UseScrollDirectionOptions, UseScrollDirectionResult, } from "./useScrollDirection";
3
+ export type { ScrollDirection, ScrollDirectionManagerOptions, } from "./ScrollDirectionManager";
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ "use client";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.useScrollDirection = void 0;
5
+ var useScrollDirection_1 = require("./useScrollDirection");
6
+ Object.defineProperty(exports, "useScrollDirection", { enumerable: true, get: function () { return useScrollDirection_1.useScrollDirection; } });
@@ -0,0 +1,17 @@
1
+ import { ScrollDirection, ScrollDirectionManagerOptions } from "./ScrollDirectionManager";
2
+ export type UseScrollDirectionOptions = ScrollDirectionManagerOptions;
3
+ export type UseScrollDirectionResult = {
4
+ direction: ScrollDirection;
5
+ isUp: boolean;
6
+ isDown: boolean;
7
+ isInitial: boolean;
8
+ };
9
+ /**
10
+ * React hook for tracking window scroll direction.
11
+ *
12
+ * @example
13
+ * const { direction, isUp, isDown, isInitial } = useScrollDirection({
14
+ * initialOffset: 120,
15
+ * });
16
+ */
17
+ export declare function useScrollDirection(options?: UseScrollDirectionOptions): UseScrollDirectionResult;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ "use client";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.useScrollDirection = void 0;
5
+ var react_1 = require("react");
6
+ var ScrollDirectionManager_1 = require("./ScrollDirectionManager");
7
+ /**
8
+ * React hook for tracking window scroll direction.
9
+ *
10
+ * @example
11
+ * const { direction, isUp, isDown, isInitial } = useScrollDirection({
12
+ * initialOffset: 120,
13
+ * });
14
+ */
15
+ function useScrollDirection(options) {
16
+ if (options === void 0) { options = {}; }
17
+ var initialOffset = options.initialOffset, onDirectionChange = options.onDirectionChange;
18
+ var _a = (0, react_1.useState)("initial"), direction = _a[0], setDirection = _a[1];
19
+ var onDirectionChangeRef = (0, react_1.useRef)(onDirectionChange);
20
+ (0, react_1.useEffect)(function () {
21
+ onDirectionChangeRef.current = onDirectionChange;
22
+ }, [onDirectionChange]);
23
+ (0, react_1.useEffect)(function () {
24
+ var manager = new ScrollDirectionManager_1.ScrollDirectionManager({
25
+ initialOffset: initialOffset,
26
+ onDirectionChange: function (newDirection) {
27
+ var _a;
28
+ setDirection(newDirection);
29
+ (_a = onDirectionChangeRef.current) === null || _a === void 0 ? void 0 : _a.call(onDirectionChangeRef, newDirection);
30
+ },
31
+ });
32
+ setDirection(manager.getDirection());
33
+ return function () {
34
+ manager.dispose();
35
+ };
36
+ }, [initialOffset]);
37
+ return {
38
+ direction: direction,
39
+ isUp: direction === "up",
40
+ isDown: direction === "down",
41
+ isInitial: direction === "initial",
42
+ };
43
+ }
44
+ exports.useScrollDirection = useScrollDirection;
package/package.json CHANGED
@@ -1,11 +1,31 @@
1
1
  {
2
2
  "name": "scroll-direction-manager",
3
- "version": "2.0.0",
4
- "description": "A utility package that simplifies tracking the scroll direction (up, down, or initial) of a web page",
3
+ "version": "2.1.0",
4
+ "description": "A utility package that simplifies tracking the scroll direction (up, down, or initial) of a web page, with React hook support",
5
5
  "main": "dist/cjs/index.js",
6
6
  "types": "dist/cjs/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/cjs/index.d.ts",
10
+ "default": "./dist/cjs/index.js"
11
+ },
12
+ "./react": {
13
+ "types": "./dist/cjs/react.d.ts",
14
+ "default": "./dist/cjs/react.js"
15
+ }
16
+ },
17
+ "typesVersions": {
18
+ "*": {
19
+ "react": [
20
+ "dist/cjs/react.d.ts"
21
+ ]
22
+ }
23
+ },
24
+ "files": [
25
+ "dist"
26
+ ],
7
27
  "scripts": {
8
- "clean": "rm -rf dist/esm",
28
+ "clean": "rm -rf dist",
9
29
  "build:cjs": "tsc --project tsconfig.json",
10
30
  "build": "npm run build:cjs",
11
31
  "test": "jest",
@@ -18,7 +38,10 @@
18
38
  },
19
39
  "keywords": [
20
40
  "scroll",
21
- "scroll-direction"
41
+ "scroll-direction",
42
+ "react",
43
+ "react-hooks",
44
+ "use-scroll-direction"
22
45
  ],
23
46
  "author": "Martin Sazzaroli",
24
47
  "license": "MIT",
@@ -26,11 +49,23 @@
26
49
  "url": "https://github.com/masaroli/scroll-direction-manager/issues"
27
50
  },
28
51
  "homepage": "https://github.com/masaroli/scroll-direction-manager#readme",
52
+ "peerDependencies": {
53
+ "react": ">=16.8.0"
54
+ },
55
+ "peerDependenciesMeta": {
56
+ "react": {
57
+ "optional": true
58
+ }
59
+ },
29
60
  "devDependencies": {
61
+ "@testing-library/react": "^16.3.2",
30
62
  "@types/jest": "^29.5.12",
63
+ "@types/react": "^19.0.0",
31
64
  "jest": "^29.7.0",
32
65
  "jest-environment-jsdom": "^29.7.0",
33
66
  "jsdom": "^24.0.0",
67
+ "react": "^19.0.0",
68
+ "react-dom": "^19.0.0",
34
69
  "ts-jest": "^29.1.3",
35
70
  "typescript": "^5.4.5"
36
71
  },
package/jest.config.js DELETED
@@ -1,8 +0,0 @@
1
- module.exports = {
2
- preset: "ts-jest",
3
- testEnvironment: "jest-environment-jsdom", // <-- Change this line
4
- testMatch: ["**/__tests__/**/*.ts?(x)", "**/?(*.)+(spec|test).ts?(x)"],
5
- collectCoverageFrom: ["src/**/*.{js,ts}"],
6
- coverageDirectory: "coverage",
7
- coverageReporters: ["text", "lcov"],
8
- };
@@ -1,60 +0,0 @@
1
- export type ScrollDirection = "initial" | "up" | "down";
2
-
3
- type ScrollDirectionManagerOptions = {
4
- initialOffset?: number;
5
- onDirectionChange?: (direction: ScrollDirection) => void;
6
- };
7
-
8
- export class ScrollDirectionManager {
9
- private readonly onDirectionChange: ScrollDirectionManagerOptions["onDirectionChange"] =
10
- undefined;
11
- private scrollPosition: number;
12
- private scrollDirection: ScrollDirection = "initial";
13
- private readonly initialOffset: number = 120;
14
-
15
- private scrollListener: EventListener | null = null;
16
-
17
- public constructor({
18
- initialOffset,
19
- onDirectionChange,
20
- }: ScrollDirectionManagerOptions) {
21
- this.scrollPosition = 0;
22
- if (initialOffset) this.initialOffset = initialOffset;
23
- this.onDirectionChange = onDirectionChange;
24
- this.setupSubscriptions();
25
- }
26
-
27
- private readonly setupSubscriptions = (): void => {
28
- // Setting up the scroll event listener
29
- this.scrollListener = this.handleScrollDirection.bind(this);
30
- window.addEventListener("scroll", this.scrollListener);
31
- };
32
-
33
- private readonly handleScrollDirection = (): void => {
34
- const position = window.scrollY;
35
- let direction: ScrollDirection = "initial";
36
-
37
- if (position > this.initialOffset) {
38
- if (position < this.scrollPosition) {
39
- direction = "up";
40
- } else {
41
- direction = "down";
42
- }
43
- }
44
-
45
- if (direction !== this.scrollDirection) {
46
- this.onDirectionChange?.(direction);
47
- }
48
-
49
- this.scrollPosition = position;
50
- this.scrollDirection = direction;
51
- };
52
-
53
- public dispose(): void {
54
- // Remove the event listener when disposing
55
- if (this.scrollListener) {
56
- window.removeEventListener("scroll", this.scrollListener);
57
- this.scrollListener = null;
58
- }
59
- }
60
- }
@@ -1,49 +0,0 @@
1
- import { ScrollDirectionManager } from "../ScrollDirectionManager";
2
-
3
- describe("ScrollDirectionManager", () => {
4
- let manager: ScrollDirectionManager;
5
- const scrollEvents: number[] = [0, 200, 100, 300];
6
- let onDirectionChangeMock: jest.Mock;
7
-
8
- beforeEach(() => {
9
- jest.resetModules();
10
- Object.defineProperty(global, "window", {
11
- value: {
12
- addEventListener: jest.fn(),
13
- scrollY: 0,
14
- },
15
- writable: true,
16
- });
17
-
18
- onDirectionChangeMock = jest.fn();
19
- manager = new ScrollDirectionManager({
20
- onDirectionChange: onDirectionChangeMock,
21
- initialOffset: 10,
22
- });
23
- });
24
-
25
- test("should initialize with the correct initial offset", () => {
26
- expect(manager["initialOffset"]).toBe(10);
27
- });
28
-
29
- test("should call onDirectionChange when scroll direction changes", () => {
30
- scrollEvents.forEach((scrollY, index) => {
31
- Object.defineProperty(global.window, "scrollY", {
32
- value: scrollY,
33
- writable: true,
34
- });
35
-
36
- manager["handleScrollDirection"]();
37
-
38
- if (index === 0) {
39
- expect(onDirectionChangeMock).not.toHaveBeenCalled();
40
- } else if (scrollY > scrollEvents[index - 1]) {
41
- expect(onDirectionChangeMock).toHaveBeenCalledWith("down");
42
- } else {
43
- expect(onDirectionChangeMock).toHaveBeenCalledWith("up");
44
- }
45
-
46
- onDirectionChangeMock.mockClear();
47
- });
48
- });
49
- });
package/src/index.ts DELETED
@@ -1,2 +0,0 @@
1
- export { ScrollDirectionManager } from "./ScrollDirectionManager";
2
- export type { ScrollDirection } from "./ScrollDirectionManager";
package/tsconfig.json DELETED
@@ -1,13 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES5",
4
- "module": "CommonJS",
5
- "declaration": true,
6
- "outDir": "./dist/cjs",
7
- "strict": true,
8
- "esModuleInterop": true,
9
- "skipLibCheck": true
10
- },
11
- "include": ["src/**/*"],
12
- "exclude": ["node_modules", "**/__tests__/*"]
13
- }