jong-router 0.1.12

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) 2023 josnin
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,238 @@
1
+ # JongRouter
2
+
3
+
4
+
5
+ A lightweight and simple-to-use web components router in Vanilla JavaScript with support for guards, nested routes, page not found, passing query parameters to components, passing route parameters to components, passing route data to components, and a router link for single-page application navigation without reloading the page.
6
+
7
+
8
+
9
+ ## Features
10
+
11
+
12
+
13
+ - **Routing**: Define routes and associate them with components.
14
+
15
+ - **Guards**: Implement route guards to control navigation based on conditions. ([Example](https://github.com/josnin/jong-router/tree/main/samples/guards))
16
+
17
+ - **Nested Routes**: Create hierarchical routes for nested components. ([Example](https://github.com/josnin/jong-router/tree/main/samples/nestedroutes))
18
+
19
+ - **Page Not Found**: Handle routes that do not match any defined route. ([Example](https://github.com/josnin/jong-router/tree/main/samples/page-not-found))
20
+
21
+ - **Query Parameters**: Pass query parameters to components. ([Example](https://github.com/josnin/jong-router/tree/main/samples/query-params))
22
+
23
+ - **Route Parameters**: Extract and pass route parameters to components. ([Example](https://github.com/josnin/jong-router/tree/main/samples/route-params))
24
+
25
+ - **Route Data**: Include additional data associated with each route. ([Example](https://github.com/josnin/jong-router/tree/main/samples/route-data))
26
+
27
+ - **Router Link**: Use attr `router-link` to navigate without reloading the page. ([Example](https://github.com/josnin/jong-router/tree/main/samples/router-link))
28
+
29
+
30
+
31
+ ## Installation
32
+
33
+
34
+
35
+ Include the `jong-router.js` script in your HTML file.
36
+
37
+ ### Plug & Play, Import directly from cdn
38
+
39
+ ```html
40
+ <!-- via html -->
41
+ <script type="module" src="https://cdn.jsdelivr.net/npm/jong-router@latest/dist/jong-router.min.js"></script>
42
+
43
+ ```
44
+
45
+ ```js
46
+ // via js
47
+ // latest
48
+ import JongRouter from 'https://cdn.jsdelivr.net/npm/jong-router@latest/dist/jong-router.min.js'
49
+
50
+ // or specific version
51
+ import JongRouter from 'https://cdn.jsdelivr.net/npm/jong-router@0.1.12/dist/jong-router.min.js'
52
+
53
+ ```
54
+
55
+ ### Or Install using NPM
56
+
57
+ ```js
58
+ // or via npm
59
+ npm i jong-router
60
+ ```
61
+
62
+
63
+
64
+ ## Usage
65
+
66
+
67
+
68
+ 1. **Initialize the Router:**
69
+
70
+
71
+
72
+ ```javascript
73
+
74
+ const router = new JongRouter([
75
+
76
+ { path: '/', component: import('./components/HomeComponent') },
77
+
78
+ { path: '/about', component: import('./components/AboutComponent') },
79
+
80
+ // Add more routes as needed
81
+
82
+ ], document.getElementById('app') );
83
+
84
+
85
+
86
+ router.init();
87
+
88
+ ```
89
+
90
+
91
+
92
+ 2. **Create Components:**
93
+
94
+
95
+
96
+ Create your web components for each route.
97
+
98
+
99
+
100
+ ```javascript
101
+
102
+ // Example: HomeComponent.js
103
+
104
+ class HomeComponent extends HTMLElement {
105
+
106
+ connectedCallback() {
107
+
108
+ this.innerHTML = '<h1>Home Component</h1>';
109
+
110
+ }
111
+
112
+ }
113
+
114
+
115
+
116
+ customElements.define('home-component', HomeComponent);
117
+
118
+ ```
119
+
120
+
121
+
122
+ 3. **Navigate with Router Links:**
123
+
124
+
125
+
126
+ Use the `<router-link>` element to create navigation links.
127
+
128
+
129
+
130
+ ```html
131
+
132
+ <!-- Example: index.html -->
133
+
134
+ <a router-link href="/">Home</a>
135
+
136
+ <a router-link href="/about">About</a>
137
+
138
+ ```
139
+
140
+
141
+
142
+ 4. **Guards**
143
+
144
+
145
+
146
+ Implement guards for route conditions
147
+
148
+
149
+
150
+ ```javascript
151
+
152
+ const router = new JongRouter([
153
+
154
+ {
155
+
156
+ path: '/dashboard',
157
+
158
+ component: import('./components/DashboardComponent'),
159
+
160
+ guards: [() => isAuthenticated()],
161
+
162
+ redirect: '/login',
163
+
164
+ },
165
+
166
+ { path: '/login', component: import('./components/LoginComponent') },
167
+ // ...other routes
168
+
169
+ ]);
170
+
171
+
172
+
173
+ function isAuthenticated() {
174
+
175
+ // Your authentication logic here
176
+
177
+ return true;
178
+
179
+ }
180
+
181
+ ```
182
+
183
+
184
+
185
+ 5. **Handle Route Parameters and Query Parameters:**
186
+
187
+
188
+
189
+ Access route parameters and query parameters in your components.
190
+
191
+
192
+
193
+ ```javascript
194
+
195
+ // Example: UserComponent.js
196
+
197
+ class UserComponent extends HTMLElement {
198
+
199
+ connectedCallback() {
200
+
201
+ const routeParams = JSON.parse(this.getAttribute('route-params'));
202
+
203
+ const queryParams = JSON.parse(this.getAttribute('query-params'));
204
+
205
+
206
+
207
+ this.innerHTML = `<h1>User Details</h1>
208
+
209
+ <p>User ID: ${routeParams.id}</p>
210
+
211
+ <p>Query Param: ${queryParams.example}</p>`;
212
+
213
+ }
214
+
215
+ }
216
+
217
+
218
+
219
+ customElements.define('user-component', UserComponent);
220
+
221
+ ```
222
+
223
+ ## How to run development server?
224
+ ```
225
+ git clone git@github.com:josnin/jong-router.git
226
+ cd ~/Documents/jong-router/
227
+ npm install
228
+ npm run dev
229
+ ```
230
+
231
+ ## Help
232
+
233
+ Need help? Open an issue in: [ISSUES](https://github.com/josnin/jong-router/issues)
234
+
235
+
236
+ ## Contributing
237
+ Want to improve and add feature? Fork the repo, add your changes and send a pull request.
238
+
@@ -0,0 +1,26 @@
1
+ interface IRoute {
2
+ pattern: string;
3
+ component?: Promise<any>;
4
+ html?: string;
5
+ guards?: (() => boolean)[];
6
+ redirect?: string;
7
+ data?: any;
8
+ }
9
+ declare class JongRouter {
10
+ private routes;
11
+ private outlet;
12
+ private shadowRoot1;
13
+ constructor(routes: IRoute[], outlet: HTMLElement, shadowRoot1?: ShadowRoot | undefined);
14
+ init(): void;
15
+ private setupNavigation;
16
+ private navigate;
17
+ private loadContent;
18
+ private loadComponent;
19
+ private handleClick;
20
+ private matchRoute;
21
+ private extractQueryParams;
22
+ private extractRouteParams;
23
+ navigateTo(route: string): void;
24
+ }
25
+ export { IRoute };
26
+ export default JongRouter;
@@ -0,0 +1,2 @@
1
+ var a=class{routes;outlet;shadowRoot1;constructor(e,n,t){this.routes=e,this.outlet=n,this.shadowRoot1=t}init(){this.setupNavigation(),this.navigate()}setupNavigation(){window.addEventListener("popstate",()=>this.navigate()),document.addEventListener("click",e=>this.handleClick(e))}navigate(){let e=window.location.pathname,n=this.routes.find(o=>this.matchRoute(o.pattern,e));if(n){if(n.guards&&n.guards.every(s=>{let i=s.bind(this)();return i||(n.redirect?this.navigateTo(n.redirect):console.warn("Guard prevented navigation, and no redirect route specified!")),i===!0})===!1)return;n.component?this.loadComponent(n.component,this.extractRouteParams(n.pattern,e),n.data):n.html?this.loadContent(n.html):console.warn("no component or html route specified!");return}let t=this.routes.find(o=>o.pattern==="**");t&&(t.component?this.loadComponent(t.component,this.extractRouteParams(t.pattern,e),t.data):t.html&&this.loadContent(t.html))}loadContent(e){this.outlet.innerHTML=e}async loadComponent(e,n,t){e.then(o=>{let s=o.default,i=new s,r=this.extractQueryParams();n&&i.setAttribute("route-params",JSON.stringify(n)),t&&i.setAttribute("route-data",JSON.stringify(t)),r&&i.setAttribute("query-params",JSON.stringify(r)),i.router=this,this.outlet.innerHTML="",this.outlet.appendChild(i)}).catch(o=>{console.error(`Error loading component: ${o}`),this.outlet.innerHTML="Component not found"})}handleClick(e){let t=e.composedPath().includes(this.shadowRoot1)?e.composedPath()[0]:e.target;if((t instanceof HTMLAnchorElement||t instanceof HTMLButtonElement)&&t.hasAttribute("router-link")){e.preventDefault();let o=t.getAttribute("href");window.history.pushState({},"",o),this.navigate()}}matchRoute(e,n){let t=e.split("/").filter(s=>s!==""),o=n.split("/").filter(s=>s!=="");return t.length===o.length&&t.every((s,i)=>s.startsWith(":")||s===o[i])}extractQueryParams(){let e=window.location.search,n=new URLSearchParams(e),t={};return n.forEach((o,s)=>{t[s]=o}),t}extractRouteParams(e,n){return e.split("/").reduce((t,o,s)=>(o.startsWith(":")&&(t[o.slice(1)]=n.split("/")[s]),t),{})}navigateTo(e){window.history.pushState({},"",e),this.navigate()}},c=a;export{c as default};
2
+ //# sourceMappingURL=jong-router.min.js.map
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "jong-router",
3
+ "version": "0.1.12",
4
+ "description": "A lightweight and simple-to-use web components router in Vanilla JavaScript with support for guards, nested routes, page not found, passing query parameters to components, passing route parameters to components, passing route data to components, and a router link for single-page application navigation without reloading the page.",
5
+ "keywords": [
6
+ "jong-router",
7
+ "web components router",
8
+ "custom elements"
9
+ ],
10
+ "main": "dist/jong-router.min.js",
11
+ "types": "dist/jong-router.d.ts",
12
+ "type": "module",
13
+ "engines": {
14
+ "node": ">=18.18.2"
15
+ },
16
+ "scripts": {
17
+ "dev": "node node_modules/vite/bin/vite.js",
18
+ "test": "echo \"Error: no test specified\" && exit 1",
19
+ "clean": "rimraf src/*.js src/*/*.js samples/*.js samples/*/*.js *.d.ts src/*.d.ts src/*/*.d.ts",
20
+ "build": "npm run clean && tsc -w",
21
+ "bundle": "npx esbuild --bundle src/jong-router.js --minify --sourcemap --format=esm --outfile=dist/jong-router.min.js --target=es2022 && npm run copy",
22
+ "copy": "cp -rvf src/*.d.ts dist/."
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/josnin/jong-router.git"
27
+ },
28
+ "author": "josnin",
29
+ "license": "MIT",
30
+ "bugs": {
31
+ "url": "https://github.com/josnin/jong-router/issues"
32
+ },
33
+ "homepage": "https://github.com/josnin/jong-router#readme",
34
+ "devDependencies": {
35
+ "@types/node": "^18.11.14",
36
+ "esbuild": "^0.19.9",
37
+ "rimraf": "^4.1.2",
38
+ "typescript": "^5.3.3",
39
+ "vite": "^5.0.8"
40
+ }
41
+ }