@arielgonzaguer/michi-router 1.0.0 → 1.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/README.md
CHANGED
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
# Michi Router
|
|
2
2
|
|
|
3
3
|
El router minimalista y simple para React.
|
|
4
|
+
El objetivo principal de esta herramienta es proporcionar la funcionalidad básica de enrutamiento.
|
|
5
|
+
|
|
6
|
+
## Características
|
|
7
|
+
|
|
8
|
+
- Es idea para proyectos pequeños o que solo necesitan una funcionalidad básica de enrutamiento.
|
|
9
|
+
- No requiere de ninguna configuración adicional.
|
|
10
|
+
- No requiere de ninguna dependencia externa.
|
|
11
|
+
- Es compatible con React 16.8 y versiones posteriores.
|
|
12
|
+
- Creado con TypeScript.
|
|
13
|
+
- Ultra ligero. Menos de 15kb (más ligero y básico que otras librerías).
|
|
4
14
|
|
|
5
15
|
## Installation
|
|
6
16
|
|
|
@@ -8,9 +18,10 @@ El router minimalista y simple para React.
|
|
|
8
18
|
npm install @arielgonzaguer/michi-router
|
|
9
19
|
```
|
|
10
20
|
|
|
11
|
-
##
|
|
21
|
+
## Uso básico
|
|
12
22
|
|
|
13
23
|
```jsx
|
|
24
|
+
// src/App.jsx //
|
|
14
25
|
import { RouterProvider, Link } from "@arielgonzaguer/michi-router";
|
|
15
26
|
|
|
16
27
|
// puede crear rutas en un archivo separado o en el mismo archivo
|
|
@@ -27,8 +38,10 @@ function App() {
|
|
|
27
38
|
</RouterProvider>
|
|
28
39
|
);
|
|
29
40
|
}
|
|
41
|
+
```
|
|
30
42
|
|
|
31
|
-
|
|
43
|
+
### Usando Link
|
|
44
|
+
```jsx
|
|
32
45
|
function NavigationComponent() {
|
|
33
46
|
return (
|
|
34
47
|
<nav>
|
|
@@ -37,14 +50,116 @@ function NavigationComponent() {
|
|
|
37
50
|
</nav>
|
|
38
51
|
);
|
|
39
52
|
}
|
|
53
|
+
```
|
|
40
54
|
|
|
41
|
-
|
|
55
|
+
### Navegación programática (Hook useNavigate)
|
|
56
|
+
```jsx
|
|
42
57
|
function NavigateButton() {
|
|
43
58
|
const navigate = useNavigate();
|
|
44
59
|
return <button onClick={() => navigate("/about")}>Ir a About</button>;
|
|
45
60
|
}
|
|
46
61
|
```
|
|
47
62
|
|
|
63
|
+
### Organización de rutas en archivos separados
|
|
64
|
+
|
|
65
|
+
Para aplicaciones más grandes, puedes organizar tus rutas en archivos separados:
|
|
66
|
+
|
|
67
|
+
```jsx
|
|
68
|
+
// routes.js
|
|
69
|
+
import Home from './pages/Home';
|
|
70
|
+
import About from './pages/About';
|
|
71
|
+
import Products from './pages/Products';
|
|
72
|
+
import NotFound from './pages/NotFound';
|
|
73
|
+
|
|
74
|
+
export const routes = [
|
|
75
|
+
{ path: "/", component: <Home /> },
|
|
76
|
+
{ path: "/about", component: <About /> },
|
|
77
|
+
{ path: "/products", component: <Products /> },
|
|
78
|
+
];
|
|
79
|
+
|
|
80
|
+
export const notFoundPage = <NotFound />;
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
```jsx
|
|
84
|
+
// App.jsx
|
|
85
|
+
import { RouterProvider } from "@arielgonzaguer/michi-router";
|
|
86
|
+
import { routes, notFoundPage } from './routes';
|
|
87
|
+
|
|
88
|
+
function App() {
|
|
89
|
+
return (
|
|
90
|
+
<RouterProvider routes={routes}>
|
|
91
|
+
{notFoundPage}
|
|
92
|
+
</RouterProvider>
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### Integración con sistemas de autenticación
|
|
98
|
+
|
|
99
|
+
```jsx
|
|
100
|
+
import { RouterProvider } from "@arielgonzaguer/michi-router";
|
|
101
|
+
import { useAuth } from "./auth-context";
|
|
102
|
+
|
|
103
|
+
function App() {
|
|
104
|
+
const { isAuthenticated } = useAuth();
|
|
105
|
+
|
|
106
|
+
// Definimos rutas condicionalmente basadas en autenticación
|
|
107
|
+
const routes = [
|
|
108
|
+
{ path: "/", component: <Home /> },
|
|
109
|
+
{ path: "/login", component: <Login /> },
|
|
110
|
+
// Solo agregamos estas rutas si el usuario está autenticado
|
|
111
|
+
...(isAuthenticated ? [
|
|
112
|
+
{ path: "/profile", component: <Profile /> },
|
|
113
|
+
{ path: "/admin", component: <Admin /> }
|
|
114
|
+
] : [])
|
|
115
|
+
];
|
|
116
|
+
|
|
117
|
+
return (
|
|
118
|
+
<RouterProvider routes={routes}>
|
|
119
|
+
<div>404: Page not found</div>
|
|
120
|
+
</RouterProvider>
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### Usando un Layout General
|
|
126
|
+
|
|
127
|
+
Puedes aplicar un layout común a todas tus rutas:
|
|
128
|
+
|
|
129
|
+
```jsx
|
|
130
|
+
import { RouterProvider } from "@arielgonzaguer/michi-router";
|
|
131
|
+
import MainLayout from "./layouts/MainLayout";
|
|
132
|
+
|
|
133
|
+
const routes = [
|
|
134
|
+
{ path: "/", component: <Home /> },
|
|
135
|
+
{ path: "/about", component: <About /> },
|
|
136
|
+
];
|
|
137
|
+
|
|
138
|
+
function App() {
|
|
139
|
+
return (
|
|
140
|
+
<RouterProvider routes={routes} layout={MainLayout}>
|
|
141
|
+
<div>404: Page not found</div>
|
|
142
|
+
</RouterProvider>
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Ejemplo de un componente Layout
|
|
147
|
+
function MainLayout({ children }) {
|
|
148
|
+
return (
|
|
149
|
+
<div className="layout">
|
|
150
|
+
<header>
|
|
151
|
+
<nav>
|
|
152
|
+
<Link to="/">Home</Link>
|
|
153
|
+
<Link to="/about">About</Link>
|
|
154
|
+
</nav>
|
|
155
|
+
</header>
|
|
156
|
+
<main>{children}</main>
|
|
157
|
+
<footer>Michi-router 😸</footer>
|
|
158
|
+
</div>
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
```
|
|
162
|
+
|
|
48
163
|
## API
|
|
49
164
|
|
|
50
165
|
### `<RouterProvider>`
|
|
@@ -55,6 +170,7 @@ Componente principal para el enrutamiento.
|
|
|
55
170
|
|
|
56
171
|
- `routes`: Array de objetos con `path` y `component`
|
|
57
172
|
- `children`: Elemento a mostrar cuando no hay ruta coincidente
|
|
173
|
+
- `layout`: Componente opcional que funciona como layout general para todas las rutas
|
|
58
174
|
|
|
59
175
|
### `<Link>`
|
|
60
176
|
|
|
@@ -74,6 +190,30 @@ Hook para navegación programática.
|
|
|
74
190
|
|
|
75
191
|
- Función navigate que acepta la ruta como parámetro
|
|
76
192
|
|
|
193
|
+
## Próximas características
|
|
194
|
+
|
|
195
|
+
- [ ] Soporte para rutas anidadas.
|
|
196
|
+
|
|
197
|
+
```jsx
|
|
198
|
+
const routes = [
|
|
199
|
+
{
|
|
200
|
+
path: "/dashboard",
|
|
201
|
+
component: <Dashboard />,
|
|
202
|
+
children: [
|
|
203
|
+
{ path: "/users", component: <Users /> },
|
|
204
|
+
{ path: "/settings", component: <Settings /> },
|
|
205
|
+
],
|
|
206
|
+
},
|
|
207
|
+
];
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
- [ ] Transiciones entre rutas.
|
|
211
|
+
```jsx
|
|
212
|
+
<RouterProvider routes={routes} transitions={true} transitionDuration={300}>
|
|
213
|
+
<NotFound />
|
|
214
|
+
</RouterProvider>
|
|
215
|
+
```
|
|
216
|
+
|
|
77
217
|
## Licencia
|
|
78
218
|
|
|
79
219
|
MIT
|
|
@@ -1,7 +1,21 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
2
|
import type { RouterContextType, RouterProviderProps, LinkProps } from './types';
|
|
3
3
|
declare const RouterContext: React.Context<RouterContextType>;
|
|
4
|
-
|
|
5
|
-
|
|
4
|
+
/**
|
|
5
|
+
* Proveedor principal del enrutador.
|
|
6
|
+
* @param routes - Array de rutas disponibles
|
|
7
|
+
* @param children - Contenido a mostrar cuando no hay coincidencia de ruta (404)
|
|
8
|
+
* @param layout - Componente de layout opcional para envolver todas las rutas
|
|
9
|
+
*/
|
|
10
|
+
export declare function RouterProvider({ routes, children, layout: Layout }: RouterProviderProps): React.JSX.Element;
|
|
11
|
+
/**
|
|
12
|
+
* Componente Link para navegación declarativa.
|
|
13
|
+
* Previene la recarga de página y utiliza el historial del navegador.
|
|
14
|
+
*/
|
|
15
|
+
export declare const Link: ({ to, children, className, ...rest }: LinkProps & React.AnchorHTMLAttributes<HTMLAnchorElement>) => React.JSX.Element;
|
|
16
|
+
/**
|
|
17
|
+
* Hook para acceder a la función de navegación programática.
|
|
18
|
+
* @returns Función navigate que permite cambiar de ruta
|
|
19
|
+
*/
|
|
6
20
|
export declare const useNavigate: () => (to: string) => void;
|
|
7
21
|
export { RouterContext };
|
|
@@ -1,44 +1,109 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var
|
|
3
|
-
|
|
2
|
+
var __assign = (this && this.__assign) || function () {
|
|
3
|
+
__assign = Object.assign || function(t) {
|
|
4
|
+
for (var s, i = 1, n = arguments.length; i < n; i++) {
|
|
5
|
+
s = arguments[i];
|
|
6
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
|
|
7
|
+
t[p] = s[p];
|
|
8
|
+
}
|
|
9
|
+
return t;
|
|
10
|
+
};
|
|
11
|
+
return __assign.apply(this, arguments);
|
|
12
|
+
};
|
|
13
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
14
|
+
if (k2 === undefined) k2 = k;
|
|
15
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
16
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
17
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
18
|
+
}
|
|
19
|
+
Object.defineProperty(o, k2, desc);
|
|
20
|
+
}) : (function(o, m, k, k2) {
|
|
21
|
+
if (k2 === undefined) k2 = k;
|
|
22
|
+
o[k2] = m[k];
|
|
23
|
+
}));
|
|
24
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
25
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
26
|
+
}) : function(o, v) {
|
|
27
|
+
o["default"] = v;
|
|
28
|
+
});
|
|
29
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
30
|
+
if (mod && mod.__esModule) return mod;
|
|
31
|
+
var result = {};
|
|
32
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
33
|
+
__setModuleDefault(result, mod);
|
|
34
|
+
return result;
|
|
35
|
+
};
|
|
36
|
+
var __rest = (this && this.__rest) || function (s, e) {
|
|
37
|
+
var t = {};
|
|
38
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
|
39
|
+
t[p] = s[p];
|
|
40
|
+
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
|
41
|
+
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
|
42
|
+
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
|
43
|
+
t[p[i]] = s[p[i]];
|
|
44
|
+
}
|
|
45
|
+
return t;
|
|
4
46
|
};
|
|
5
47
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
48
|
exports.RouterContext = exports.useNavigate = exports.Link = exports.RouterProvider = void 0;
|
|
7
|
-
var react_1 =
|
|
8
|
-
var react_2 = require("react");
|
|
49
|
+
var react_1 = __importStar(require("react"));
|
|
9
50
|
// Creación del contexto con un valor inicial
|
|
10
|
-
var RouterContext = (0,
|
|
11
|
-
path:
|
|
12
|
-
navigate: function () {
|
|
51
|
+
var RouterContext = (0, react_1.createContext)({
|
|
52
|
+
path: window.location.pathname,
|
|
53
|
+
navigate: function () {
|
|
54
|
+
console.warn('RouterContext usado fuera de RouterProvider');
|
|
55
|
+
}
|
|
13
56
|
});
|
|
14
57
|
exports.RouterContext = RouterContext;
|
|
58
|
+
/**
|
|
59
|
+
* Proveedor principal del enrutador.
|
|
60
|
+
* @param routes - Array de rutas disponibles
|
|
61
|
+
* @param children - Contenido a mostrar cuando no hay coincidencia de ruta (404)
|
|
62
|
+
* @param layout - Componente de layout opcional para envolver todas las rutas
|
|
63
|
+
*/
|
|
15
64
|
function RouterProvider(_a) {
|
|
16
|
-
var routes = _a.routes, children = _a.children;
|
|
17
|
-
var _b = (0,
|
|
18
|
-
(0,
|
|
65
|
+
var routes = _a.routes, children = _a.children, Layout = _a.layout;
|
|
66
|
+
var _b = (0, react_1.useState)(window.location.pathname), path = _b[0], setPath = _b[1];
|
|
67
|
+
(0, react_1.useEffect)(function () {
|
|
19
68
|
var handlePopState = function () { return setPath(window.location.pathname); };
|
|
20
69
|
window.addEventListener('popstate', handlePopState);
|
|
21
70
|
return function () { return window.removeEventListener('popstate', handlePopState); };
|
|
22
71
|
}, []);
|
|
23
|
-
var navigate = function (to) {
|
|
72
|
+
var navigate = (0, react_1.useCallback)(function (to) {
|
|
24
73
|
window.history.pushState({}, '', to);
|
|
25
74
|
setPath(to);
|
|
26
|
-
};
|
|
75
|
+
}, []);
|
|
76
|
+
// Encontrar la ruta actual
|
|
27
77
|
var currentRoute = routes.find(function (route) { return route.path === path; });
|
|
28
|
-
|
|
78
|
+
var routeContent = currentRoute ? currentRoute.component : children;
|
|
79
|
+
try {
|
|
80
|
+
return (react_1.default.createElement(RouterContext.Provider, { value: { path: path, navigate: navigate } }, Layout ? (react_1.default.createElement(Layout, null, routeContent)) : (routeContent)));
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
console.error('Error en RouterProvider:', error);
|
|
84
|
+
return react_1.default.createElement("div", null, "Error en el enrutador. Consulta la consola para m\u00E1s detalles.");
|
|
85
|
+
}
|
|
29
86
|
}
|
|
30
87
|
exports.RouterProvider = RouterProvider;
|
|
88
|
+
/**
|
|
89
|
+
* Componente Link para navegación declarativa.
|
|
90
|
+
* Previene la recarga de página y utiliza el historial del navegador.
|
|
91
|
+
*/
|
|
31
92
|
var Link = function (_a) {
|
|
32
|
-
var to = _a.to, children = _a.children, className = _a.className;
|
|
33
|
-
var navigate = (0,
|
|
34
|
-
return (react_1.default.createElement("a", { href: to, className: className,
|
|
93
|
+
var to = _a.to, children = _a.children, className = _a.className, rest = __rest(_a, ["to", "children", "className"]);
|
|
94
|
+
var navigate = (0, react_1.useContext)(RouterContext).navigate;
|
|
95
|
+
return (react_1.default.createElement("a", __assign({ href: to, className: className, onClick: function (e) {
|
|
35
96
|
e.preventDefault();
|
|
36
97
|
navigate(to);
|
|
37
|
-
} }, children));
|
|
98
|
+
} }, rest), children));
|
|
38
99
|
};
|
|
39
100
|
exports.Link = Link;
|
|
101
|
+
/**
|
|
102
|
+
* Hook para acceder a la función de navegación programática.
|
|
103
|
+
* @returns Función navigate que permite cambiar de ruta
|
|
104
|
+
*/
|
|
40
105
|
var useNavigate = function () {
|
|
41
|
-
var navigate = (0,
|
|
106
|
+
var navigate = (0, react_1.useContext)(RouterContext).navigate;
|
|
42
107
|
return navigate;
|
|
43
108
|
};
|
|
44
109
|
exports.useNavigate = useNavigate;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export { RouterProvider, Link, useNavigate } from './Michi-router';
|
|
2
|
-
export type { Route, RouterContextType, RouterProviderProps, LinkProps } from './types';
|
|
2
|
+
export type { Route, RouterContextType, RouterProviderProps, LinkProps, LayoutProps } from './types';
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
import { ReactNode } from
|
|
1
|
+
import { ReactNode } from "react";
|
|
2
|
+
export interface LayoutProps {
|
|
3
|
+
children: ReactNode;
|
|
4
|
+
}
|
|
2
5
|
export interface Route {
|
|
3
6
|
path: string;
|
|
4
7
|
component: ReactNode;
|
|
@@ -8,10 +11,16 @@ export interface RouterContextType {
|
|
|
8
11
|
navigate: (to: string) => void;
|
|
9
12
|
}
|
|
10
13
|
export interface RouterProviderProps {
|
|
11
|
-
routes:
|
|
12
|
-
|
|
14
|
+
routes: Array<{
|
|
15
|
+
path: string;
|
|
16
|
+
component: React.ReactNode;
|
|
17
|
+
}>;
|
|
18
|
+
children?: React.ReactNode;
|
|
19
|
+
layout?: React.ComponentType<{
|
|
20
|
+
children: React.ReactNode;
|
|
21
|
+
}>;
|
|
13
22
|
}
|
|
14
|
-
export interface LinkProps {
|
|
23
|
+
export interface LinkProps extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> {
|
|
15
24
|
to: string;
|
|
16
25
|
children: ReactNode;
|
|
17
26
|
className?: string;
|