@modastar/z-router 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Lanstar
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
File without changes
package/dist/index.cjs ADDED
@@ -0,0 +1,185 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ DefaultTransitionDuration: () => DefaultTransitionDuration,
24
+ LocationContext: () => LocationContext,
25
+ RouteContext: () => RouteContext,
26
+ RouterContext: () => RouterContext,
27
+ createRouter: () => createRouter,
28
+ matchRoute: () => matchRoute,
29
+ matchUrl: () => matchUrl,
30
+ parseLocationFromHref: () => parseLocationFromHref,
31
+ redirect: () => redirect,
32
+ useLocation: () => useLocation,
33
+ useMatches: () => useMatches,
34
+ useRoute: () => useRoute,
35
+ useRouter: () => useRouter
36
+ });
37
+ module.exports = __toCommonJS(index_exports);
38
+
39
+ // src/utils.ts
40
+ var DefaultTransitionDuration = 300;
41
+ var redirect = (options) => {
42
+ return new Error("", { cause: options });
43
+ };
44
+ var matchUrl = (pattern, url) => {
45
+ try {
46
+ let pathname, searchParams;
47
+ if (url.startsWith("http://") || url.startsWith("https://")) {
48
+ const urlObj = new URL(url);
49
+ pathname = urlObj.pathname;
50
+ searchParams = urlObj.searchParams;
51
+ } else {
52
+ const [path, queryString] = url.split("?");
53
+ if (!path) {
54
+ return null;
55
+ }
56
+ pathname = path;
57
+ searchParams = new URLSearchParams(queryString || "");
58
+ }
59
+ const cleanPath = pathname.replaceAll(/^\/|\/$/g, "");
60
+ const cleanPattern = pattern.replaceAll(/^\/|\/$/g, "");
61
+ const pathSegments = cleanPath.split("/");
62
+ const patternSegments = cleanPattern.split("/");
63
+ if (pathSegments.length !== patternSegments.length) {
64
+ return null;
65
+ }
66
+ const params = {};
67
+ for (let i = 0; i < patternSegments.length; i++) {
68
+ const patternSegment = patternSegments[i];
69
+ const pathSegment = pathSegments[i];
70
+ if (patternSegment.startsWith(":")) {
71
+ const paramName = patternSegment.slice(1);
72
+ params[paramName] = decodeURIComponent(pathSegment);
73
+ } else if (patternSegment !== pathSegment) {
74
+ return null;
75
+ }
76
+ }
77
+ const query = Object.fromEntries(searchParams.entries());
78
+ return { params, query };
79
+ } catch {
80
+ return null;
81
+ }
82
+ };
83
+ var matchRoute = (rootRoute, url) => {
84
+ const _matchRoute = (matches, route) => {
85
+ if (route.children) {
86
+ for (const childRoute of route.children) {
87
+ const matchesResult = _matchRoute([...matches, childRoute], childRoute);
88
+ if (matchesResult) {
89
+ return matchesResult;
90
+ }
91
+ }
92
+ return null;
93
+ }
94
+ let pattern = "";
95
+ for (const match of matches) {
96
+ if (match.pathname === void 0) continue;
97
+ pattern += `/${match.pathname}`;
98
+ }
99
+ const result = matchUrl(pattern, url);
100
+ if (result) {
101
+ return { matches, ...result };
102
+ }
103
+ return null;
104
+ };
105
+ return _matchRoute([], rootRoute);
106
+ };
107
+ var parseLocationFromHref = (rootRoute, to) => {
108
+ const result = matchRoute(rootRoute, to);
109
+ if (!result) return null;
110
+ return {
111
+ pathname: to,
112
+ params: result.params,
113
+ query: result.query
114
+ };
115
+ };
116
+ var createRouter = (options) => {
117
+ return options;
118
+ };
119
+
120
+ // src/context/locationContext.ts
121
+ var import_react = require("react");
122
+ var LocationContext = (0, import_react.createContext)(null);
123
+
124
+ // src/context/routeContext.ts
125
+ var import_react2 = require("react");
126
+ var RouteContext = (0, import_react2.createContext)(null);
127
+
128
+ // src/context/routerContext.ts
129
+ var import_react3 = require("react");
130
+ var RouterContext = (0, import_react3.createContext)(null);
131
+
132
+ // src/hooks/useLocation.ts
133
+ var import_react4 = require("react");
134
+ var useLocation = () => {
135
+ const context = (0, import_react4.useContext)(LocationContext);
136
+ if (context === null) {
137
+ throw new Error("useLocation must be used within a LocationProvider");
138
+ }
139
+ return context;
140
+ };
141
+
142
+ // src/hooks/useRoute.ts
143
+ var import_react5 = require("react");
144
+ var useRoute = () => {
145
+ const route = (0, import_react5.useContext)(RouteContext);
146
+ if (route === null) {
147
+ throw new Error("useRoute must be used within a RouteProvider");
148
+ }
149
+ return route;
150
+ };
151
+
152
+ // src/hooks/useMatches.ts
153
+ var useMatches = () => {
154
+ const route = useRoute();
155
+ const location = useLocation();
156
+ if (!location) return [];
157
+ return matchRoute(route, location.pathname)?.matches || [];
158
+ };
159
+
160
+ // src/hooks/useRouter.ts
161
+ var import_react6 = require("react");
162
+ var useRouter = () => {
163
+ const router = (0, import_react6.useContext)(RouterContext);
164
+ if (router === null) {
165
+ throw new Error("useRouter must be used within a Stack");
166
+ }
167
+ return router;
168
+ };
169
+ // Annotate the CommonJS export names for ESM import in node:
170
+ 0 && (module.exports = {
171
+ DefaultTransitionDuration,
172
+ LocationContext,
173
+ RouteContext,
174
+ RouterContext,
175
+ createRouter,
176
+ matchRoute,
177
+ matchUrl,
178
+ parseLocationFromHref,
179
+ redirect,
180
+ useLocation,
181
+ useMatches,
182
+ useRoute,
183
+ useRouter
184
+ });
185
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/context/locationContext.ts","../src/context/routeContext.ts","../src/context/routerContext.ts","../src/hooks/useLocation.ts","../src/hooks/useRoute.ts","../src/hooks/useMatches.ts","../src/hooks/useRouter.ts"],"sourcesContent":["export * from \"./utils.js\";\n\nexport * from \"./context/index.js\";\nexport * from \"./hooks/index.js\";\n","import type { Location, RootRoute, Route, RouterOptions } from \"./types.js\";\n\nexport const DefaultTransitionDuration = 300;\n\nexport const redirect = (options: { to: string; replace?: boolean }) => {\n return new Error(\"\", { cause: options });\n};\n\nexport const matchUrl = (\n pattern: string,\n url: string\n): { params: Record<string, string>; query: Record<string, string> } | null => {\n try {\n // 解析 URL\n let pathname, searchParams;\n\n if (url.startsWith(\"http://\") || url.startsWith(\"https://\")) {\n const urlObj = new URL(url);\n pathname = urlObj.pathname;\n searchParams = urlObj.searchParams;\n } else {\n // 處理相對路徑\n const [path, queryString] = url.split(\"?\");\n if (!path) {\n return null;\n }\n pathname = path;\n searchParams = new URLSearchParams(queryString || \"\");\n }\n\n // 移除路徑首尾的斜線以便比較\n const cleanPath = pathname.replaceAll(/^\\/|\\/$/g, \"\");\n const cleanPattern = pattern.replaceAll(/^\\/|\\/$/g, \"\");\n\n // 分割路徑段\n const pathSegments = cleanPath.split(\"/\");\n const patternSegments = cleanPattern.split(\"/\");\n\n // 路徑段數量不同則不匹配\n if (pathSegments.length !== patternSegments.length) {\n return null;\n }\n\n // 提取路徑參數\n const params: Record<string, string> = {};\n for (let i = 0; i < patternSegments.length; i++) {\n const patternSegment = patternSegments[i];\n const pathSegment = pathSegments[i];\n\n if (patternSegment.startsWith(\":\")) {\n // 動態參數\n const paramName = patternSegment.slice(1);\n params[paramName] = decodeURIComponent(pathSegment);\n } else if (patternSegment !== pathSegment) {\n // 靜態段不匹配\n return null;\n }\n }\n\n // 提取查詢參數\n const query = Object.fromEntries(searchParams.entries());\n\n return { params, query };\n } catch {\n return null;\n }\n};\n\nexport const matchRoute = (\n rootRoute: RootRoute,\n url: string\n): {\n matches: Route[];\n params: Record<string, string>;\n query: Record<string, string>;\n} | null => {\n const _matchRoute = (\n matches: Route[],\n route: Route\n ): {\n matches: Route[];\n params: Record<string, string>;\n query: Record<string, string>;\n } | null => {\n if (route.children) {\n for (const childRoute of route.children) {\n const matchesResult = _matchRoute([...matches, childRoute], childRoute);\n if (matchesResult) {\n return matchesResult;\n }\n }\n return null;\n }\n\n let pattern = \"\";\n for (const match of matches) {\n if (match.pathname === undefined) continue;\n pattern += `/${match.pathname}`;\n }\n const result = matchUrl(pattern, url);\n if (result) {\n return { matches, ...result };\n }\n return null;\n };\n\n return _matchRoute([], rootRoute);\n};\n\nexport const parseLocationFromHref = (\n rootRoute: RootRoute,\n to: string\n): Pick<Location, \"pathname\" | \"params\" | \"query\"> | null => {\n const result = matchRoute(rootRoute, to);\n if (!result) return null;\n return {\n pathname: to,\n params: result.params,\n query: result.query,\n };\n};\n\nexport const createRouter = (options: RouterOptions): RouterOptions => {\n return options;\n};\n","import { createContext } from \"react\";\n\nimport type { Location } from \"@/types.js\";\n\nexport const LocationContext = createContext<Location | null>(null);\n","import { createContext } from \"react\";\n\nimport type { RootRoute } from \"@/types.js\";\n\nexport const RouteContext = createContext<RootRoute | null>(null);\n","import { createContext } from \"react\";\n\nimport type {\n BackOptions,\n ForwardOptions,\n Location,\n NavigateOptions,\n RouterOptions,\n} from \"@/types.js\";\n\nexport interface RouterContextType {\n // Router Config\n options: RouterOptions;\n\n // Navigation State\n history: Location[];\n currentLocationIndex: number;\n location: Location | null;\n canGoBack: boolean;\n canGoForward: boolean;\n\n // Transition state\n isTransitioning: boolean;\n transitionDuration: number;\n transitioningToIndex: number | null;\n\n // Actions\n navigate: (options: NavigateOptions) => void;\n back: (options: BackOptions) => void;\n forward: (options: ForwardOptions) => void;\n}\n\nexport const RouterContext = createContext<RouterContextType | null>(null);\n","import { useContext } from \"react\";\n\nimport { LocationContext } from \"@/context/locationContext.js\";\n\nexport const useLocation = () => {\n const context = useContext(LocationContext);\n if (context === null) {\n throw new Error(\"useLocation must be used within a LocationProvider\");\n }\n return context;\n};\n","import { useContext } from \"react\";\n\nimport { RouteContext } from \"@/context/routeContext.js\";\n\nexport const useRoute = () => {\n const route = useContext(RouteContext);\n if (route === null) {\n throw new Error(\"useRoute must be used within a RouteProvider\");\n }\n return route;\n};\n","import { matchRoute } from \"@/utils.js\";\n\nimport { useLocation } from \"./useLocation.js\";\nimport { useRoute } from \"./useRoute.js\";\n\nexport const useMatches = () => {\n const route = useRoute();\n const location = useLocation();\n if (!location) return [];\n return matchRoute(route, location.pathname)?.matches || [];\n};\n","import { useContext } from \"react\";\n\nimport { RouterContext } from \"@/context/routerContext.js\";\n\nexport const useRouter = () => {\n const router = useContext(RouterContext);\n if (router === null) {\n throw new Error(\"useRouter must be used within a Stack\");\n }\n return router;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;A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Y;AACrC,MAAI,UAAU,MAAM;AAClB,UAAM,IAAI,MAAM,8CAA8C;AAAA,EAChE;AACA,SAAO;AACT;;;ACLO,IAAM,aAAa,MAAM;AAC9B,QAAM,QAAQ,SAAS;AACvB,QAAM,WAAW,YAAY;AAC7B,MAAI,CAAC,SAAU,QAAO,CAAC;AACvB,SAAO,WAAW,OAAO,SAAS,QAAQ,GAAG,WAAW,CAAC;AAC3D;;;ACVA,IAAAC,gBAA2B;AAIpB,IAAM,YAAY,MAAM;AAC7B,QAAM,aAAS,0BAAW,aAAa;AACvC,MAAI,WAAW,MAAM;AACnB,UAAM,IAAI,MAAM,uCAAuC;AAAA,EACzD;AACA,SAAO;AACT;","names":["import_react","import_react","import_react","import_react","import_react"]}
@@ -0,0 +1,103 @@
1
+ import { Pathname } from '@/lib/router';
2
+ import * as react from 'react';
3
+
4
+ interface Route {
5
+ id?: string;
6
+ pathname?: string;
7
+ beforeLoad?: ({ location }: { location: Location }) => Promise<void>;
8
+ component?: React.ComponentType<{ children?: React.ReactNode }>;
9
+ pendingComponent?: React.ComponentType;
10
+ children?: Route[];
11
+ }
12
+
13
+ interface RootRoute extends Route {
14
+ notFoundComponent?: React.ComponentType;
15
+ }
16
+
17
+ interface Location {
18
+ index: number;
19
+ pathname: Pathname;
20
+ params: any;
21
+ query: any;
22
+ state?: Map<string, any>;
23
+ }
24
+
25
+ interface RouterOptions {
26
+ defaultViewTransition?: (
27
+ fromLocation: Location | undefined,
28
+ toLocation: Location | undefined
29
+ ) => boolean;
30
+ }
31
+
32
+ interface TransitionOptions {
33
+ transition?: boolean;
34
+ duration?: number;
35
+ onFinish?: () => void;
36
+ }
37
+
38
+ type NavigateOptions = Partial<
39
+ Pick<Location, "params" | "query" | "state">
40
+ > & {
41
+ to: string;
42
+ replace?: boolean;
43
+ updateHistory?: boolean;
44
+ } & TransitionOptions;
45
+
46
+ type BackOptions =
47
+ | (TransitionOptions & {
48
+ depth?: number;
49
+ })
50
+ | void;
51
+
52
+ type ForwardOptions =
53
+ | (TransitionOptions & {
54
+ depth?: number;
55
+ })
56
+ | void;
57
+
58
+ declare const DefaultTransitionDuration = 300;
59
+ declare const redirect: (options: {
60
+ to: string;
61
+ replace?: boolean;
62
+ }) => Error;
63
+ declare const matchUrl: (pattern: string, url: string) => {
64
+ params: Record<string, string>;
65
+ query: Record<string, string>;
66
+ } | null;
67
+ declare const matchRoute: (rootRoute: RootRoute, url: string) => {
68
+ matches: Route[];
69
+ params: Record<string, string>;
70
+ query: Record<string, string>;
71
+ } | null;
72
+ declare const parseLocationFromHref: (rootRoute: RootRoute, to: string) => Pick<Location, "pathname" | "params" | "query"> | null;
73
+ declare const createRouter: (options: RouterOptions) => RouterOptions;
74
+
75
+ declare const LocationContext: react.Context<Location | null>;
76
+
77
+ declare const RouteContext: react.Context<RootRoute | null>;
78
+
79
+ interface RouterContextType {
80
+ options: RouterOptions;
81
+ history: Location[];
82
+ currentLocationIndex: number;
83
+ location: Location | null;
84
+ canGoBack: boolean;
85
+ canGoForward: boolean;
86
+ isTransitioning: boolean;
87
+ transitionDuration: number;
88
+ transitioningToIndex: number | null;
89
+ navigate: (options: NavigateOptions) => void;
90
+ back: (options: BackOptions) => void;
91
+ forward: (options: ForwardOptions) => void;
92
+ }
93
+ declare const RouterContext: react.Context<RouterContextType | null>;
94
+
95
+ declare const useLocation: () => Location;
96
+
97
+ declare const useMatches: () => Route[];
98
+
99
+ declare const useRoute: () => RootRoute;
100
+
101
+ declare const useRouter: () => RouterContextType;
102
+
103
+ export { DefaultTransitionDuration, LocationContext, RouteContext, RouterContext, type RouterContextType, createRouter, matchRoute, matchUrl, parseLocationFromHref, redirect, useLocation, useMatches, useRoute, useRouter };
@@ -0,0 +1,103 @@
1
+ import { Pathname } from '@/lib/router';
2
+ import * as react from 'react';
3
+
4
+ interface Route {
5
+ id?: string;
6
+ pathname?: string;
7
+ beforeLoad?: ({ location }: { location: Location }) => Promise<void>;
8
+ component?: React.ComponentType<{ children?: React.ReactNode }>;
9
+ pendingComponent?: React.ComponentType;
10
+ children?: Route[];
11
+ }
12
+
13
+ interface RootRoute extends Route {
14
+ notFoundComponent?: React.ComponentType;
15
+ }
16
+
17
+ interface Location {
18
+ index: number;
19
+ pathname: Pathname;
20
+ params: any;
21
+ query: any;
22
+ state?: Map<string, any>;
23
+ }
24
+
25
+ interface RouterOptions {
26
+ defaultViewTransition?: (
27
+ fromLocation: Location | undefined,
28
+ toLocation: Location | undefined
29
+ ) => boolean;
30
+ }
31
+
32
+ interface TransitionOptions {
33
+ transition?: boolean;
34
+ duration?: number;
35
+ onFinish?: () => void;
36
+ }
37
+
38
+ type NavigateOptions = Partial<
39
+ Pick<Location, "params" | "query" | "state">
40
+ > & {
41
+ to: string;
42
+ replace?: boolean;
43
+ updateHistory?: boolean;
44
+ } & TransitionOptions;
45
+
46
+ type BackOptions =
47
+ | (TransitionOptions & {
48
+ depth?: number;
49
+ })
50
+ | void;
51
+
52
+ type ForwardOptions =
53
+ | (TransitionOptions & {
54
+ depth?: number;
55
+ })
56
+ | void;
57
+
58
+ declare const DefaultTransitionDuration = 300;
59
+ declare const redirect: (options: {
60
+ to: string;
61
+ replace?: boolean;
62
+ }) => Error;
63
+ declare const matchUrl: (pattern: string, url: string) => {
64
+ params: Record<string, string>;
65
+ query: Record<string, string>;
66
+ } | null;
67
+ declare const matchRoute: (rootRoute: RootRoute, url: string) => {
68
+ matches: Route[];
69
+ params: Record<string, string>;
70
+ query: Record<string, string>;
71
+ } | null;
72
+ declare const parseLocationFromHref: (rootRoute: RootRoute, to: string) => Pick<Location, "pathname" | "params" | "query"> | null;
73
+ declare const createRouter: (options: RouterOptions) => RouterOptions;
74
+
75
+ declare const LocationContext: react.Context<Location | null>;
76
+
77
+ declare const RouteContext: react.Context<RootRoute | null>;
78
+
79
+ interface RouterContextType {
80
+ options: RouterOptions;
81
+ history: Location[];
82
+ currentLocationIndex: number;
83
+ location: Location | null;
84
+ canGoBack: boolean;
85
+ canGoForward: boolean;
86
+ isTransitioning: boolean;
87
+ transitionDuration: number;
88
+ transitioningToIndex: number | null;
89
+ navigate: (options: NavigateOptions) => void;
90
+ back: (options: BackOptions) => void;
91
+ forward: (options: ForwardOptions) => void;
92
+ }
93
+ declare const RouterContext: react.Context<RouterContextType | null>;
94
+
95
+ declare const useLocation: () => Location;
96
+
97
+ declare const useMatches: () => Route[];
98
+
99
+ declare const useRoute: () => RootRoute;
100
+
101
+ declare const useRouter: () => RouterContextType;
102
+
103
+ export { DefaultTransitionDuration, LocationContext, RouteContext, RouterContext, type RouterContextType, createRouter, matchRoute, matchUrl, parseLocationFromHref, redirect, useLocation, useMatches, useRoute, useRouter };
package/dist/index.js ADDED
@@ -0,0 +1,146 @@
1
+ // src/utils.ts
2
+ var DefaultTransitionDuration = 300;
3
+ var redirect = (options) => {
4
+ return new Error("", { cause: options });
5
+ };
6
+ var matchUrl = (pattern, url) => {
7
+ try {
8
+ let pathname, searchParams;
9
+ if (url.startsWith("http://") || url.startsWith("https://")) {
10
+ const urlObj = new URL(url);
11
+ pathname = urlObj.pathname;
12
+ searchParams = urlObj.searchParams;
13
+ } else {
14
+ const [path, queryString] = url.split("?");
15
+ if (!path) {
16
+ return null;
17
+ }
18
+ pathname = path;
19
+ searchParams = new URLSearchParams(queryString || "");
20
+ }
21
+ const cleanPath = pathname.replaceAll(/^\/|\/$/g, "");
22
+ const cleanPattern = pattern.replaceAll(/^\/|\/$/g, "");
23
+ const pathSegments = cleanPath.split("/");
24
+ const patternSegments = cleanPattern.split("/");
25
+ if (pathSegments.length !== patternSegments.length) {
26
+ return null;
27
+ }
28
+ const params = {};
29
+ for (let i = 0; i < patternSegments.length; i++) {
30
+ const patternSegment = patternSegments[i];
31
+ const pathSegment = pathSegments[i];
32
+ if (patternSegment.startsWith(":")) {
33
+ const paramName = patternSegment.slice(1);
34
+ params[paramName] = decodeURIComponent(pathSegment);
35
+ } else if (patternSegment !== pathSegment) {
36
+ return null;
37
+ }
38
+ }
39
+ const query = Object.fromEntries(searchParams.entries());
40
+ return { params, query };
41
+ } catch {
42
+ return null;
43
+ }
44
+ };
45
+ var matchRoute = (rootRoute, url) => {
46
+ const _matchRoute = (matches, route) => {
47
+ if (route.children) {
48
+ for (const childRoute of route.children) {
49
+ const matchesResult = _matchRoute([...matches, childRoute], childRoute);
50
+ if (matchesResult) {
51
+ return matchesResult;
52
+ }
53
+ }
54
+ return null;
55
+ }
56
+ let pattern = "";
57
+ for (const match of matches) {
58
+ if (match.pathname === void 0) continue;
59
+ pattern += `/${match.pathname}`;
60
+ }
61
+ const result = matchUrl(pattern, url);
62
+ if (result) {
63
+ return { matches, ...result };
64
+ }
65
+ return null;
66
+ };
67
+ return _matchRoute([], rootRoute);
68
+ };
69
+ var parseLocationFromHref = (rootRoute, to) => {
70
+ const result = matchRoute(rootRoute, to);
71
+ if (!result) return null;
72
+ return {
73
+ pathname: to,
74
+ params: result.params,
75
+ query: result.query
76
+ };
77
+ };
78
+ var createRouter = (options) => {
79
+ return options;
80
+ };
81
+
82
+ // src/context/locationContext.ts
83
+ import { createContext } from "react";
84
+ var LocationContext = createContext(null);
85
+
86
+ // src/context/routeContext.ts
87
+ import { createContext as createContext2 } from "react";
88
+ var RouteContext = createContext2(null);
89
+
90
+ // src/context/routerContext.ts
91
+ import { createContext as createContext3 } from "react";
92
+ var RouterContext = createContext3(null);
93
+
94
+ // src/hooks/useLocation.ts
95
+ import { useContext } from "react";
96
+ var useLocation = () => {
97
+ const context = useContext(LocationContext);
98
+ if (context === null) {
99
+ throw new Error("useLocation must be used within a LocationProvider");
100
+ }
101
+ return context;
102
+ };
103
+
104
+ // src/hooks/useRoute.ts
105
+ import { useContext as useContext2 } from "react";
106
+ var useRoute = () => {
107
+ const route = useContext2(RouteContext);
108
+ if (route === null) {
109
+ throw new Error("useRoute must be used within a RouteProvider");
110
+ }
111
+ return route;
112
+ };
113
+
114
+ // src/hooks/useMatches.ts
115
+ var useMatches = () => {
116
+ const route = useRoute();
117
+ const location = useLocation();
118
+ if (!location) return [];
119
+ return matchRoute(route, location.pathname)?.matches || [];
120
+ };
121
+
122
+ // src/hooks/useRouter.ts
123
+ import { useContext as useContext3 } from "react";
124
+ var useRouter = () => {
125
+ const router = useContext3(RouterContext);
126
+ if (router === null) {
127
+ throw new Error("useRouter must be used within a Stack");
128
+ }
129
+ return router;
130
+ };
131
+ export {
132
+ DefaultTransitionDuration,
133
+ LocationContext,
134
+ RouteContext,
135
+ RouterContext,
136
+ createRouter,
137
+ matchRoute,
138
+ matchUrl,
139
+ parseLocationFromHref,
140
+ redirect,
141
+ useLocation,
142
+ useMatches,
143
+ useRoute,
144
+ useRouter
145
+ };
146
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils.ts","../src/context/locationContext.ts","../src/context/routeContext.ts","../src/context/routerContext.ts","../src/hooks/useLocation.ts","../src/hooks/useRoute.ts","../src/hooks/useMatches.ts","../src/hooks/useRouter.ts"],"sourcesContent":["import type { Location, RootRoute, Route, RouterOptions } from \"./types.js\";\n\nexport const DefaultTransitionDuration = 300;\n\nexport const redirect = (options: { to: string; replace?: boolean }) => {\n return new Error(\"\", { cause: options });\n};\n\nexport const matchUrl = (\n pattern: string,\n url: string\n): { params: Record<string, string>; query: Record<string, string> } | null => {\n try {\n // 解析 URL\n let pathname, searchParams;\n\n if (url.startsWith(\"http://\") || url.startsWith(\"https://\")) {\n const urlObj = new URL(url);\n pathname = urlObj.pathname;\n searchParams = urlObj.searchParams;\n } else {\n // 處理相對路徑\n const [path, queryString] = url.split(\"?\");\n if (!path) {\n return null;\n }\n pathname = path;\n searchParams = new URLSearchParams(queryString || \"\");\n }\n\n // 移除路徑首尾的斜線以便比較\n const cleanPath = pathname.replaceAll(/^\\/|\\/$/g, \"\");\n const cleanPattern = pattern.replaceAll(/^\\/|\\/$/g, \"\");\n\n // 分割路徑段\n const pathSegments = cleanPath.split(\"/\");\n const patternSegments = cleanPattern.split(\"/\");\n\n // 路徑段數量不同則不匹配\n if (pathSegments.length !== patternSegments.length) {\n return null;\n }\n\n // 提取路徑參數\n const params: Record<string, string> = {};\n for (let i = 0; i < patternSegments.length; i++) {\n const patternSegment = patternSegments[i];\n const pathSegment = pathSegments[i];\n\n if (patternSegment.startsWith(\":\")) {\n // 動態參數\n const paramName = patternSegment.slice(1);\n params[paramName] = decodeURIComponent(pathSegment);\n } else if (patternSegment !== pathSegment) {\n // 靜態段不匹配\n return null;\n }\n }\n\n // 提取查詢參數\n const query = Object.fromEntries(searchParams.entries());\n\n return { params, query };\n } catch {\n return null;\n }\n};\n\nexport const matchRoute = (\n rootRoute: RootRoute,\n url: string\n): {\n matches: Route[];\n params: Record<string, string>;\n query: Record<string, string>;\n} | null => {\n const _matchRoute = (\n matches: Route[],\n route: Route\n ): {\n matches: Route[];\n params: Record<string, string>;\n query: Record<string, string>;\n } | null => {\n if (route.children) {\n for (const childRoute of route.children) {\n const matchesResult = _matchRoute([...matches, childRoute], childRoute);\n if (matchesResult) {\n return matchesResult;\n }\n }\n return null;\n }\n\n let pattern = \"\";\n for (const match of matches) {\n if (match.pathname === undefined) continue;\n pattern += `/${match.pathname}`;\n }\n const result = matchUrl(pattern, url);\n if (result) {\n return { matches, ...result };\n }\n return null;\n };\n\n return _matchRoute([], rootRoute);\n};\n\nexport const parseLocationFromHref = (\n rootRoute: RootRoute,\n to: string\n): Pick<Location, \"pathname\" | \"params\" | \"query\"> | null => {\n const result = matchRoute(rootRoute, to);\n if (!result) return null;\n return {\n pathname: to,\n params: result.params,\n query: result.query,\n };\n};\n\nexport const createRouter = (options: RouterOptions): RouterOptions => {\n return options;\n};\n","import { createContext } from \"react\";\n\nimport type { Location } from \"@/types.js\";\n\nexport const LocationContext = createContext<Location | null>(null);\n","import { createContext } from \"react\";\n\nimport type { RootRoute } from \"@/types.js\";\n\nexport const RouteContext = createContext<RootRoute | null>(null);\n","import { createContext } from \"react\";\n\nimport type {\n BackOptions,\n ForwardOptions,\n Location,\n NavigateOptions,\n RouterOptions,\n} from \"@/types.js\";\n\nexport interface RouterContextType {\n // Router Config\n options: RouterOptions;\n\n // Navigation State\n history: Location[];\n currentLocationIndex: number;\n location: Location | null;\n canGoBack: boolean;\n canGoForward: boolean;\n\n // Transition state\n isTransitioning: boolean;\n transitionDuration: number;\n transitioningToIndex: number | null;\n\n // Actions\n navigate: (options: NavigateOptions) => void;\n back: (options: BackOptions) => void;\n forward: (options: ForwardOptions) => void;\n}\n\nexport const RouterContext = createContext<RouterContextType | null>(null);\n","import { useContext } from \"react\";\n\nimport { LocationContext } from \"@/context/locationContext.js\";\n\nexport const useLocation = () => {\n const context = useContext(LocationContext);\n if (context === null) {\n throw new Error(\"useLocation must be used within a LocationProvider\");\n }\n return context;\n};\n","import { useContext } from \"react\";\n\nimport { RouteContext } from \"@/context/routeContext.js\";\n\nexport const useRoute = () => {\n const route = useContext(RouteContext);\n if (route === null) {\n throw new Error(\"useRoute must be used within a RouteProvider\");\n }\n return route;\n};\n","import { matchRoute } from \"@/utils.js\";\n\nimport { useLocation } from \"./useLocation.js\";\nimport { useRoute } from \"./useRoute.js\";\n\nexport const useMatches = () => {\n const route = useRoute();\n const location = useLocation();\n if (!location) return [];\n return matchRoute(route, location.pathname)?.matches || [];\n};\n","import { useContext } from \"react\";\n\nimport { RouterContext } from \"@/context/routerContext.js\";\n\nexport const useRouter = () => {\n const router = useContext(RouterContext);\n if (router === null) {\n throw new Error(\"useRouter must be used within a Stack\");\n }\n return router;\n};\n"],"mappings":";AAEO,IAAM,4BAA4B;AAElC,IAAM,WAAW,CAAC,YAA+C;AACtE,SAAO,IAAI,MAAM,IAAI,EAAE,OAAO,QAAQ,CAAC;AACzC;AAEO,IAAM,WAAW,CACtB,SACA,QAC6E;AAC7E,MAAI;AAEF,QAAI,UAAU;AAEd,QAAI,IAAI,WAAW,SAAS,KAAK,IAAI,WAAW,UAAU,GAAG;AAC3D,YAAM,SAAS,IAAI,IAAI,GAAG;AAC1B,iBAAW,OAAO;AAClB,qBAAe,OAAO;AAAA,IACxB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AAM,IAAI,MAAM,uCAAuC;AAAA,EACzD;AACA,SAAO;AACT;","names":["createContext","createContext","useContext","useContext","useContext","useContext"]}
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@modastar/z-router",
3
+ "version": "0.0.2",
4
+ "description": "",
5
+ "keywords": [],
6
+ "homepage": "https://github.com/xLanStar/z-router#readme",
7
+ "bugs": {
8
+ "url": "https://github.com/xLanStar/z-router/issues"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/xLanStar/z-router.git"
13
+ },
14
+ "license": "MIT",
15
+ "author": "Lanstar <danny95624268@gmail.com>",
16
+ "type": "module",
17
+ "main": "dist/index.js",
18
+ "module": "dist/index.mjs",
19
+ "types": "dist/index.d.ts",
20
+ "scripts": {
21
+ "build": "tsup",
22
+ "build:watch": "tsup --watch",
23
+ "prepublishOnly": "pnpm run build"
24
+ },
25
+ "packageManager": "pnpm@10.23.0",
26
+ "dependencies": {
27
+ "react": "^19.2.0"
28
+ },
29
+ "devDependencies": {
30
+ "@types/react": "^19.2.7",
31
+ "tsup": "^8.5.1",
32
+ "typescript": "^5.9.3"
33
+ }
34
+ }