@e7w/easy-routes 0.0.1

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.md ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Kamil Bysiec
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # 自用React-router配置
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@e7w/easy-routes",
3
+ "version": "0.0.1",
4
+ "publishConfig": {
5
+ "access": "public",
6
+ "registry": "https://registry.npmjs.org/"
7
+ },
8
+ "type": "module",
9
+ "exports": {
10
+ "types": "./src/index.ts",
11
+ "import": "./src/index.ts"
12
+ },
13
+ "dependencies": {
14
+ "@e7w/easy-model": "^0.2.1",
15
+ "nprogress": "^0.2.0",
16
+ "react": "^19.2.0",
17
+ "react-router": "^7.13.1",
18
+ "tailwindcss": "^4.2.1",
19
+ "zod": "^4.3.6"
20
+ },
21
+ "devDependencies": {
22
+ "@eslint/js": "^9.39.1",
23
+ "@types/node": "^24.10.1",
24
+ "@types/nprogress": "^0.2.3",
25
+ "@types/react": "^19.2.7",
26
+ "@types/react-dom": "^19.2.3",
27
+ "@vitejs/plugin-react": "^5.1.1",
28
+ "eslint": "^9.39.1",
29
+ "eslint-plugin-react-hooks": "^7.0.1",
30
+ "eslint-plugin-react-refresh": "^0.4.24",
31
+ "globals": "^16.5.0",
32
+ "typescript": "~5.9.3",
33
+ "typescript-eslint": "^8.48.0",
34
+ "vite": "^8.0.0-beta.13",
35
+ "vitest": "^4.0.18"
36
+ },
37
+ "files": [
38
+ "src",
39
+ "README.md",
40
+ "LICENSE.md"
41
+ ],
42
+ "license": "MIT",
43
+ "scripts": {
44
+ "lint": "eslint ."
45
+ }
46
+ }
@@ -0,0 +1,109 @@
1
+ @import "tailwindcss";
2
+
3
+ /* KEYFRAMES */
4
+
5
+ @keyframes spin {
6
+ from {
7
+ transform: rotate(0);
8
+ }
9
+ to {
10
+ transform: rotate(359deg);
11
+ }
12
+ }
13
+
14
+ @keyframes spin3D {
15
+ from {
16
+ transform: rotate3d(0.5, 0.5, 0.5, 360deg);
17
+ }
18
+ to {
19
+ transform: rotate3d(0deg);
20
+ }
21
+ }
22
+
23
+ @keyframes configure-clockwise {
24
+ 0% {
25
+ transform: rotate(0);
26
+ }
27
+ 25% {
28
+ transform: rotate(90deg);
29
+ }
30
+ 50% {
31
+ transform: rotate(180deg);
32
+ }
33
+ 75% {
34
+ transform: rotate(270deg);
35
+ }
36
+ 100% {
37
+ transform: rotate(360deg);
38
+ }
39
+ }
40
+
41
+ @keyframes configure-xclockwise {
42
+ 0% {
43
+ transform: rotate(45deg);
44
+ }
45
+ 25% {
46
+ transform: rotate(-45deg);
47
+ }
48
+ 50% {
49
+ transform: rotate(-135deg);
50
+ }
51
+ 75% {
52
+ transform: rotate(-225deg);
53
+ }
54
+ 100% {
55
+ transform: rotate(-315deg);
56
+ }
57
+ }
58
+
59
+ @keyframes pulse {
60
+ from {
61
+ opacity: 1;
62
+ transform: scale(1);
63
+ }
64
+ to {
65
+ opacity: 0.25;
66
+ transform: scale(0.75);
67
+ }
68
+ }
69
+
70
+ /* GRID STYLING */
71
+ .spinner-box {
72
+ @apply top-0 left-0 w-full h-full flex justify-center items-center bg-transparent fixed z-50 backdrop-blur-sm;
73
+ }
74
+
75
+ .leo {
76
+ @apply absolute flex justify-center items-center rounded-full;
77
+ }
78
+
79
+ .blue-orbit {
80
+ @apply w-[165px] h-[165px] border-[1px] border-blue-400/70 border-solid animate-[spin3D_3s_linear_0.2s_infinite];
81
+ }
82
+
83
+ .green-orbit {
84
+ @apply w-[120px] h-[120px] border-[1px] border-solid border-green-400/70 animate-[spin3D_2s_linear_0s_infinite];
85
+ }
86
+
87
+ .red-orbit {
88
+ @apply w-[90px] h-[30px] border-[1px] border-solid border-orange-400/70 animate-[spin3D_1s_linear_0s_infinite];
89
+ }
90
+
91
+ .white-orbit {
92
+ @apply w-[60px] h-[60px] border-2 border-solid border-white animate-[spin3D_10s_linear_0s_infinite];
93
+ }
94
+
95
+ .w1 {
96
+ transform: rotate3D(1, 1, 1, 90deg);
97
+ }
98
+
99
+ .w2 {
100
+ transform: rotate3D(1, 2, 0.5, 90deg);
101
+ }
102
+
103
+ .w3 {
104
+ transform: rotate3D(0.5, 1, 2, 90deg);
105
+ }
106
+
107
+ .markdown-body {
108
+ background-color: var(--color-base-300);
109
+ }
@@ -0,0 +1,8 @@
1
+ import type { FC } from "react";
2
+ import { Outlet } from "react-router";
3
+
4
+ export const DefaultOutlet: FC = () => (
5
+ <>
6
+ <Outlet />
7
+ </>
8
+ );
@@ -0,0 +1,25 @@
1
+ import type { FC } from "react";
2
+ import { isRouteErrorResponse, useRouteError } from "react-router";
3
+
4
+ export const ErrorBoundary: FC = () => {
5
+ const error = useRouteError();
6
+ return (
7
+ <div className="flex h-full w-full items-center justify-center">
8
+ <div className="flex flex-col items-center justify-center">
9
+ <h1 className="text-2xl font-bold mb-4">Error</h1>
10
+ <p>Something went wrong.</p>
11
+ {isRouteErrorResponse(error) && (
12
+ <>
13
+ <p className="text-red-300">
14
+ {error.status} {error.statusText}
15
+ </p>
16
+ <p className="text-red-300">{JSON.stringify(error.data)}</p>
17
+ </>
18
+ )}
19
+ {error instanceof Error && (
20
+ <p className="text-red-300">{error.message}</p>
21
+ )}
22
+ </div>
23
+ </div>
24
+ );
25
+ };
@@ -0,0 +1,23 @@
1
+ import { type FC } from "react";
2
+ import { useDebouncedValue } from "../utils/hooks";
3
+ import { useLoader } from "@e7w/easy-model";
4
+ import "../assets/index.css";
5
+
6
+ export const Loading: FC = () => {
7
+ const { isGlobalLoading } = useLoader();
8
+ const visible = useDebouncedValue(isGlobalLoading);
9
+ if (!visible) return;
10
+ return (
11
+ <div className="spinner-box">
12
+ <div className="blue-orbit leo"></div>
13
+
14
+ <div className="green-orbit leo"></div>
15
+
16
+ <div className="red-orbit leo"></div>
17
+
18
+ <div className="white-orbit w1 leo"></div>
19
+ <div className="white-orbit w2 leo"></div>
20
+ <div className="white-orbit w3 leo"></div>
21
+ </div>
22
+ );
23
+ };
@@ -0,0 +1,31 @@
1
+ import { useEffect, type FC } from "react";
2
+ import { Outlet, useNavigation } from "react-router";
3
+ import nProgress from "nprogress";
4
+ import "nprogress/nprogress.css";
5
+ import { Loading } from "./Loading";
6
+
7
+ nProgress.configure({
8
+ showSpinner: false, // 是否显示右上角螺旋加载提示(通常关掉更简洁)
9
+ speed: 500, // 动画速度(毫秒)
10
+ minimum: 0.1, // 进度条开始时的最小百分比
11
+ easing: "ease", // 动画缓动函数
12
+ trickleSpeed: 200, // 进度条自动递增的频率(毫秒)
13
+ });
14
+
15
+ export const ProgressLayout: FC = () => {
16
+ const { state } = useNavigation();
17
+ useEffect(() => {
18
+ if (state === "loading") {
19
+ nProgress.start();
20
+ } else {
21
+ nProgress.done();
22
+ }
23
+ }, [state]);
24
+
25
+ return (
26
+ <>
27
+ <Outlet />
28
+ <Loading />
29
+ </>
30
+ );
31
+ };
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export type { Loader } from "./types";
2
+ export { routerSchema } from "./models/system";
3
+ export { routes } from "./router";
@@ -0,0 +1,49 @@
1
+ import { inject, loader, provide } from "@e7w/easy-model";
2
+ import z from "zod";
3
+ import type { Ctx } from "../types";
4
+ import type { Params } from "react-router";
5
+
6
+ export interface RouterSchema {
7
+ init(): void | Promise<void>;
8
+ permission: number;
9
+ defaultTitle?: string;
10
+ }
11
+
12
+ export const routerSchema: z.ZodType<RouterSchema, RouterSchema> = z.object({
13
+ init: z.function({
14
+ output: z.union([z.promise(z.void()), z.void()]),
15
+ }),
16
+ permission: z.number(),
17
+ defaultTitle: z.string().optional(),
18
+ });
19
+
20
+ export const system = provide(
21
+ class System {
22
+ @inject(routerSchema)
23
+ router: RouterSchema = {
24
+ init() {},
25
+ permission: 0,
26
+ defaultTitle: document.title,
27
+ };
28
+
29
+ @loader.once
30
+ @loader.load(true)
31
+ async init() {
32
+ await this.router.init();
33
+ }
34
+
35
+ hasPermission(permission: number = 0) {
36
+ return (this.router.permission & permission) === permission;
37
+ }
38
+
39
+ getCtx(params: Params, request: Request, permission = 0): Ctx {
40
+ return {
41
+ title: this.router.defaultTitle || document.title,
42
+ signed: (permission & 1) === 0 || this.hasPermission(1),
43
+ noPermission: !this.hasPermission(permission),
44
+ params,
45
+ query: Object.fromEntries(new URL(request.url).searchParams),
46
+ };
47
+ }
48
+ },
49
+ )();
package/src/router.tsx ADDED
@@ -0,0 +1,96 @@
1
+ import type { FC } from "react";
2
+ import { Navigate, redirect, type RouteObject } from "react-router";
3
+ import { DefaultOutlet } from "./components/DefaultOutlet";
4
+ import { ErrorBoundary } from "./components/ErrorBoundary";
5
+ import { ProgressLayout } from "./components/ProgressLayout";
6
+ import type { Meta } from "./types";
7
+ import { system } from "./models/system";
8
+
9
+ const pages: Record<string, FC> = import.meta.glob("/src/pages/**/index.tsx", {
10
+ eager: true,
11
+ import: "Page",
12
+ }) as Record<string, FC>;
13
+ const layouts: Record<string, FC> = import.meta.glob(
14
+ "/src/pages/**/layout.tsx",
15
+ {
16
+ eager: true,
17
+ import: "Layout",
18
+ },
19
+ ) as Record<string, FC>;
20
+ const metas: Record<string, Meta> = import.meta.glob("/src/pages/**/meta.ts", {
21
+ eager: true,
22
+ });
23
+
24
+ const routes: RouteObject[] = [];
25
+ const obj: Record<string, RouteObject> = {};
26
+ const filePaths = new Set(
27
+ Object.keys({ ...pages, ...layouts }).map((p) =>
28
+ p.replace(/\/(index|layout)\.tsx$/, ""),
29
+ ),
30
+ );
31
+ filePaths.forEach((filePath) => {
32
+ const pagePath = filePath + "/index.tsx";
33
+ const Page = pages[pagePath];
34
+ const layoutPath = filePath + "/layout.tsx";
35
+ const Layout = layouts[layoutPath] || DefaultOutlet;
36
+ const metaPath = filePath + "/meta.ts";
37
+ const meta = metas[metaPath] || {};
38
+ const path =
39
+ filePath.replace(/.*\/pages/, "").replace(/\[([^\]]+)\]/, ":$1") || "/";
40
+
41
+ const hasPage = Boolean(Page);
42
+ obj[path] = {
43
+ path,
44
+ element: <Layout />,
45
+ children: [
46
+ {
47
+ element: hasPage ? <Page /> : <Navigate to="/" replace />,
48
+ index: true,
49
+ loader: hasPage
50
+ ? async ({ params, request }) => {
51
+ await system.init();
52
+ const ctx = system.getCtx(params, request, meta.permission);
53
+ await meta.loader?.(ctx, meta);
54
+ if (!ctx.signed) return redirect("/login");
55
+ if (ctx.noPermission) return redirect("/403");
56
+ document.title = ctx.title;
57
+ return ctx.data;
58
+ }
59
+ : undefined,
60
+ },
61
+ ],
62
+ };
63
+ });
64
+
65
+ filePaths.forEach((filePath) => {
66
+ const path =
67
+ filePath.replace(/.*\/pages/, "").replace(/\[([^\]]+)\]/, ":$1") || "/";
68
+ if (path === "/") return;
69
+ const currentObj = obj[path];
70
+ const segments = path.split("/").filter(Boolean);
71
+ const paths = ["/"];
72
+ segments.reduce((acc, curr) => {
73
+ const newPath = acc + "/" + curr;
74
+ if (newPath !== path) paths.unshift(newPath);
75
+ return newPath;
76
+ }, "");
77
+ for (let index = 0; index < paths.length; index++) {
78
+ const p = paths[index];
79
+ if (obj[p]) {
80
+ obj[p].children!.push(currentObj);
81
+ break;
82
+ }
83
+ }
84
+ });
85
+ obj["/"].errorElement = <ErrorBoundary />;
86
+ routes.push({
87
+ path: "/",
88
+ element: <ProgressLayout />,
89
+ children: [obj["/"]],
90
+ });
91
+ routes.push({
92
+ path: "*",
93
+ element: <Navigate to={obj["/404"] ? "/404" : "/"} replace />,
94
+ });
95
+
96
+ export { routes };
@@ -0,0 +1,18 @@
1
+ import type { Params } from "react-router";
2
+
3
+ export interface Ctx {
4
+ title: string;
5
+ signed: boolean;
6
+ noPermission: boolean;
7
+ params: Params;
8
+ query: Params;
9
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
+ data?: any;
11
+ }
12
+
13
+ export type Meta = {
14
+ permission?: number;
15
+ loader?: Loader;
16
+ } & Record<string, unknown>;
17
+
18
+ export type Loader = (ctx: Ctx, meta: Meta) => void | Promise<void>;
@@ -0,0 +1,16 @@
1
+ import { useEffect, useRef, useState } from "react";
2
+
3
+ export function useDebouncedValue<T>(value: T): T {
4
+ const [result, setResult] = useState(value);
5
+ const timer = useRef<number | undefined>(undefined);
6
+ useEffect(() => {
7
+ clearTimeout(timer.current);
8
+ timer.current = setTimeout(() => {
9
+ setResult(value);
10
+ }, 700);
11
+ return () => {
12
+ clearTimeout(timer.current);
13
+ };
14
+ }, [result, value]);
15
+ return result;
16
+ }