use-go-back 1.0.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 +98 -0
- package/dist/index-BDs7GAQ6.d.ts +41 -0
- package/dist/index.d.ts +41 -0
- package/dist/index.js +60 -0
- package/dist/index.js.map +1 -0
- package/package.json +60 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Forge 42
|
|
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
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# use-go-back
|
|
2
|
+
|
|
3
|
+
A React hook that navigates back to a specific route in browser history using the Navigation API, preserving scroll position.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- 🎯 Navigate back to a specific pathname in history
|
|
8
|
+
- 📜 Preserves scroll position automatically (thanks to Navigation API)
|
|
9
|
+
- 🔍 Flexible pathname matching (exact string or custom function)
|
|
10
|
+
- 🔄 Graceful fallback when Navigation API is not available
|
|
11
|
+
- 📦 Zero dependencies (only React as peer dependency)
|
|
12
|
+
- 🎨 TypeScript support
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install use-go-back
|
|
18
|
+
# or
|
|
19
|
+
pnpm add use-go-back
|
|
20
|
+
# or
|
|
21
|
+
yarn add use-go-back
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Usage
|
|
25
|
+
|
|
26
|
+
### Basic Example
|
|
27
|
+
|
|
28
|
+
```tsx
|
|
29
|
+
import { useGoBack } from "use-go-back";
|
|
30
|
+
|
|
31
|
+
function MyComponent() {
|
|
32
|
+
const goBack = useGoBack({ targetPathname: "/" });
|
|
33
|
+
|
|
34
|
+
return <button onClick={goBack}>Go to Home</button>;
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### With Custom Pathname Matcher
|
|
39
|
+
|
|
40
|
+
```tsx
|
|
41
|
+
import { useGoBack } from "use-go-back";
|
|
42
|
+
|
|
43
|
+
function SearchLayout() {
|
|
44
|
+
// Go back to any search-related page
|
|
45
|
+
const goBack = useGoBack({
|
|
46
|
+
targetPathname: (pathname) => pathname.startsWith("/search"),
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
return <button onClick={goBack}>Back to Search</button>;
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
### With Fallback URL
|
|
54
|
+
|
|
55
|
+
```tsx
|
|
56
|
+
import { useGoBack } from "use-go-back";
|
|
57
|
+
|
|
58
|
+
function MyComponent() {
|
|
59
|
+
const goBack = useGoBack({
|
|
60
|
+
targetPathname: "/dashboard",
|
|
61
|
+
fallbackUrl: "/dashboard", // Used if Navigation API is unavailable
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
return <button onClick={goBack}>Back to Dashboard</button>;
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## API
|
|
69
|
+
|
|
70
|
+
### `useGoBack(options?)`
|
|
71
|
+
|
|
72
|
+
Returns a function that navigates back to the target route.
|
|
73
|
+
|
|
74
|
+
#### Options
|
|
75
|
+
|
|
76
|
+
| Option | Type | Default | Description |
|
|
77
|
+
|--------|------|---------|-------------|
|
|
78
|
+
| `targetPathname` | `string \| ((pathname: string) => boolean)` | `"/"` | The target pathname to go back to. Can be an exact string match or a custom matcher function. |
|
|
79
|
+
| `fallbackUrl` | `string` | `undefined` | Fallback URL to navigate to if Navigation API is not available and no matching history entry is found. |
|
|
80
|
+
|
|
81
|
+
#### Returns
|
|
82
|
+
|
|
83
|
+
A function `() => void` that navigates back to the target route when called.
|
|
84
|
+
|
|
85
|
+
## How It Works
|
|
86
|
+
|
|
87
|
+
1. **Navigation API**: The hook uses the [Navigation API](https://developer.mozilla.org/en-US/docs/Web/API/Navigation_API) to access browser history entries.
|
|
88
|
+
2. **History Search**: It searches backwards through history to find the closest entry matching your target pathname.
|
|
89
|
+
3. **Scroll Preservation**: When using `window.history.go()`, the browser automatically restores the scroll position, which is perfect for nested routes.
|
|
90
|
+
4. **Fallback**: If the Navigation API is not available or no matching entry is found, it falls back to the provided `fallbackUrl` or uses `history.back()`.
|
|
91
|
+
|
|
92
|
+
## Browser Support
|
|
93
|
+
|
|
94
|
+
The hook works in all modern browsers. For browsers that don't support the Navigation API, it gracefully falls back to using `window.location.href` or `history.back()`.
|
|
95
|
+
|
|
96
|
+
## License
|
|
97
|
+
|
|
98
|
+
MIT
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
//#region src/index.d.ts
|
|
2
|
+
type PathnameMatcher = string | ((pathname: string) => boolean);
|
|
3
|
+
interface UseGoBackOptions {
|
|
4
|
+
/**
|
|
5
|
+
* The target pathname to go back to. Can be:
|
|
6
|
+
* - A string: exact pathname match (e.g., "/")
|
|
7
|
+
* - A function: custom matcher function (e.g., (pathname) => pathname === "/" || pathname.startsWith("/search"))
|
|
8
|
+
* @default "/"
|
|
9
|
+
*/
|
|
10
|
+
targetPathname?: PathnameMatcher;
|
|
11
|
+
/**
|
|
12
|
+
* Fallback URL to navigate to if Navigation API is not available and no matching history entry is found
|
|
13
|
+
*/
|
|
14
|
+
fallbackUrl?: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Hook that provides a function to navigate back to a specific route in browser history.
|
|
18
|
+
* Uses the Navigation API to find the closest matching history entry and navigates back to it,
|
|
19
|
+
* which automatically restores scroll position.
|
|
20
|
+
*
|
|
21
|
+
* @param options - Configuration options
|
|
22
|
+
* @returns A function that navigates back to the target route
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```tsx
|
|
26
|
+
* // Go back to the index page
|
|
27
|
+
* const goBack = useGoBack({ targetPathname: "/" });
|
|
28
|
+
*
|
|
29
|
+
* // Go back to any search-related page
|
|
30
|
+
* const goBack = useGoBack({
|
|
31
|
+
* targetPathname: (pathname) => pathname.startsWith("/search")
|
|
32
|
+
* });
|
|
33
|
+
*
|
|
34
|
+
* // Use with a button
|
|
35
|
+
* <Button onClick={goBack}>Back</Button>
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
declare function useGoBack(options?: UseGoBackOptions): () => void;
|
|
39
|
+
//#endregion
|
|
40
|
+
export { useGoBack };
|
|
41
|
+
//# sourceMappingURL=index-BDs7GAQ6.d.ts.map
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
//#region src/index.d.ts
|
|
2
|
+
type PathnameMatcher = string | ((pathname: string) => boolean);
|
|
3
|
+
interface UseGoBackOptions {
|
|
4
|
+
/**
|
|
5
|
+
* The target pathname to go back to. Can be:
|
|
6
|
+
* - A string: exact pathname match (e.g., "/")
|
|
7
|
+
* - A function: custom matcher function (e.g., (pathname) => pathname === "/" || pathname.startsWith("/search"))
|
|
8
|
+
* @default "/"
|
|
9
|
+
*/
|
|
10
|
+
targetPathname?: PathnameMatcher;
|
|
11
|
+
/**
|
|
12
|
+
* Fallback URL to navigate to if Navigation API is not available and no matching history entry is found
|
|
13
|
+
*/
|
|
14
|
+
fallbackUrl?: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Hook that provides a function to navigate back to a specific route in browser history.
|
|
18
|
+
* Uses the Navigation API to find the closest matching history entry and navigates back to it,
|
|
19
|
+
* which automatically restores scroll position.
|
|
20
|
+
*
|
|
21
|
+
* @param options - Configuration options
|
|
22
|
+
* @returns A function that navigates back to the target route
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```tsx
|
|
26
|
+
* // Go back to the index page
|
|
27
|
+
* const goBack = useGoBack({ targetPathname: "/" });
|
|
28
|
+
*
|
|
29
|
+
* // Go back to any search-related page
|
|
30
|
+
* const goBack = useGoBack({
|
|
31
|
+
* targetPathname: (pathname) => pathname.startsWith("/search")
|
|
32
|
+
* });
|
|
33
|
+
*
|
|
34
|
+
* // Use with a button
|
|
35
|
+
* <Button onClick={goBack}>Back</Button>
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
declare function useGoBack(options?: UseGoBackOptions): () => void;
|
|
39
|
+
//#endregion
|
|
40
|
+
export { useGoBack };
|
|
41
|
+
//# sourceMappingURL=index-BDs7GAQ6.d.ts.map
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { useCallback } from "react";
|
|
2
|
+
|
|
3
|
+
//#region src/index.ts
|
|
4
|
+
/**
|
|
5
|
+
* Hook that provides a function to navigate back to a specific route in browser history.
|
|
6
|
+
* Uses the Navigation API to find the closest matching history entry and navigates back to it,
|
|
7
|
+
* which automatically restores scroll position.
|
|
8
|
+
*
|
|
9
|
+
* @param options - Configuration options
|
|
10
|
+
* @returns A function that navigates back to the target route
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```tsx
|
|
14
|
+
* // Go back to the index page
|
|
15
|
+
* const goBack = useGoBack({ targetPathname: "/" });
|
|
16
|
+
*
|
|
17
|
+
* // Go back to any search-related page
|
|
18
|
+
* const goBack = useGoBack({
|
|
19
|
+
* targetPathname: (pathname) => pathname.startsWith("/search")
|
|
20
|
+
* });
|
|
21
|
+
*
|
|
22
|
+
* // Use with a button
|
|
23
|
+
* <Button onClick={goBack}>Back</Button>
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
function useGoBack(options = {}) {
|
|
27
|
+
const { targetPathname = "/", fallbackUrl } = options;
|
|
28
|
+
const matchesPathname = useCallback((pathname) => {
|
|
29
|
+
if (typeof targetPathname === "string") return pathname === targetPathname;
|
|
30
|
+
return targetPathname(pathname);
|
|
31
|
+
}, [targetPathname]);
|
|
32
|
+
return useCallback(() => {
|
|
33
|
+
const nav = window.navigation;
|
|
34
|
+
if (nav && typeof nav === "object" && "currentEntry" in nav) {
|
|
35
|
+
const currentIndex = nav.currentEntry?.index ?? -1;
|
|
36
|
+
const entries = nav.entries();
|
|
37
|
+
for (let i = currentIndex - 1; i >= 0; i--) {
|
|
38
|
+
const entry = entries[i];
|
|
39
|
+
if (entry) {
|
|
40
|
+
if (matchesPathname(new URL(entry.url).pathname)) {
|
|
41
|
+
const stepsBack = currentIndex - i;
|
|
42
|
+
window.history.go(-stepsBack);
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const finalFallback = fallbackUrl ?? (typeof targetPathname === "string" ? targetPathname : void 0);
|
|
49
|
+
if (finalFallback) window.location.href = finalFallback;
|
|
50
|
+
else window.history.back();
|
|
51
|
+
}, [
|
|
52
|
+
matchesPathname,
|
|
53
|
+
fallbackUrl,
|
|
54
|
+
targetPathname
|
|
55
|
+
]);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
//#endregion
|
|
59
|
+
export { useGoBack };
|
|
60
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { useCallback } from \"react\"\n\ntype PathnameMatcher = string | ((pathname: string) => boolean)\n\ninterface UseGoBackOptions {\n\t/**\n\t * The target pathname to go back to. Can be:\n\t * - A string: exact pathname match (e.g., \"/\")\n\t * - A function: custom matcher function (e.g., (pathname) => pathname === \"/\" || pathname.startsWith(\"/search\"))\n\t * @default \"/\"\n\t */\n\ttargetPathname?: PathnameMatcher\n\t/**\n\t * Fallback URL to navigate to if Navigation API is not available and no matching history entry is found\n\t */\n\tfallbackUrl?: string\n}\n\n/**\n * Hook that provides a function to navigate back to a specific route in browser history.\n * Uses the Navigation API to find the closest matching history entry and navigates back to it,\n * which automatically restores scroll position.\n *\n * @param options - Configuration options\n * @returns A function that navigates back to the target route\n *\n * @example\n * ```tsx\n * // Go back to the index page\n * const goBack = useGoBack({ targetPathname: \"/\" });\n *\n * // Go back to any search-related page\n * const goBack = useGoBack({\n * targetPathname: (pathname) => pathname.startsWith(\"/search\")\n * });\n *\n * // Use with a button\n * <Button onClick={goBack}>Back</Button>\n * ```\n */\nexport function useGoBack(options: UseGoBackOptions = {}) {\n\tconst { targetPathname = \"/\", fallbackUrl } = options\n\n\tconst matchesPathname = useCallback(\n\t\t(pathname: string): boolean => {\n\t\t\tif (typeof targetPathname === \"string\") {\n\t\t\t\treturn pathname === targetPathname\n\t\t\t}\n\t\t\treturn targetPathname(pathname)\n\t\t},\n\t\t[targetPathname]\n\t)\n\n\tconst goBack = useCallback(() => {\n\t\t// Check if Navigation API is available\n\t\t// @ts-expect-error - Navigation API is not yet in all TypeScript definitions\n\t\tconst nav = window.navigation\n\t\tif (nav && typeof nav === \"object\" && \"currentEntry\" in nav) {\n\t\t\tconst currentIndex = nav.currentEntry?.index ?? -1\n\t\t\tconst entries = nav.entries()\n\n\t\t\t// Look backwards through history to find the closest matching entry\n\t\t\tfor (let i = currentIndex - 1; i >= 0; i--) {\n\t\t\t\tconst entry = entries[i]\n\t\t\t\tif (entry) {\n\t\t\t\t\tconst url = new URL(entry.url)\n\t\t\t\t\t// Check if this entry matches the target pathname\n\t\t\t\t\tif (matchesPathname(url.pathname)) {\n\t\t\t\t\t\t// Calculate how many steps back we need to go\n\t\t\t\t\t\tconst stepsBack = currentIndex - i\n\t\t\t\t\t\t// Use browser navigation to go back, which restores scroll position\n\t\t\t\t\t\twindow.history.go(-stepsBack)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Fallback: if Navigation API is not available or no matching entry found\n\t\t// Use fallbackUrl if provided, otherwise use targetPathname if it's a string, otherwise use history.back()\n\t\tconst finalFallback = fallbackUrl ?? (typeof targetPathname === \"string\" ? targetPathname : undefined)\n\t\tif (finalFallback) {\n\t\t\twindow.location.href = finalFallback\n\t\t} else {\n\t\t\twindow.history.back()\n\t\t}\n\t}, [matchesPathname, fallbackUrl, targetPathname])\n\n\treturn goBack\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAgB,UAAU,UAA4B,EAAE,EAAE;CACzD,MAAM,EAAE,iBAAiB,KAAK,gBAAgB;CAE9C,MAAM,kBAAkB,aACtB,aAA8B;AAC9B,MAAI,OAAO,mBAAmB,SAC7B,QAAO,aAAa;AAErB,SAAO,eAAe,SAAS;IAEhC,CAAC,eAAe,CAChB;AAqCD,QAnCe,kBAAkB;EAGhC,MAAM,MAAM,OAAO;AACnB,MAAI,OAAO,OAAO,QAAQ,YAAY,kBAAkB,KAAK;GAC5D,MAAM,eAAe,IAAI,cAAc,SAAS;GAChD,MAAM,UAAU,IAAI,SAAS;AAG7B,QAAK,IAAI,IAAI,eAAe,GAAG,KAAK,GAAG,KAAK;IAC3C,MAAM,QAAQ,QAAQ;AACtB,QAAI,OAGH;SAAI,gBAFQ,IAAI,IAAI,MAAM,IAAI,CAEN,SAAS,EAAE;MAElC,MAAM,YAAY,eAAe;AAEjC,aAAO,QAAQ,GAAG,CAAC,UAAU;AAC7B;;;;;EAQJ,MAAM,gBAAgB,gBAAgB,OAAO,mBAAmB,WAAW,iBAAiB;AAC5F,MAAI,cACH,QAAO,SAAS,OAAO;MAEvB,QAAO,QAAQ,MAAM;IAEpB;EAAC;EAAiB;EAAa;EAAe,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "use-go-back",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "A React hook that navigates back to a specific route in browser history using the Navigation API, preserving scroll position",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
"./package.json": "./package.json",
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"import": "./dist/index.js",
|
|
14
|
+
"default": "./dist/index.js"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"author": "",
|
|
18
|
+
"license": "MIT",
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://github.com/gijsroge/use-go-back.git"
|
|
22
|
+
},
|
|
23
|
+
"bugs": {
|
|
24
|
+
"url": "https://github.com/gijsroge/use-go-back/issues"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"dist"
|
|
28
|
+
],
|
|
29
|
+
"homepage": "https://github.com/gijsroge/use-go-back#readme",
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"react": ">=16.8.0"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@arethetypeswrong/cli": "^0.17.4",
|
|
38
|
+
"@changesets/cli": "^2.29.0",
|
|
39
|
+
"@testing-library/react": "^16.1.0",
|
|
40
|
+
"@types/node": "22.14.1",
|
|
41
|
+
"@types/react": "^18.3.0",
|
|
42
|
+
"@types/react-dom": "^18.3.0",
|
|
43
|
+
"@vitest/coverage-v8": "^3.1.1",
|
|
44
|
+
"happy-dom": "^17.4.4",
|
|
45
|
+
"react": "^18.3.0",
|
|
46
|
+
"react-dom": "^18.3.0",
|
|
47
|
+
"tsdown": "^0.15.6",
|
|
48
|
+
"typescript": "^5.8.3",
|
|
49
|
+
"vitest": "^3.1.1"
|
|
50
|
+
},
|
|
51
|
+
"scripts": {
|
|
52
|
+
"build": "tsdown src/index.ts && pnpm run build:fix-types",
|
|
53
|
+
"build:fix-types": "node -e \"const fs=require('fs');const files=fs.readdirSync('dist');const dts=files.find(f=>f.endsWith('.d.ts')&&f.startsWith('index-'));if(dts)fs.copyFileSync('dist/'+dts,'dist/index.d.ts');\"",
|
|
54
|
+
"test:unit": "vitest run --passWithNoTests",
|
|
55
|
+
"test:cov": "vitest run --coverage",
|
|
56
|
+
"test:types": "tsc",
|
|
57
|
+
"test:publint": "publint --strict",
|
|
58
|
+
"test:exports": "attw --pack ."
|
|
59
|
+
}
|
|
60
|
+
}
|