eleva 1.0.0-alpha → 1.0.0-rc.10
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 +1 -1
- package/README.md +554 -137
- package/dist/eleva-plugins.cjs.js +3397 -0
- package/dist/eleva-plugins.cjs.js.map +1 -0
- package/dist/eleva-plugins.esm.js +3392 -0
- package/dist/eleva-plugins.esm.js.map +1 -0
- package/dist/eleva-plugins.umd.js +3403 -0
- package/dist/eleva-plugins.umd.js.map +1 -0
- package/dist/eleva-plugins.umd.min.js +3 -0
- package/dist/eleva-plugins.umd.min.js.map +1 -0
- package/dist/eleva.cjs.js +1448 -0
- package/dist/eleva.cjs.js.map +1 -0
- package/dist/eleva.d.ts +1057 -80
- package/dist/eleva.esm.js +1230 -274
- package/dist/eleva.esm.js.map +1 -1
- package/dist/eleva.umd.js +1230 -274
- package/dist/eleva.umd.js.map +1 -1
- package/dist/eleva.umd.min.js +3 -0
- package/dist/eleva.umd.min.js.map +1 -0
- package/dist/plugins/attr.umd.js +231 -0
- package/dist/plugins/attr.umd.js.map +1 -0
- package/dist/plugins/attr.umd.min.js +3 -0
- package/dist/plugins/attr.umd.min.js.map +1 -0
- package/dist/plugins/props.umd.js +711 -0
- package/dist/plugins/props.umd.js.map +1 -0
- package/dist/plugins/props.umd.min.js +3 -0
- package/dist/plugins/props.umd.min.js.map +1 -0
- package/dist/plugins/router.umd.js +1807 -0
- package/dist/plugins/router.umd.js.map +1 -0
- package/dist/plugins/router.umd.min.js +3 -0
- package/dist/plugins/router.umd.min.js.map +1 -0
- package/dist/plugins/store.umd.js +684 -0
- package/dist/plugins/store.umd.js.map +1 -0
- package/dist/plugins/store.umd.min.js +3 -0
- package/dist/plugins/store.umd.min.js.map +1 -0
- package/package.json +240 -62
- package/src/core/Eleva.js +552 -145
- package/src/modules/Emitter.js +154 -18
- package/src/modules/Renderer.js +288 -86
- package/src/modules/Signal.js +132 -13
- package/src/modules/TemplateEngine.js +153 -27
- package/src/plugins/Attr.js +252 -0
- package/src/plugins/Props.js +590 -0
- package/src/plugins/Router.js +1919 -0
- package/src/plugins/Store.js +741 -0
- package/src/plugins/index.js +40 -0
- package/types/core/Eleva.d.ts +482 -48
- package/types/core/Eleva.d.ts.map +1 -1
- package/types/modules/Emitter.d.ts +151 -20
- package/types/modules/Emitter.d.ts.map +1 -1
- package/types/modules/Renderer.d.ts +151 -12
- package/types/modules/Renderer.d.ts.map +1 -1
- package/types/modules/Signal.d.ts +130 -16
- package/types/modules/Signal.d.ts.map +1 -1
- package/types/modules/TemplateEngine.d.ts +154 -14
- package/types/modules/TemplateEngine.d.ts.map +1 -1
- package/types/plugins/Attr.d.ts +28 -0
- package/types/plugins/Attr.d.ts.map +1 -0
- package/types/plugins/Props.d.ts +48 -0
- package/types/plugins/Props.d.ts.map +1 -0
- package/types/plugins/Router.d.ts +1000 -0
- package/types/plugins/Router.d.ts.map +1 -0
- package/types/plugins/Store.d.ts +86 -0
- package/types/plugins/Store.d.ts.map +1 -0
- package/types/plugins/index.d.ts +5 -0
- package/types/plugins/index.d.ts.map +1 -0
- package/dist/eleva.min.js +0 -2
- package/dist/eleva.min.js.map +0 -1
|
@@ -0,0 +1,1919 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @typedef {import('eleva').Eleva} Eleva
|
|
5
|
+
* @typedef {import('eleva').Signal} Signal
|
|
6
|
+
* @typedef {import('eleva').ComponentDefinition} ComponentDefinition
|
|
7
|
+
* @typedef {import('eleva').Emitter} Emitter
|
|
8
|
+
* @typedef {import('eleva').MountResult} MountResult
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
// ============================================
|
|
12
|
+
// Core Type Definitions
|
|
13
|
+
// ============================================
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @typedef {'hash' | 'history' | 'query'} RouterMode
|
|
17
|
+
* The routing mode determines how the router manages URL state.
|
|
18
|
+
* - `hash`: Uses URL hash (e.g., `/#/path`) - works without server config
|
|
19
|
+
* - `history`: Uses HTML5 History API (e.g., `/path`) - requires server config
|
|
20
|
+
* - `query`: Uses query parameters (e.g., `?view=/path`) - useful for embedded apps
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @typedef {Object} RouterOptions
|
|
25
|
+
* @property {RouterMode} [mode='hash'] - The routing mode to use.
|
|
26
|
+
* @property {string} [queryParam='view'] - Query parameter name for 'query' mode.
|
|
27
|
+
* @property {string} [viewSelector='root'] - Selector for the view container element.
|
|
28
|
+
* @property {string} mount - CSS selector for the mount point element.
|
|
29
|
+
* @property {RouteDefinition[]} routes - Array of route definitions.
|
|
30
|
+
* @property {string | ComponentDefinition} [globalLayout] - Default layout for all routes.
|
|
31
|
+
* @property {NavigationGuard} [onBeforeEach] - Global navigation guard.
|
|
32
|
+
* @description Configuration options for the Router plugin.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* @typedef {Object} NavigationTarget
|
|
37
|
+
* @property {string} path - The target path (can include params like '/users/:id').
|
|
38
|
+
* @property {Record<string, string>} [params] - Route parameters to inject into the path.
|
|
39
|
+
* @property {Record<string, string>} [query] - Query parameters to append.
|
|
40
|
+
* @property {boolean} [replace=false] - Whether to replace current history entry.
|
|
41
|
+
* @property {Record<string, any>} [state] - State object to pass to history.
|
|
42
|
+
* @description Object describing a navigation target for `router.navigate()`.
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* @typedef {Object} ScrollPosition
|
|
47
|
+
* @property {number} x - Horizontal scroll position.
|
|
48
|
+
* @property {number} y - Vertical scroll position.
|
|
49
|
+
* @description Represents a saved scroll position.
|
|
50
|
+
*/
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* @typedef {Object} RouteSegment
|
|
54
|
+
* @property {'static' | 'param'} type - The segment type.
|
|
55
|
+
* @property {string} value - The segment value (for static) or empty string (for param).
|
|
56
|
+
* @property {string} [name] - The parameter name (for param segments).
|
|
57
|
+
* @description Internal representation of a parsed route path segment.
|
|
58
|
+
* @private
|
|
59
|
+
*/
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* @typedef {Object} RouteMatch
|
|
63
|
+
* @property {RouteDefinition} route - The matched route definition.
|
|
64
|
+
* @property {Record<string, string>} params - The extracted route parameters.
|
|
65
|
+
* @description Result of matching a path against route definitions.
|
|
66
|
+
* @private
|
|
67
|
+
*/
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* @typedef {Record<string, any>} RouteMeta
|
|
71
|
+
* @description Arbitrary metadata attached to routes for use in guards and components.
|
|
72
|
+
* Common properties include:
|
|
73
|
+
* - `requiresAuth: boolean` - Whether the route requires authentication
|
|
74
|
+
* - `title: string` - Page title for the route
|
|
75
|
+
* - `roles: string[]` - Required user roles
|
|
76
|
+
* @example
|
|
77
|
+
* {
|
|
78
|
+
* path: '/admin',
|
|
79
|
+
* component: AdminPage,
|
|
80
|
+
* meta: { requiresAuth: true, roles: ['admin'], title: 'Admin Dashboard' }
|
|
81
|
+
* }
|
|
82
|
+
*/
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* @typedef {Object} RouterErrorHandler
|
|
86
|
+
* @property {(error: Error, context: string, details?: Record<string, any>) => void} handle - Throws a formatted error.
|
|
87
|
+
* @property {(message: string, details?: Record<string, any>) => void} warn - Logs a warning.
|
|
88
|
+
* @property {(message: string, error: Error, details?: Record<string, any>) => void} log - Logs an error without throwing.
|
|
89
|
+
* @description Interface for the router's error handling system.
|
|
90
|
+
*/
|
|
91
|
+
|
|
92
|
+
// ============================================
|
|
93
|
+
// Event Callback Type Definitions
|
|
94
|
+
// ============================================
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* @callback NavigationContextCallback
|
|
98
|
+
* @param {NavigationContext} context - The navigation context (can be modified to block/redirect).
|
|
99
|
+
* @returns {void | Promise<void>}
|
|
100
|
+
* @description Callback for `router:beforeEach` event. Modify context to control navigation.
|
|
101
|
+
*/
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* @callback ResolveContextCallback
|
|
105
|
+
* @param {ResolveContext} context - The resolve context (can be modified to block/redirect).
|
|
106
|
+
* @returns {void | Promise<void>}
|
|
107
|
+
* @description Callback for `router:beforeResolve` and `router:afterResolve` events.
|
|
108
|
+
*/
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* @callback RenderContextCallback
|
|
112
|
+
* @param {RenderContext} context - The render context.
|
|
113
|
+
* @returns {void | Promise<void>}
|
|
114
|
+
* @description Callback for `router:beforeRender` and `router:afterRender` events.
|
|
115
|
+
*/
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* @callback ScrollContextCallback
|
|
119
|
+
* @param {ScrollContext} context - The scroll context with saved position info.
|
|
120
|
+
* @returns {void | Promise<void>}
|
|
121
|
+
* @description Callback for `router:scroll` event. Use to implement scroll behavior.
|
|
122
|
+
*/
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* @callback RouteChangeCallback
|
|
126
|
+
* @param {RouteLocation} to - The target route location.
|
|
127
|
+
* @param {RouteLocation | null} from - The source route location.
|
|
128
|
+
* @returns {void | Promise<void>}
|
|
129
|
+
* @description Callback for `router:afterEnter`, `router:afterLeave`, `router:afterEach` events.
|
|
130
|
+
*/
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* @callback RouterErrorCallback
|
|
134
|
+
* @param {Error} error - The error that occurred.
|
|
135
|
+
* @param {RouteLocation} [to] - The target route (if available).
|
|
136
|
+
* @param {RouteLocation | null} [from] - The source route (if available).
|
|
137
|
+
* @returns {void | Promise<void>}
|
|
138
|
+
* @description Callback for `router:onError` event.
|
|
139
|
+
*/
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* @callback RouterReadyCallback
|
|
143
|
+
* @param {Router} router - The router instance.
|
|
144
|
+
* @returns {void | Promise<void>}
|
|
145
|
+
* @description Callback for `router:ready` event.
|
|
146
|
+
*/
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* @callback RouteAddedCallback
|
|
150
|
+
* @param {RouteDefinition} route - The added route definition.
|
|
151
|
+
* @returns {void | Promise<void>}
|
|
152
|
+
* @description Callback for `router:routeAdded` event.
|
|
153
|
+
*/
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* @callback RouteRemovedCallback
|
|
157
|
+
* @param {RouteDefinition} route - The removed route definition.
|
|
158
|
+
* @returns {void | Promise<void>}
|
|
159
|
+
* @description Callback for `router:routeRemoved` event.
|
|
160
|
+
*/
|
|
161
|
+
|
|
162
|
+
// ============================================
|
|
163
|
+
// Core Type Definitions (continued)
|
|
164
|
+
// ============================================
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Simple error handler for the core router.
|
|
168
|
+
* Can be overridden by error handling plugins.
|
|
169
|
+
* Provides consistent error formatting and logging for router operations.
|
|
170
|
+
* @private
|
|
171
|
+
*/
|
|
172
|
+
const CoreErrorHandler = {
|
|
173
|
+
/**
|
|
174
|
+
* Handles router errors with basic formatting.
|
|
175
|
+
* @param {Error} error - The error to handle.
|
|
176
|
+
* @param {string} context - The context where the error occurred.
|
|
177
|
+
* @param {Object} details - Additional error details.
|
|
178
|
+
* @throws {Error} The formatted error.
|
|
179
|
+
*/
|
|
180
|
+
handle(error, context, details = {}) {
|
|
181
|
+
const message = `[ElevaRouter] ${context}: ${error.message}`;
|
|
182
|
+
const formattedError = new Error(message);
|
|
183
|
+
|
|
184
|
+
// Preserve original error details
|
|
185
|
+
formattedError.originalError = error;
|
|
186
|
+
formattedError.context = context;
|
|
187
|
+
formattedError.details = details;
|
|
188
|
+
|
|
189
|
+
console.error(message, { error, context, details });
|
|
190
|
+
throw formattedError;
|
|
191
|
+
},
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Logs a warning without throwing an error.
|
|
195
|
+
* @param {string} message - The warning message.
|
|
196
|
+
* @param {Object} details - Additional warning details.
|
|
197
|
+
*/
|
|
198
|
+
warn(message, details = {}) {
|
|
199
|
+
console.warn(`[ElevaRouter] ${message}`, details);
|
|
200
|
+
},
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Logs an error without throwing.
|
|
204
|
+
* @param {string} message - The error message.
|
|
205
|
+
* @param {Error} error - The original error.
|
|
206
|
+
* @param {Object} details - Additional error details.
|
|
207
|
+
*/
|
|
208
|
+
log(message, error, details = {}) {
|
|
209
|
+
console.error(`[ElevaRouter] ${message}`, { error, details });
|
|
210
|
+
},
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* @typedef {Object} RouteLocation
|
|
215
|
+
* @property {string} path - The path of the route (e.g., '/users/123').
|
|
216
|
+
* @property {Record<string, string>} query - Query parameters as key-value pairs.
|
|
217
|
+
* @property {string} fullUrl - The complete URL including hash, path, and query string.
|
|
218
|
+
* @property {Record<string, string>} params - Dynamic route parameters (e.g., `{ id: '123' }`).
|
|
219
|
+
* @property {RouteMeta} meta - Metadata associated with the matched route.
|
|
220
|
+
* @property {string} [name] - The optional name of the matched route.
|
|
221
|
+
* @property {RouteDefinition} matched - The raw route definition object that was matched.
|
|
222
|
+
* @description Represents the current or target location in the router.
|
|
223
|
+
*/
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* @typedef {boolean | string | NavigationTarget | void} NavigationGuardResult
|
|
227
|
+
* The return value of a navigation guard.
|
|
228
|
+
* - `true` or `undefined/void`: Allow navigation
|
|
229
|
+
* - `false`: Abort navigation
|
|
230
|
+
* - `string`: Redirect to path
|
|
231
|
+
* - `NavigationTarget`: Redirect with options
|
|
232
|
+
*/
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* @callback NavigationGuard
|
|
236
|
+
* @param {RouteLocation} to - The target route location.
|
|
237
|
+
* @param {RouteLocation | null} from - The source route location (null on initial navigation).
|
|
238
|
+
* @returns {NavigationGuardResult | Promise<NavigationGuardResult>}
|
|
239
|
+
* @description A function that controls navigation flow. Runs before navigation is confirmed.
|
|
240
|
+
* @example
|
|
241
|
+
* // Simple auth guard
|
|
242
|
+
* const authGuard = (to, from) => {
|
|
243
|
+
* if (to.meta.requiresAuth && !isLoggedIn()) {
|
|
244
|
+
* return '/login'; // Redirect
|
|
245
|
+
* }
|
|
246
|
+
* // Allow navigation (implicit return undefined)
|
|
247
|
+
* };
|
|
248
|
+
*/
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* @callback NavigationHook
|
|
252
|
+
* @param {RouteLocation} to - The target route location.
|
|
253
|
+
* @param {RouteLocation | null} from - The source route location.
|
|
254
|
+
* @returns {void | Promise<void>}
|
|
255
|
+
* @description A lifecycle hook for side effects. Does not affect navigation flow.
|
|
256
|
+
* @example
|
|
257
|
+
* // Analytics hook
|
|
258
|
+
* const analyticsHook = (to, from) => {
|
|
259
|
+
* analytics.trackPageView(to.path);
|
|
260
|
+
* };
|
|
261
|
+
*/
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* @typedef {Object} RouterPlugin
|
|
265
|
+
* @property {string} name - Unique plugin identifier.
|
|
266
|
+
* @property {string} [version] - Plugin version (recommended to match router version).
|
|
267
|
+
* @property {(router: Router, options?: Record<string, any>) => void} install - Installation function.
|
|
268
|
+
* @property {(router: Router) => void | Promise<void>} [destroy] - Cleanup function called on router.destroy().
|
|
269
|
+
* @description Interface for router plugins. Plugins can extend router functionality.
|
|
270
|
+
* @example
|
|
271
|
+
* const AnalyticsPlugin = {
|
|
272
|
+
* name: 'analytics',
|
|
273
|
+
* version: '1.0.0',
|
|
274
|
+
* install(router, options) {
|
|
275
|
+
* router.emitter.on('router:afterEach', (to, from) => {
|
|
276
|
+
* analytics.track(to.path);
|
|
277
|
+
* });
|
|
278
|
+
* }
|
|
279
|
+
* };
|
|
280
|
+
*/
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* @typedef {Object} NavigationContext
|
|
284
|
+
* @property {RouteLocation} to - The target route location.
|
|
285
|
+
* @property {RouteLocation | null} from - The source route location.
|
|
286
|
+
* @property {boolean} cancelled - Whether navigation has been cancelled.
|
|
287
|
+
* @property {string | {path: string} | null} redirectTo - Redirect target if navigation should redirect.
|
|
288
|
+
* @description A context object passed to navigation events that plugins can modify to control navigation flow.
|
|
289
|
+
*/
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* @typedef {Object} ResolveContext
|
|
293
|
+
* @property {RouteLocation} to - The target route location.
|
|
294
|
+
* @property {RouteLocation | null} from - The source route location.
|
|
295
|
+
* @property {RouteDefinition} route - The matched route definition.
|
|
296
|
+
* @property {ComponentDefinition | null} layoutComponent - The resolved layout component (available in afterResolve).
|
|
297
|
+
* @property {ComponentDefinition | null} pageComponent - The resolved page component (available in afterResolve).
|
|
298
|
+
* @property {boolean} cancelled - Whether navigation has been cancelled.
|
|
299
|
+
* @property {string | {path: string} | null} redirectTo - Redirect target if navigation should redirect.
|
|
300
|
+
* @description A context object passed to component resolution events.
|
|
301
|
+
*/
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* @typedef {Object} RenderContext
|
|
305
|
+
* @property {RouteLocation} to - The target route location.
|
|
306
|
+
* @property {RouteLocation | null} from - The source route location.
|
|
307
|
+
* @property {ComponentDefinition | null} layoutComponent - The layout component being rendered.
|
|
308
|
+
* @property {ComponentDefinition} pageComponent - The page component being rendered.
|
|
309
|
+
* @description A context object passed to render events.
|
|
310
|
+
*/
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* @typedef {Object} ScrollContext
|
|
314
|
+
* @property {RouteLocation} to - The target route location.
|
|
315
|
+
* @property {RouteLocation | null} from - The source route location.
|
|
316
|
+
* @property {{x: number, y: number} | null} savedPosition - The saved scroll position (if navigating via back/forward).
|
|
317
|
+
* @description A context object passed to scroll events for plugins to handle scroll behavior.
|
|
318
|
+
*/
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* @typedef {string | ComponentDefinition | (() => Promise<{default: ComponentDefinition}>)} RouteComponent
|
|
322
|
+
* A component that can be rendered for a route.
|
|
323
|
+
* - `string`: Name of a registered component
|
|
324
|
+
* - `ComponentDefinition`: Inline component definition
|
|
325
|
+
* - `() => Promise<{default: ComponentDefinition}>`: Lazy-loaded component (e.g., `() => import('./Page.js')`)
|
|
326
|
+
*/
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* @typedef {Object} RouteDefinition
|
|
330
|
+
* @property {string} path - URL path pattern. Supports:
|
|
331
|
+
* - Static: `'/about'`
|
|
332
|
+
* - Dynamic params: `'/users/:id'`
|
|
333
|
+
* - Wildcard: `'*'` (catch-all, must be last)
|
|
334
|
+
* @property {RouteComponent} component - The component to render for this route.
|
|
335
|
+
* @property {RouteComponent} [layout] - Optional layout component to wrap the route component.
|
|
336
|
+
* @property {string} [name] - Optional route name for programmatic navigation.
|
|
337
|
+
* @property {RouteMeta} [meta] - Optional metadata (auth flags, titles, etc.).
|
|
338
|
+
* @property {NavigationGuard} [beforeEnter] - Route-specific guard before entering.
|
|
339
|
+
* @property {NavigationHook} [afterEnter] - Hook after entering and component is mounted.
|
|
340
|
+
* @property {NavigationGuard} [beforeLeave] - Guard before leaving this route.
|
|
341
|
+
* @property {NavigationHook} [afterLeave] - Hook after leaving and component is unmounted.
|
|
342
|
+
* @property {RouteSegment[]} [segments] - Internal: parsed path segments (added by router).
|
|
343
|
+
* @description Defines a route in the application.
|
|
344
|
+
* @example
|
|
345
|
+
* // Static route
|
|
346
|
+
* { path: '/about', component: AboutPage }
|
|
347
|
+
*
|
|
348
|
+
* // Dynamic route with params
|
|
349
|
+
* { path: '/users/:id', component: UserPage, meta: { requiresAuth: true } }
|
|
350
|
+
*
|
|
351
|
+
* // Lazy-loaded route with layout
|
|
352
|
+
* {
|
|
353
|
+
* path: '/dashboard',
|
|
354
|
+
* component: () => import('./Dashboard.js'),
|
|
355
|
+
* layout: DashboardLayout,
|
|
356
|
+
* beforeEnter: (to, from) => isLoggedIn() || '/login'
|
|
357
|
+
* }
|
|
358
|
+
*
|
|
359
|
+
* // Catch-all 404 route (must be last)
|
|
360
|
+
* { path: '*', component: NotFoundPage }
|
|
361
|
+
*/
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* @class Router
|
|
365
|
+
* @classdesc A powerful, reactive, and flexible Router Plugin for Eleva.js.
|
|
366
|
+
* This class manages all routing logic, including state, navigation, and rendering.
|
|
367
|
+
*
|
|
368
|
+
* ## Features
|
|
369
|
+
* - Multiple routing modes (hash, history, query)
|
|
370
|
+
* - Reactive route state via Signals
|
|
371
|
+
* - Navigation guards and lifecycle hooks
|
|
372
|
+
* - Lazy-loaded components
|
|
373
|
+
* - Layout system
|
|
374
|
+
* - Plugin architecture
|
|
375
|
+
* - Scroll position management
|
|
376
|
+
*
|
|
377
|
+
* ## Events Reference
|
|
378
|
+
* | Event | Callback Type | Can Block | Description |
|
|
379
|
+
* |-------|--------------|-----------|-------------|
|
|
380
|
+
* | `router:ready` | {@link RouterReadyCallback} | No | Router initialized |
|
|
381
|
+
* | `router:beforeEach` | {@link NavigationContextCallback} | Yes | Before guards run |
|
|
382
|
+
* | `router:beforeResolve` | {@link ResolveContextCallback} | Yes | Before component loading |
|
|
383
|
+
* | `router:afterResolve` | {@link ResolveContextCallback} | No | After components loaded |
|
|
384
|
+
* | `router:afterLeave` | {@link RouteChangeCallback} | No | After leaving route |
|
|
385
|
+
* | `router:beforeRender` | {@link RenderContextCallback} | No | Before DOM update |
|
|
386
|
+
* | `router:afterRender` | {@link RenderContextCallback} | No | After DOM update |
|
|
387
|
+
* | `router:scroll` | {@link ScrollContextCallback} | No | For scroll behavior |
|
|
388
|
+
* | `router:afterEnter` | {@link RouteChangeCallback} | No | After entering route |
|
|
389
|
+
* | `router:afterEach` | {@link RouteChangeCallback} | No | Navigation complete |
|
|
390
|
+
* | `router:onError` | {@link RouterErrorCallback} | No | Navigation error |
|
|
391
|
+
* | `router:routeAdded` | {@link RouteAddedCallback} | No | Dynamic route added |
|
|
392
|
+
* | `router:routeRemoved` | {@link RouteRemovedCallback} | No | Dynamic route removed |
|
|
393
|
+
*
|
|
394
|
+
* ## Reactive Signals
|
|
395
|
+
* - `currentRoute: Signal<RouteLocation | null>` - Current route info
|
|
396
|
+
* - `previousRoute: Signal<RouteLocation | null>` - Previous route info
|
|
397
|
+
* - `currentParams: Signal<Record<string, string>>` - Current route params
|
|
398
|
+
* - `currentQuery: Signal<Record<string, string>>` - Current query params
|
|
399
|
+
* - `currentLayout: Signal<MountResult | null>` - Mounted layout instance
|
|
400
|
+
* - `currentView: Signal<MountResult | null>` - Mounted view instance
|
|
401
|
+
* - `isReady: Signal<boolean>` - Router readiness state
|
|
402
|
+
*
|
|
403
|
+
* @note Internal API Access Policy:
|
|
404
|
+
* As a core Eleva plugin, the Router may access internal Eleva APIs (prefixed with _)
|
|
405
|
+
* such as `eleva._components`. This is intentional and these internal APIs are
|
|
406
|
+
* considered stable for official plugins. Third-party plugins should avoid
|
|
407
|
+
* accessing internal APIs as they may change without notice.
|
|
408
|
+
*
|
|
409
|
+
* @example
|
|
410
|
+
* // Basic setup
|
|
411
|
+
* const router = new Router(eleva, {
|
|
412
|
+
* mode: 'hash',
|
|
413
|
+
* mount: '#app',
|
|
414
|
+
* routes: [
|
|
415
|
+
* { path: '/', component: HomePage },
|
|
416
|
+
* { path: '/users/:id', component: UserPage },
|
|
417
|
+
* { path: '*', component: NotFoundPage }
|
|
418
|
+
* ]
|
|
419
|
+
* });
|
|
420
|
+
*
|
|
421
|
+
* // Start router
|
|
422
|
+
* await router.start();
|
|
423
|
+
*
|
|
424
|
+
* // Navigate programmatically
|
|
425
|
+
* const success = await router.navigate('/users/123');
|
|
426
|
+
*
|
|
427
|
+
* // Watch for route changes
|
|
428
|
+
* router.currentRoute.watch((route) => {
|
|
429
|
+
* document.title = route?.meta?.title || 'My App';
|
|
430
|
+
* });
|
|
431
|
+
*
|
|
432
|
+
* @private
|
|
433
|
+
*/
|
|
434
|
+
class Router {
|
|
435
|
+
/**
|
|
436
|
+
* Creates an instance of the Router.
|
|
437
|
+
* @param {Eleva} eleva - The Eleva framework instance.
|
|
438
|
+
* @param {RouterOptions} options - The configuration options for the router.
|
|
439
|
+
*/
|
|
440
|
+
constructor(eleva, options = {}) {
|
|
441
|
+
/** @type {Eleva} The Eleva framework instance. */
|
|
442
|
+
this.eleva = eleva;
|
|
443
|
+
|
|
444
|
+
/** @type {RouterOptions} The merged router options. */
|
|
445
|
+
this.options = {
|
|
446
|
+
mode: "hash",
|
|
447
|
+
queryParam: "view",
|
|
448
|
+
viewSelector: "root",
|
|
449
|
+
...options,
|
|
450
|
+
};
|
|
451
|
+
|
|
452
|
+
/** @private @type {RouteDefinition[]} The processed list of route definitions. */
|
|
453
|
+
this.routes = this._processRoutes(options.routes || []);
|
|
454
|
+
|
|
455
|
+
/** @private @type {import('eleva').Emitter} The shared Eleva event emitter for global hooks. */
|
|
456
|
+
this.emitter = this.eleva.emitter;
|
|
457
|
+
|
|
458
|
+
/** @private @type {boolean} A flag indicating if the router has been started. */
|
|
459
|
+
this.isStarted = false;
|
|
460
|
+
|
|
461
|
+
/** @private @type {boolean} A flag to prevent navigation loops from history events. */
|
|
462
|
+
this._isNavigating = false;
|
|
463
|
+
|
|
464
|
+
/** @private @type {number} Counter for tracking navigation operations to prevent race conditions. */
|
|
465
|
+
this._navigationId = 0;
|
|
466
|
+
|
|
467
|
+
/** @private @type {Array<() => void>} A collection of cleanup functions for event listeners. */
|
|
468
|
+
this.eventListeners = [];
|
|
469
|
+
|
|
470
|
+
/** @type {Signal<RouteLocation | null>} A reactive signal holding the current route's information. */
|
|
471
|
+
this.currentRoute = new this.eleva.signal(null);
|
|
472
|
+
|
|
473
|
+
/** @type {Signal<RouteLocation | null>} A reactive signal holding the previous route's information. */
|
|
474
|
+
this.previousRoute = new this.eleva.signal(null);
|
|
475
|
+
|
|
476
|
+
/** @type {Signal<Object<string, string>>} A reactive signal holding the current route's parameters. */
|
|
477
|
+
this.currentParams = new this.eleva.signal({});
|
|
478
|
+
|
|
479
|
+
/** @type {Signal<Object<string, string>>} A reactive signal holding the current route's query parameters. */
|
|
480
|
+
this.currentQuery = new this.eleva.signal({});
|
|
481
|
+
|
|
482
|
+
/** @type {Signal<import('eleva').MountResult | null>} A reactive signal for the currently mounted layout instance. */
|
|
483
|
+
this.currentLayout = new this.eleva.signal(null);
|
|
484
|
+
|
|
485
|
+
/** @type {Signal<import('eleva').MountResult | null>} A reactive signal for the currently mounted view (page) instance. */
|
|
486
|
+
this.currentView = new this.eleva.signal(null);
|
|
487
|
+
|
|
488
|
+
/** @type {Signal<boolean>} A reactive signal indicating if the router is ready (started and initial navigation complete). */
|
|
489
|
+
this.isReady = new this.eleva.signal(false);
|
|
490
|
+
|
|
491
|
+
/** @private @type {Map<string, RouterPlugin>} Map of registered plugins by name. */
|
|
492
|
+
this.plugins = new Map();
|
|
493
|
+
|
|
494
|
+
/** @private @type {Array<NavigationGuard>} Array of global before-each navigation guards. */
|
|
495
|
+
this._beforeEachGuards = [];
|
|
496
|
+
|
|
497
|
+
// If onBeforeEach was provided in options, add it to the guards array
|
|
498
|
+
if (options.onBeforeEach) {
|
|
499
|
+
this._beforeEachGuards.push(options.onBeforeEach);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** @type {Object} The error handler instance. Can be overridden by plugins. */
|
|
503
|
+
this.errorHandler = CoreErrorHandler;
|
|
504
|
+
|
|
505
|
+
/** @private @type {Map<string, {x: number, y: number}>} Saved scroll positions by route path. */
|
|
506
|
+
this._scrollPositions = new Map();
|
|
507
|
+
|
|
508
|
+
this._validateOptions();
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* Validates the provided router options.
|
|
513
|
+
* @private
|
|
514
|
+
* @throws {Error} If the routing mode is invalid.
|
|
515
|
+
*/
|
|
516
|
+
_validateOptions() {
|
|
517
|
+
if (!["hash", "query", "history"].includes(this.options.mode)) {
|
|
518
|
+
this.errorHandler.handle(
|
|
519
|
+
new Error(
|
|
520
|
+
`Invalid routing mode: ${this.options.mode}. Must be "hash", "query", or "history".`
|
|
521
|
+
),
|
|
522
|
+
"Configuration validation failed"
|
|
523
|
+
);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* Pre-processes route definitions to parse their path segments for efficient matching.
|
|
529
|
+
* @private
|
|
530
|
+
* @param {RouteDefinition[]} routes - The raw route definitions.
|
|
531
|
+
* @returns {RouteDefinition[]} The processed routes.
|
|
532
|
+
*/
|
|
533
|
+
_processRoutes(routes) {
|
|
534
|
+
const processedRoutes = [];
|
|
535
|
+
for (const route of routes) {
|
|
536
|
+
try {
|
|
537
|
+
processedRoutes.push({
|
|
538
|
+
...route,
|
|
539
|
+
segments: this._parsePathIntoSegments(route.path),
|
|
540
|
+
});
|
|
541
|
+
} catch (error) {
|
|
542
|
+
this.errorHandler.warn(
|
|
543
|
+
`Invalid path in route definition "${route.path || "undefined"}": ${error.message}`,
|
|
544
|
+
{ route, error }
|
|
545
|
+
);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
return processedRoutes;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Parses a route path string into an array of static and parameter segments.
|
|
553
|
+
* @private
|
|
554
|
+
* @param {string} path - The path pattern to parse.
|
|
555
|
+
* @returns {Array<{type: 'static' | 'param', value?: string, name?: string}>} An array of segment objects.
|
|
556
|
+
* @throws {Error} If the route path is not a valid string.
|
|
557
|
+
*/
|
|
558
|
+
_parsePathIntoSegments(path) {
|
|
559
|
+
if (!path || typeof path !== "string") {
|
|
560
|
+
this.errorHandler.handle(
|
|
561
|
+
new Error("Route path must be a non-empty string"),
|
|
562
|
+
"Path parsing failed",
|
|
563
|
+
{ path }
|
|
564
|
+
);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
const normalizedPath = path.replace(/\/+/g, "/").replace(/\/$/, "") || "/";
|
|
568
|
+
|
|
569
|
+
if (normalizedPath === "/") {
|
|
570
|
+
return [];
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
return normalizedPath
|
|
574
|
+
.split("/")
|
|
575
|
+
.filter(Boolean)
|
|
576
|
+
.map((segment) => {
|
|
577
|
+
if (segment.startsWith(":")) {
|
|
578
|
+
const paramName = segment.substring(1);
|
|
579
|
+
if (!paramName) {
|
|
580
|
+
this.errorHandler.handle(
|
|
581
|
+
new Error(`Invalid parameter segment: ${segment}`),
|
|
582
|
+
"Path parsing failed",
|
|
583
|
+
{ segment, path }
|
|
584
|
+
);
|
|
585
|
+
}
|
|
586
|
+
return { type: "param", name: paramName };
|
|
587
|
+
}
|
|
588
|
+
return { type: "static", value: segment };
|
|
589
|
+
});
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* Finds the view element within a container using multiple selector strategies.
|
|
594
|
+
* @private
|
|
595
|
+
* @param {HTMLElement} container - The parent element to search within.
|
|
596
|
+
* @returns {HTMLElement} The found view element or the container itself as a fallback.
|
|
597
|
+
*/
|
|
598
|
+
_findViewElement(container) {
|
|
599
|
+
const selector = this.options.viewSelector;
|
|
600
|
+
return (
|
|
601
|
+
container.querySelector(`#${selector}`) ||
|
|
602
|
+
container.querySelector(`.${selector}`) ||
|
|
603
|
+
container.querySelector(`[data-${selector}]`) ||
|
|
604
|
+
container.querySelector(selector) ||
|
|
605
|
+
container
|
|
606
|
+
);
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/**
|
|
610
|
+
* Starts the router, initializes event listeners, and performs the initial navigation.
|
|
611
|
+
* @returns {Promise<Router>} The router instance for method chaining.
|
|
612
|
+
*
|
|
613
|
+
* @example
|
|
614
|
+
* // Basic usage
|
|
615
|
+
* await router.start();
|
|
616
|
+
*
|
|
617
|
+
* // Method chaining
|
|
618
|
+
* await router.start().then(r => r.navigate('/home'));
|
|
619
|
+
*
|
|
620
|
+
* // Reactive readiness
|
|
621
|
+
* router.isReady.watch((ready) => {
|
|
622
|
+
* if (ready) console.log('Router is ready!');
|
|
623
|
+
* });
|
|
624
|
+
*/
|
|
625
|
+
async start() {
|
|
626
|
+
if (this.isStarted) {
|
|
627
|
+
this.errorHandler.warn("Router is already started");
|
|
628
|
+
return this;
|
|
629
|
+
}
|
|
630
|
+
if (typeof window === "undefined") {
|
|
631
|
+
this.errorHandler.warn(
|
|
632
|
+
"Router start skipped: `window` object not available (SSR environment)"
|
|
633
|
+
);
|
|
634
|
+
return this;
|
|
635
|
+
}
|
|
636
|
+
if (
|
|
637
|
+
typeof document !== "undefined" &&
|
|
638
|
+
!document.querySelector(this.options.mount)
|
|
639
|
+
) {
|
|
640
|
+
this.errorHandler.warn(
|
|
641
|
+
`Mount element "${this.options.mount}" was not found in the DOM. The router will not start.`,
|
|
642
|
+
{ mountSelector: this.options.mount }
|
|
643
|
+
);
|
|
644
|
+
return this;
|
|
645
|
+
}
|
|
646
|
+
const handler = () => this._handleRouteChange();
|
|
647
|
+
if (this.options.mode === "hash") {
|
|
648
|
+
window.addEventListener("hashchange", handler);
|
|
649
|
+
this.eventListeners.push(() =>
|
|
650
|
+
window.removeEventListener("hashchange", handler)
|
|
651
|
+
);
|
|
652
|
+
} else {
|
|
653
|
+
window.addEventListener("popstate", handler);
|
|
654
|
+
this.eventListeners.push(() =>
|
|
655
|
+
window.removeEventListener("popstate", handler)
|
|
656
|
+
);
|
|
657
|
+
}
|
|
658
|
+
this.isStarted = true;
|
|
659
|
+
// Initial navigation is not a popstate event
|
|
660
|
+
await this._handleRouteChange(false);
|
|
661
|
+
// Set isReady to true after initial navigation completes
|
|
662
|
+
this.isReady.value = true;
|
|
663
|
+
await this.emitter.emit("router:ready", this);
|
|
664
|
+
return this;
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/**
|
|
668
|
+
* Stops the router and cleans up all event listeners and mounted components.
|
|
669
|
+
* @returns {Promise<void>}
|
|
670
|
+
*/
|
|
671
|
+
async destroy() {
|
|
672
|
+
if (!this.isStarted) return;
|
|
673
|
+
|
|
674
|
+
// Clean up plugins
|
|
675
|
+
for (const plugin of this.plugins.values()) {
|
|
676
|
+
if (typeof plugin.destroy === "function") {
|
|
677
|
+
try {
|
|
678
|
+
await plugin.destroy(this);
|
|
679
|
+
} catch (error) {
|
|
680
|
+
this.errorHandler.log(`Plugin ${plugin.name} destroy failed`, error);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
this.eventListeners.forEach((cleanup) => cleanup());
|
|
686
|
+
this.eventListeners = [];
|
|
687
|
+
if (this.currentLayout.value) {
|
|
688
|
+
await this.currentLayout.value.unmount();
|
|
689
|
+
}
|
|
690
|
+
this.isStarted = false;
|
|
691
|
+
this.isReady.value = false;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/**
|
|
695
|
+
* Alias for destroy(). Stops the router and cleans up all resources.
|
|
696
|
+
* Provided for semantic consistency (start/stop pattern).
|
|
697
|
+
* @returns {Promise<void>}
|
|
698
|
+
*
|
|
699
|
+
* @example
|
|
700
|
+
* await router.start();
|
|
701
|
+
* // ... later
|
|
702
|
+
* await router.stop();
|
|
703
|
+
*/
|
|
704
|
+
async stop() {
|
|
705
|
+
return this.destroy();
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* Programmatically navigates to a new route.
|
|
710
|
+
* @param {string | NavigationTarget} location - The target location as a path string or navigation target object.
|
|
711
|
+
* @param {Record<string, string>} [params] - Route parameters (only used when location is a string).
|
|
712
|
+
* @returns {Promise<boolean>} True if navigation succeeded, false if blocked by guards or failed.
|
|
713
|
+
*
|
|
714
|
+
* @example
|
|
715
|
+
* // Basic navigation
|
|
716
|
+
* await router.navigate('/users/123');
|
|
717
|
+
*
|
|
718
|
+
* // Check if navigation succeeded
|
|
719
|
+
* const success = await router.navigate('/protected');
|
|
720
|
+
* if (!success) {
|
|
721
|
+
* console.log('Navigation was blocked by a guard');
|
|
722
|
+
* }
|
|
723
|
+
*
|
|
724
|
+
* // Navigate with options
|
|
725
|
+
* await router.navigate({
|
|
726
|
+
* path: '/users/:id',
|
|
727
|
+
* params: { id: '123' },
|
|
728
|
+
* query: { tab: 'profile' },
|
|
729
|
+
* replace: true
|
|
730
|
+
* });
|
|
731
|
+
*/
|
|
732
|
+
async navigate(location, params = {}) {
|
|
733
|
+
try {
|
|
734
|
+
const target =
|
|
735
|
+
typeof location === "string" ? { path: location, params } : location;
|
|
736
|
+
let path = this._buildPath(target.path, target.params || {});
|
|
737
|
+
const query = target.query || {};
|
|
738
|
+
|
|
739
|
+
if (Object.keys(query).length > 0) {
|
|
740
|
+
const queryString = new URLSearchParams(query).toString();
|
|
741
|
+
if (queryString) path += `?${queryString}`;
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
if (this._isSameRoute(path, target.params, query)) {
|
|
745
|
+
return true; // Already at this route, consider it successful
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
const navigationSuccessful = await this._proceedWithNavigation(path);
|
|
749
|
+
|
|
750
|
+
if (navigationSuccessful) {
|
|
751
|
+
// Increment navigation ID and capture it for this navigation
|
|
752
|
+
const currentNavId = ++this._navigationId;
|
|
753
|
+
this._isNavigating = true;
|
|
754
|
+
|
|
755
|
+
const state = target.state || {};
|
|
756
|
+
const replace = target.replace || false;
|
|
757
|
+
const historyMethod = replace ? "replaceState" : "pushState";
|
|
758
|
+
|
|
759
|
+
if (this.options.mode === "hash") {
|
|
760
|
+
if (replace) {
|
|
761
|
+
const newUrl = `${window.location.pathname}${window.location.search}#${path}`;
|
|
762
|
+
window.history.replaceState(state, "", newUrl);
|
|
763
|
+
} else {
|
|
764
|
+
window.location.hash = path;
|
|
765
|
+
}
|
|
766
|
+
} else {
|
|
767
|
+
const url =
|
|
768
|
+
this.options.mode === "query" ? this._buildQueryUrl(path) : path;
|
|
769
|
+
history[historyMethod](state, "", url);
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
// Only reset the flag if no newer navigation has started
|
|
773
|
+
queueMicrotask(() => {
|
|
774
|
+
if (this._navigationId === currentNavId) {
|
|
775
|
+
this._isNavigating = false;
|
|
776
|
+
}
|
|
777
|
+
});
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
return navigationSuccessful;
|
|
781
|
+
} catch (error) {
|
|
782
|
+
this.errorHandler.log("Navigation failed", error);
|
|
783
|
+
await this.emitter.emit("router:onError", error);
|
|
784
|
+
return false;
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/**
|
|
789
|
+
* Builds a URL for query mode.
|
|
790
|
+
* @private
|
|
791
|
+
* @param {string} path - The path to set as the query parameter.
|
|
792
|
+
* @returns {string} The full URL with the updated query string.
|
|
793
|
+
*/
|
|
794
|
+
_buildQueryUrl(path) {
|
|
795
|
+
const urlParams = new URLSearchParams(window.location.search);
|
|
796
|
+
urlParams.set(this.options.queryParam, path.split("?")[0]);
|
|
797
|
+
return `${window.location.pathname}?${urlParams.toString()}`;
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
/**
|
|
801
|
+
* Checks if the target route is identical to the current route.
|
|
802
|
+
* @private
|
|
803
|
+
* @param {string} path - The target path with query string.
|
|
804
|
+
* @param {object} params - The target params.
|
|
805
|
+
* @param {object} query - The target query.
|
|
806
|
+
* @returns {boolean} - True if the routes are the same.
|
|
807
|
+
*/
|
|
808
|
+
_isSameRoute(path, params, query) {
|
|
809
|
+
const current = this.currentRoute.value;
|
|
810
|
+
if (!current) return false;
|
|
811
|
+
const [targetPath, queryString] = path.split("?");
|
|
812
|
+
const targetQuery = query || this._parseQuery(queryString || "");
|
|
813
|
+
return (
|
|
814
|
+
current.path === targetPath &&
|
|
815
|
+
JSON.stringify(current.params) === JSON.stringify(params || {}) &&
|
|
816
|
+
JSON.stringify(current.query) === JSON.stringify(targetQuery)
|
|
817
|
+
);
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
/**
|
|
821
|
+
* Injects dynamic parameters into a path string.
|
|
822
|
+
* @private
|
|
823
|
+
*/
|
|
824
|
+
_buildPath(path, params) {
|
|
825
|
+
let result = path;
|
|
826
|
+
for (const [key, value] of Object.entries(params)) {
|
|
827
|
+
// Fix: Handle special characters and ensure proper encoding
|
|
828
|
+
const encodedValue = encodeURIComponent(String(value));
|
|
829
|
+
result = result.replace(new RegExp(`:${key}\\b`, "g"), encodedValue);
|
|
830
|
+
}
|
|
831
|
+
return result;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/**
|
|
835
|
+
* The handler for browser-initiated route changes (e.g., back/forward buttons).
|
|
836
|
+
* @private
|
|
837
|
+
* @param {boolean} [isPopState=true] - Whether this is a popstate event (back/forward navigation).
|
|
838
|
+
*/
|
|
839
|
+
async _handleRouteChange(isPopState = true) {
|
|
840
|
+
if (this._isNavigating) return;
|
|
841
|
+
|
|
842
|
+
try {
|
|
843
|
+
const from = this.currentRoute.value;
|
|
844
|
+
const toLocation = this._getCurrentLocation();
|
|
845
|
+
|
|
846
|
+
const navigationSuccessful = await this._proceedWithNavigation(
|
|
847
|
+
toLocation.fullUrl,
|
|
848
|
+
isPopState
|
|
849
|
+
);
|
|
850
|
+
|
|
851
|
+
// If navigation was blocked by a guard, revert the URL change
|
|
852
|
+
if (!navigationSuccessful && from) {
|
|
853
|
+
this.navigate({ path: from.path, query: from.query, replace: true });
|
|
854
|
+
}
|
|
855
|
+
} catch (error) {
|
|
856
|
+
this.errorHandler.log("Route change handling failed", error, {
|
|
857
|
+
currentUrl: typeof window !== "undefined" ? window.location.href : "",
|
|
858
|
+
});
|
|
859
|
+
await this.emitter.emit("router:onError", error);
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
/**
|
|
864
|
+
* Manages the core navigation lifecycle. Runs guards before committing changes.
|
|
865
|
+
* Emits lifecycle events that plugins can hook into:
|
|
866
|
+
* - router:beforeEach - Before guards run (can block/redirect via context)
|
|
867
|
+
* - router:beforeResolve - Before component resolution (can block/redirect)
|
|
868
|
+
* - router:afterResolve - After components are resolved
|
|
869
|
+
* - router:beforeRender - Before DOM rendering
|
|
870
|
+
* - router:afterRender - After DOM rendering
|
|
871
|
+
* - router:scroll - After render, for scroll behavior
|
|
872
|
+
* - router:afterEnter - After entering a route
|
|
873
|
+
* - router:afterLeave - After leaving a route
|
|
874
|
+
* - router:afterEach - After navigation completes
|
|
875
|
+
*
|
|
876
|
+
* @private
|
|
877
|
+
* @param {string} fullPath - The full path (e.g., '/users/123?foo=bar') to navigate to.
|
|
878
|
+
* @param {boolean} [isPopState=false] - Whether this navigation was triggered by popstate (back/forward).
|
|
879
|
+
* @returns {Promise<boolean>} - `true` if navigation succeeded, `false` if aborted.
|
|
880
|
+
*/
|
|
881
|
+
async _proceedWithNavigation(fullPath, isPopState = false) {
|
|
882
|
+
const from = this.currentRoute.value;
|
|
883
|
+
const [path, queryString] = (fullPath || "/").split("?");
|
|
884
|
+
const toLocation = {
|
|
885
|
+
path: path.startsWith("/") ? path : `/${path}`,
|
|
886
|
+
query: this._parseQuery(queryString),
|
|
887
|
+
fullUrl: fullPath,
|
|
888
|
+
};
|
|
889
|
+
|
|
890
|
+
let toMatch = this._matchRoute(toLocation.path);
|
|
891
|
+
|
|
892
|
+
if (!toMatch) {
|
|
893
|
+
const notFoundRoute = this.routes.find((route) => route.path === "*");
|
|
894
|
+
if (notFoundRoute) {
|
|
895
|
+
toMatch = {
|
|
896
|
+
route: notFoundRoute,
|
|
897
|
+
params: {
|
|
898
|
+
pathMatch: decodeURIComponent(toLocation.path.substring(1)),
|
|
899
|
+
},
|
|
900
|
+
};
|
|
901
|
+
} else {
|
|
902
|
+
await this.emitter.emit(
|
|
903
|
+
"router:onError",
|
|
904
|
+
new Error(`Route not found: ${toLocation.path}`),
|
|
905
|
+
toLocation,
|
|
906
|
+
from
|
|
907
|
+
);
|
|
908
|
+
return false;
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
const to = {
|
|
913
|
+
...toLocation,
|
|
914
|
+
params: toMatch.params,
|
|
915
|
+
meta: toMatch.route.meta || {},
|
|
916
|
+
name: toMatch.route.name,
|
|
917
|
+
matched: toMatch.route,
|
|
918
|
+
};
|
|
919
|
+
|
|
920
|
+
try {
|
|
921
|
+
// 1. Run all *pre-navigation* guards.
|
|
922
|
+
const canNavigate = await this._runGuards(to, from, toMatch.route);
|
|
923
|
+
if (!canNavigate) return false;
|
|
924
|
+
|
|
925
|
+
// 2. Save current scroll position before navigating away
|
|
926
|
+
if (from && typeof window !== "undefined") {
|
|
927
|
+
this._scrollPositions.set(from.path, {
|
|
928
|
+
x: window.scrollX || window.pageXOffset || 0,
|
|
929
|
+
y: window.scrollY || window.pageYOffset || 0,
|
|
930
|
+
});
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
// 3. Emit beforeResolve event - plugins can show loading indicators
|
|
934
|
+
/** @type {ResolveContext} */
|
|
935
|
+
const resolveContext = {
|
|
936
|
+
to,
|
|
937
|
+
from,
|
|
938
|
+
route: toMatch.route,
|
|
939
|
+
layoutComponent: null,
|
|
940
|
+
pageComponent: null,
|
|
941
|
+
cancelled: false,
|
|
942
|
+
redirectTo: null,
|
|
943
|
+
};
|
|
944
|
+
await this.emitter.emit("router:beforeResolve", resolveContext);
|
|
945
|
+
|
|
946
|
+
// Check if resolution was cancelled or redirected
|
|
947
|
+
if (resolveContext.cancelled) return false;
|
|
948
|
+
if (resolveContext.redirectTo) {
|
|
949
|
+
this.navigate(resolveContext.redirectTo);
|
|
950
|
+
return false;
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// 4. Resolve async components *before* touching the DOM.
|
|
954
|
+
const { layoutComponent, pageComponent } = await this._resolveComponents(
|
|
955
|
+
toMatch.route
|
|
956
|
+
);
|
|
957
|
+
|
|
958
|
+
// 5. Emit afterResolve event - plugins can hide loading indicators
|
|
959
|
+
resolveContext.layoutComponent = layoutComponent;
|
|
960
|
+
resolveContext.pageComponent = pageComponent;
|
|
961
|
+
await this.emitter.emit("router:afterResolve", resolveContext);
|
|
962
|
+
|
|
963
|
+
// 6. Unmount the previous view/layout.
|
|
964
|
+
if (from) {
|
|
965
|
+
const toLayout = toMatch.route.layout || this.options.globalLayout;
|
|
966
|
+
const fromLayout = from.matched.layout || this.options.globalLayout;
|
|
967
|
+
|
|
968
|
+
const tryUnmount = async (instance) => {
|
|
969
|
+
if (!instance) return;
|
|
970
|
+
|
|
971
|
+
try {
|
|
972
|
+
await instance.unmount();
|
|
973
|
+
} catch (error) {
|
|
974
|
+
this.errorHandler.warn("Error during component unmount", {
|
|
975
|
+
error,
|
|
976
|
+
instance,
|
|
977
|
+
});
|
|
978
|
+
}
|
|
979
|
+
};
|
|
980
|
+
|
|
981
|
+
if (toLayout !== fromLayout) {
|
|
982
|
+
await tryUnmount(this.currentLayout.value);
|
|
983
|
+
this.currentLayout.value = null;
|
|
984
|
+
} else {
|
|
985
|
+
await tryUnmount(this.currentView.value);
|
|
986
|
+
this.currentView.value = null;
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
// Call `afterLeave` hook *after* the old component has been unmounted.
|
|
990
|
+
if (from.matched.afterLeave) {
|
|
991
|
+
await from.matched.afterLeave(to, from);
|
|
992
|
+
}
|
|
993
|
+
await this.emitter.emit("router:afterLeave", to, from);
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
// 7. Update reactive state.
|
|
997
|
+
this.previousRoute.value = from;
|
|
998
|
+
this.currentRoute.value = to;
|
|
999
|
+
this.currentParams.value = to.params || {};
|
|
1000
|
+
this.currentQuery.value = to.query || {};
|
|
1001
|
+
|
|
1002
|
+
// 8. Emit beforeRender event - plugins can add transitions
|
|
1003
|
+
/** @type {RenderContext} */
|
|
1004
|
+
const renderContext = {
|
|
1005
|
+
to,
|
|
1006
|
+
from,
|
|
1007
|
+
layoutComponent,
|
|
1008
|
+
pageComponent,
|
|
1009
|
+
};
|
|
1010
|
+
await this.emitter.emit("router:beforeRender", renderContext);
|
|
1011
|
+
|
|
1012
|
+
// 9. Render the new components.
|
|
1013
|
+
await this._render(layoutComponent, pageComponent, to);
|
|
1014
|
+
|
|
1015
|
+
// 10. Emit afterRender event - plugins can trigger animations
|
|
1016
|
+
await this.emitter.emit("router:afterRender", renderContext);
|
|
1017
|
+
|
|
1018
|
+
// 11. Emit scroll event - plugins can handle scroll restoration
|
|
1019
|
+
/** @type {ScrollContext} */
|
|
1020
|
+
const scrollContext = {
|
|
1021
|
+
to,
|
|
1022
|
+
from,
|
|
1023
|
+
savedPosition: isPopState
|
|
1024
|
+
? this._scrollPositions.get(to.path) || null
|
|
1025
|
+
: null,
|
|
1026
|
+
};
|
|
1027
|
+
await this.emitter.emit("router:scroll", scrollContext);
|
|
1028
|
+
|
|
1029
|
+
// 12. Run post-navigation hooks.
|
|
1030
|
+
if (toMatch.route.afterEnter) {
|
|
1031
|
+
await toMatch.route.afterEnter(to, from);
|
|
1032
|
+
}
|
|
1033
|
+
await this.emitter.emit("router:afterEnter", to, from);
|
|
1034
|
+
await this.emitter.emit("router:afterEach", to, from);
|
|
1035
|
+
|
|
1036
|
+
return true;
|
|
1037
|
+
} catch (error) {
|
|
1038
|
+
this.errorHandler.log("Error during navigation", error, { to, from });
|
|
1039
|
+
await this.emitter.emit("router:onError", error, to, from);
|
|
1040
|
+
return false;
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
/**
|
|
1045
|
+
* Executes all applicable navigation guards for a transition in order.
|
|
1046
|
+
* Guards are executed in the following order:
|
|
1047
|
+
* 1. Global beforeEach event (emitter-based, can block via context)
|
|
1048
|
+
* 2. Global beforeEach guards (registered via onBeforeEach)
|
|
1049
|
+
* 3. Route-specific beforeLeave guard (from the route being left)
|
|
1050
|
+
* 4. Route-specific beforeEnter guard (from the route being entered)
|
|
1051
|
+
*
|
|
1052
|
+
* @private
|
|
1053
|
+
* @param {RouteLocation} to - The target route location.
|
|
1054
|
+
* @param {RouteLocation | null} from - The current route location (null on initial navigation).
|
|
1055
|
+
* @param {RouteDefinition} route - The matched route definition.
|
|
1056
|
+
* @returns {Promise<boolean>} - `false` if navigation should be aborted.
|
|
1057
|
+
*/
|
|
1058
|
+
async _runGuards(to, from, route) {
|
|
1059
|
+
// Create navigation context that plugins can modify to block navigation
|
|
1060
|
+
/** @type {NavigationContext} */
|
|
1061
|
+
const navContext = {
|
|
1062
|
+
to,
|
|
1063
|
+
from,
|
|
1064
|
+
cancelled: false,
|
|
1065
|
+
redirectTo: null,
|
|
1066
|
+
};
|
|
1067
|
+
|
|
1068
|
+
// Emit beforeEach event with context - plugins can block by modifying context
|
|
1069
|
+
await this.emitter.emit("router:beforeEach", navContext);
|
|
1070
|
+
|
|
1071
|
+
// Check if navigation was cancelled or redirected by event listeners
|
|
1072
|
+
if (navContext.cancelled) return false;
|
|
1073
|
+
if (navContext.redirectTo) {
|
|
1074
|
+
this.navigate(navContext.redirectTo);
|
|
1075
|
+
return false;
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
// Collect all guards in execution order
|
|
1079
|
+
const guards = [
|
|
1080
|
+
...this._beforeEachGuards,
|
|
1081
|
+
...(from && from.matched.beforeLeave ? [from.matched.beforeLeave] : []),
|
|
1082
|
+
...(route.beforeEnter ? [route.beforeEnter] : []),
|
|
1083
|
+
];
|
|
1084
|
+
|
|
1085
|
+
for (const guard of guards) {
|
|
1086
|
+
const result = await guard(to, from);
|
|
1087
|
+
if (result === false) return false;
|
|
1088
|
+
if (typeof result === "string" || typeof result === "object") {
|
|
1089
|
+
this.navigate(result);
|
|
1090
|
+
return false;
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
return true;
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
/**
|
|
1097
|
+
* Resolves a string component definition to a component object.
|
|
1098
|
+
* @private
|
|
1099
|
+
* @param {string} def - The component name to resolve.
|
|
1100
|
+
* @returns {ComponentDefinition} The resolved component.
|
|
1101
|
+
* @throws {Error} If the component is not registered.
|
|
1102
|
+
*
|
|
1103
|
+
* @note Core plugins (Router, Attr, Props, Store) may access eleva._components
|
|
1104
|
+
* directly. This is intentional and stable for official Eleva plugins shipped
|
|
1105
|
+
* with the framework. Third-party plugins should use eleva.component() for
|
|
1106
|
+
* registration and avoid direct access to internal APIs.
|
|
1107
|
+
*/
|
|
1108
|
+
_resolveStringComponent(def) {
|
|
1109
|
+
const componentDef = this.eleva._components.get(def);
|
|
1110
|
+
if (!componentDef) {
|
|
1111
|
+
this.errorHandler.handle(
|
|
1112
|
+
new Error(`Component "${def}" not registered.`),
|
|
1113
|
+
"Component resolution failed",
|
|
1114
|
+
{
|
|
1115
|
+
componentName: def,
|
|
1116
|
+
availableComponents: Array.from(this.eleva._components.keys()),
|
|
1117
|
+
}
|
|
1118
|
+
);
|
|
1119
|
+
}
|
|
1120
|
+
return componentDef;
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
/**
|
|
1124
|
+
* Resolves a function component definition to a component object.
|
|
1125
|
+
* @private
|
|
1126
|
+
* @param {Function} def - The function to resolve.
|
|
1127
|
+
* @returns {Promise<ComponentDefinition>} The resolved component.
|
|
1128
|
+
* @throws {Error} If the function fails to load the component.
|
|
1129
|
+
*/
|
|
1130
|
+
async _resolveFunctionComponent(def) {
|
|
1131
|
+
try {
|
|
1132
|
+
const funcStr = def.toString();
|
|
1133
|
+
const isAsyncImport =
|
|
1134
|
+
funcStr.includes("import(") || funcStr.startsWith("() =>");
|
|
1135
|
+
|
|
1136
|
+
const result = await def();
|
|
1137
|
+
return isAsyncImport ? result.default || result : result;
|
|
1138
|
+
} catch (error) {
|
|
1139
|
+
this.errorHandler.handle(
|
|
1140
|
+
new Error(`Failed to load async component: ${error.message}`),
|
|
1141
|
+
"Component resolution failed",
|
|
1142
|
+
{ function: def.toString(), error }
|
|
1143
|
+
);
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
/**
|
|
1148
|
+
* Validates a component definition object.
|
|
1149
|
+
* @private
|
|
1150
|
+
* @param {any} def - The component definition to validate.
|
|
1151
|
+
* @returns {ComponentDefinition} The validated component.
|
|
1152
|
+
* @throws {Error} If the component definition is invalid.
|
|
1153
|
+
*/
|
|
1154
|
+
_validateComponentDefinition(def) {
|
|
1155
|
+
if (!def || typeof def !== "object") {
|
|
1156
|
+
this.errorHandler.handle(
|
|
1157
|
+
new Error(`Invalid component definition: ${typeof def}`),
|
|
1158
|
+
"Component validation failed",
|
|
1159
|
+
{ definition: def }
|
|
1160
|
+
);
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
if (
|
|
1164
|
+
typeof def.template !== "function" &&
|
|
1165
|
+
typeof def.template !== "string"
|
|
1166
|
+
) {
|
|
1167
|
+
this.errorHandler.handle(
|
|
1168
|
+
new Error("Component missing template property"),
|
|
1169
|
+
"Component validation failed",
|
|
1170
|
+
{ definition: def }
|
|
1171
|
+
);
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
return def;
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
/**
|
|
1178
|
+
* Resolves a component definition to a component object.
|
|
1179
|
+
* @private
|
|
1180
|
+
* @param {any} def - The component definition to resolve.
|
|
1181
|
+
* @returns {Promise<ComponentDefinition | null>} The resolved component or null.
|
|
1182
|
+
*/
|
|
1183
|
+
async _resolveComponent(def) {
|
|
1184
|
+
if (def === null || def === undefined) {
|
|
1185
|
+
return null;
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
if (typeof def === "string") {
|
|
1189
|
+
return this._resolveStringComponent(def);
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
if (typeof def === "function") {
|
|
1193
|
+
return await this._resolveFunctionComponent(def);
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
if (def && typeof def === "object") {
|
|
1197
|
+
return this._validateComponentDefinition(def);
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
this.errorHandler.handle(
|
|
1201
|
+
new Error(`Invalid component definition: ${typeof def}`),
|
|
1202
|
+
"Component resolution failed",
|
|
1203
|
+
{ definition: def }
|
|
1204
|
+
);
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
/**
|
|
1208
|
+
* Asynchronously resolves the layout and page components for a route.
|
|
1209
|
+
* @private
|
|
1210
|
+
* @param {RouteDefinition} route - The route to resolve components for.
|
|
1211
|
+
* @returns {Promise<{layoutComponent: ComponentDefinition | null, pageComponent: ComponentDefinition}>}
|
|
1212
|
+
*/
|
|
1213
|
+
async _resolveComponents(route) {
|
|
1214
|
+
const effectiveLayout = route.layout || this.options.globalLayout;
|
|
1215
|
+
|
|
1216
|
+
try {
|
|
1217
|
+
const [layoutComponent, pageComponent] = await Promise.all([
|
|
1218
|
+
this._resolveComponent(effectiveLayout),
|
|
1219
|
+
this._resolveComponent(route.component),
|
|
1220
|
+
]);
|
|
1221
|
+
|
|
1222
|
+
if (!pageComponent) {
|
|
1223
|
+
this.errorHandler.handle(
|
|
1224
|
+
new Error(
|
|
1225
|
+
`Page component is null or undefined for route: ${route.path}`
|
|
1226
|
+
),
|
|
1227
|
+
"Component resolution failed",
|
|
1228
|
+
{ route: route.path }
|
|
1229
|
+
);
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
return { layoutComponent, pageComponent };
|
|
1233
|
+
} catch (error) {
|
|
1234
|
+
this.errorHandler.log(
|
|
1235
|
+
`Error resolving components for route ${route.path}`,
|
|
1236
|
+
error,
|
|
1237
|
+
{ route: route.path }
|
|
1238
|
+
);
|
|
1239
|
+
throw error;
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
/**
|
|
1244
|
+
* Renders the components for the current route into the DOM.
|
|
1245
|
+
* @private
|
|
1246
|
+
* @param {ComponentDefinition | null} layoutComponent - The pre-loaded layout component.
|
|
1247
|
+
* @param {ComponentDefinition} pageComponent - The pre-loaded page component.
|
|
1248
|
+
*/
|
|
1249
|
+
async _render(layoutComponent, pageComponent) {
|
|
1250
|
+
const mountEl = document.querySelector(this.options.mount);
|
|
1251
|
+
if (!mountEl) {
|
|
1252
|
+
this.errorHandler.handle(
|
|
1253
|
+
new Error(`Mount element "${this.options.mount}" not found.`),
|
|
1254
|
+
{ mountSelector: this.options.mount }
|
|
1255
|
+
);
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
if (layoutComponent) {
|
|
1259
|
+
const layoutInstance = await this.eleva.mount(
|
|
1260
|
+
mountEl,
|
|
1261
|
+
this._wrapComponentWithChildren(layoutComponent)
|
|
1262
|
+
);
|
|
1263
|
+
this.currentLayout.value = layoutInstance;
|
|
1264
|
+
const viewEl = this._findViewElement(layoutInstance.container);
|
|
1265
|
+
const viewInstance = await this.eleva.mount(
|
|
1266
|
+
viewEl,
|
|
1267
|
+
this._wrapComponentWithChildren(pageComponent)
|
|
1268
|
+
);
|
|
1269
|
+
this.currentView.value = viewInstance;
|
|
1270
|
+
} else {
|
|
1271
|
+
const viewInstance = await this.eleva.mount(
|
|
1272
|
+
mountEl,
|
|
1273
|
+
this._wrapComponentWithChildren(pageComponent)
|
|
1274
|
+
);
|
|
1275
|
+
this.currentView.value = viewInstance;
|
|
1276
|
+
this.currentLayout.value = null;
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
/**
|
|
1281
|
+
* Creates a getter function for router context properties.
|
|
1282
|
+
* @private
|
|
1283
|
+
* @param {string} property - The property name to access.
|
|
1284
|
+
* @param {any} defaultValue - The default value if property is undefined.
|
|
1285
|
+
* @returns {Function} A getter function.
|
|
1286
|
+
*/
|
|
1287
|
+
_createRouteGetter(property, defaultValue) {
|
|
1288
|
+
return () => this.currentRoute.value?.[property] ?? defaultValue;
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
/**
|
|
1292
|
+
* Wraps a component definition to inject router-specific context into its setup function.
|
|
1293
|
+
* @private
|
|
1294
|
+
* @param {ComponentDefinition} component - The component to wrap.
|
|
1295
|
+
* @returns {ComponentDefinition} The wrapped component definition.
|
|
1296
|
+
*/
|
|
1297
|
+
_wrapComponent(component) {
|
|
1298
|
+
const originalSetup = component.setup;
|
|
1299
|
+
const self = this;
|
|
1300
|
+
|
|
1301
|
+
return {
|
|
1302
|
+
...component,
|
|
1303
|
+
async setup(ctx) {
|
|
1304
|
+
ctx.router = {
|
|
1305
|
+
navigate: self.navigate.bind(self),
|
|
1306
|
+
current: self.currentRoute,
|
|
1307
|
+
previous: self.previousRoute,
|
|
1308
|
+
|
|
1309
|
+
// Route property getters
|
|
1310
|
+
get params() {
|
|
1311
|
+
return self._createRouteGetter("params", {})();
|
|
1312
|
+
},
|
|
1313
|
+
get query() {
|
|
1314
|
+
return self._createRouteGetter("query", {})();
|
|
1315
|
+
},
|
|
1316
|
+
get path() {
|
|
1317
|
+
return self._createRouteGetter("path", "/")();
|
|
1318
|
+
},
|
|
1319
|
+
get fullUrl() {
|
|
1320
|
+
return self._createRouteGetter("fullUrl", window.location.href)();
|
|
1321
|
+
},
|
|
1322
|
+
get meta() {
|
|
1323
|
+
return self._createRouteGetter("meta", {})();
|
|
1324
|
+
},
|
|
1325
|
+
};
|
|
1326
|
+
|
|
1327
|
+
return originalSetup ? await originalSetup(ctx) : {};
|
|
1328
|
+
},
|
|
1329
|
+
};
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
/**
|
|
1333
|
+
* Recursively wraps all child components to ensure they have access to router context.
|
|
1334
|
+
* @private
|
|
1335
|
+
* @param {ComponentDefinition | string} component - The component to wrap (can be a definition object or a registered component name).
|
|
1336
|
+
* @returns {ComponentDefinition | string} The wrapped component definition or the original string reference.
|
|
1337
|
+
*/
|
|
1338
|
+
_wrapComponentWithChildren(component) {
|
|
1339
|
+
// If the component is a string (registered component name), return as-is
|
|
1340
|
+
// The router context will be injected when the component is resolved during mounting
|
|
1341
|
+
if (typeof component === "string") {
|
|
1342
|
+
return component;
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
// If not a valid component object, return as-is
|
|
1346
|
+
if (!component || typeof component !== "object") {
|
|
1347
|
+
return component;
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
const wrappedComponent = this._wrapComponent(component);
|
|
1351
|
+
|
|
1352
|
+
// If the component has children, wrap them too
|
|
1353
|
+
if (
|
|
1354
|
+
wrappedComponent.children &&
|
|
1355
|
+
typeof wrappedComponent.children === "object"
|
|
1356
|
+
) {
|
|
1357
|
+
const wrappedChildren = {};
|
|
1358
|
+
for (const [selector, childComponent] of Object.entries(
|
|
1359
|
+
wrappedComponent.children
|
|
1360
|
+
)) {
|
|
1361
|
+
wrappedChildren[selector] =
|
|
1362
|
+
this._wrapComponentWithChildren(childComponent);
|
|
1363
|
+
}
|
|
1364
|
+
wrappedComponent.children = wrappedChildren;
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
return wrappedComponent;
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
/**
|
|
1371
|
+
* Gets the current location information from the browser's window object.
|
|
1372
|
+
* @private
|
|
1373
|
+
* @returns {Omit<RouteLocation, 'params' | 'meta' | 'name' | 'matched'>}
|
|
1374
|
+
*/
|
|
1375
|
+
_getCurrentLocation() {
|
|
1376
|
+
if (typeof window === "undefined")
|
|
1377
|
+
return { path: "/", query: {}, fullUrl: "" };
|
|
1378
|
+
let path, queryString, fullUrl;
|
|
1379
|
+
switch (this.options.mode) {
|
|
1380
|
+
case "hash":
|
|
1381
|
+
fullUrl = window.location.hash.slice(1) || "/";
|
|
1382
|
+
[path, queryString] = fullUrl.split("?");
|
|
1383
|
+
break;
|
|
1384
|
+
case "query":
|
|
1385
|
+
const urlParams = new URLSearchParams(window.location.search);
|
|
1386
|
+
path = urlParams.get(this.options.queryParam) || "/";
|
|
1387
|
+
queryString = window.location.search.slice(1);
|
|
1388
|
+
fullUrl = path;
|
|
1389
|
+
break;
|
|
1390
|
+
default: // 'history' mode
|
|
1391
|
+
path = window.location.pathname || "/";
|
|
1392
|
+
queryString = window.location.search.slice(1);
|
|
1393
|
+
fullUrl = `${path}${queryString ? "?" + queryString : ""}`;
|
|
1394
|
+
}
|
|
1395
|
+
return {
|
|
1396
|
+
path: path.startsWith("/") ? path : `/${path}`,
|
|
1397
|
+
query: this._parseQuery(queryString),
|
|
1398
|
+
fullUrl,
|
|
1399
|
+
};
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
/**
|
|
1403
|
+
* Parses a query string into a key-value object.
|
|
1404
|
+
* @private
|
|
1405
|
+
*/
|
|
1406
|
+
_parseQuery(queryString) {
|
|
1407
|
+
const query = {};
|
|
1408
|
+
if (queryString) {
|
|
1409
|
+
new URLSearchParams(queryString).forEach((value, key) => {
|
|
1410
|
+
query[key] = value;
|
|
1411
|
+
});
|
|
1412
|
+
}
|
|
1413
|
+
return query;
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
/**
|
|
1417
|
+
* Matches a given path against the registered routes.
|
|
1418
|
+
* @private
|
|
1419
|
+
* @param {string} path - The path to match.
|
|
1420
|
+
* @returns {{route: RouteDefinition, params: Object<string, string>} | null} The matched route and its params, or null.
|
|
1421
|
+
*/
|
|
1422
|
+
_matchRoute(path) {
|
|
1423
|
+
const pathSegments = path.split("/").filter(Boolean);
|
|
1424
|
+
|
|
1425
|
+
for (const route of this.routes) {
|
|
1426
|
+
// Handle the root path as a special case.
|
|
1427
|
+
if (route.path === "/") {
|
|
1428
|
+
if (pathSegments.length === 0) return { route, params: {} };
|
|
1429
|
+
continue;
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
if (route.segments.length !== pathSegments.length) continue;
|
|
1433
|
+
|
|
1434
|
+
const params = {};
|
|
1435
|
+
let isMatch = true;
|
|
1436
|
+
for (let i = 0; i < route.segments.length; i++) {
|
|
1437
|
+
const routeSegment = route.segments[i];
|
|
1438
|
+
const pathSegment = pathSegments[i];
|
|
1439
|
+
if (routeSegment.type === "param") {
|
|
1440
|
+
params[routeSegment.name] = decodeURIComponent(pathSegment);
|
|
1441
|
+
} else if (routeSegment.value !== pathSegment) {
|
|
1442
|
+
isMatch = false;
|
|
1443
|
+
break;
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
if (isMatch) return { route, params };
|
|
1447
|
+
}
|
|
1448
|
+
return null;
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
// ============================================
|
|
1452
|
+
// Dynamic Route Management API
|
|
1453
|
+
// ============================================
|
|
1454
|
+
|
|
1455
|
+
/**
|
|
1456
|
+
* Adds a new route dynamically at runtime.
|
|
1457
|
+
* The route will be processed and available for navigation immediately.
|
|
1458
|
+
*
|
|
1459
|
+
* @param {RouteDefinition} route - The route definition to add.
|
|
1460
|
+
* @param {RouteDefinition} [parentRoute] - Optional parent route to add as a child (not yet implemented).
|
|
1461
|
+
* @returns {() => void} A function to remove the added route.
|
|
1462
|
+
*
|
|
1463
|
+
* @example
|
|
1464
|
+
* // Add a route dynamically
|
|
1465
|
+
* const removeRoute = router.addRoute({
|
|
1466
|
+
* path: '/dynamic',
|
|
1467
|
+
* component: DynamicPage,
|
|
1468
|
+
* meta: { title: 'Dynamic Page' }
|
|
1469
|
+
* });
|
|
1470
|
+
*
|
|
1471
|
+
* // Later, remove the route
|
|
1472
|
+
* removeRoute();
|
|
1473
|
+
*/
|
|
1474
|
+
addRoute(route, parentRoute = null) {
|
|
1475
|
+
if (!route || !route.path) {
|
|
1476
|
+
this.errorHandler.warn("Invalid route definition: missing path", {
|
|
1477
|
+
route,
|
|
1478
|
+
});
|
|
1479
|
+
return () => {};
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
// Check if route already exists
|
|
1483
|
+
if (this.hasRoute(route.path)) {
|
|
1484
|
+
this.errorHandler.warn(`Route "${route.path}" already exists`, { route });
|
|
1485
|
+
return () => {};
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
// Process the route (parse segments)
|
|
1489
|
+
const processedRoute = {
|
|
1490
|
+
...route,
|
|
1491
|
+
segments: this._parsePathIntoSegments(route.path),
|
|
1492
|
+
};
|
|
1493
|
+
|
|
1494
|
+
// Add to routes array (before wildcard if exists)
|
|
1495
|
+
const wildcardIndex = this.routes.findIndex((r) => r.path === "*");
|
|
1496
|
+
if (wildcardIndex !== -1) {
|
|
1497
|
+
this.routes.splice(wildcardIndex, 0, processedRoute);
|
|
1498
|
+
} else {
|
|
1499
|
+
this.routes.push(processedRoute);
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
// Emit event for plugins
|
|
1503
|
+
this.emitter.emit("router:routeAdded", processedRoute);
|
|
1504
|
+
|
|
1505
|
+
// Return removal function
|
|
1506
|
+
return () => this.removeRoute(route.path);
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
/**
|
|
1510
|
+
* Removes a route by its path.
|
|
1511
|
+
*
|
|
1512
|
+
* @param {string} path - The path of the route to remove.
|
|
1513
|
+
* @returns {boolean} True if the route was removed, false if not found.
|
|
1514
|
+
*
|
|
1515
|
+
* @example
|
|
1516
|
+
* router.removeRoute('/dynamic');
|
|
1517
|
+
*/
|
|
1518
|
+
removeRoute(path) {
|
|
1519
|
+
const index = this.routes.findIndex((r) => r.path === path);
|
|
1520
|
+
if (index === -1) {
|
|
1521
|
+
return false;
|
|
1522
|
+
}
|
|
1523
|
+
|
|
1524
|
+
const [removedRoute] = this.routes.splice(index, 1);
|
|
1525
|
+
|
|
1526
|
+
// Emit event for plugins
|
|
1527
|
+
this.emitter.emit("router:routeRemoved", removedRoute);
|
|
1528
|
+
|
|
1529
|
+
return true;
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
/**
|
|
1533
|
+
* Checks if a route with the given path exists.
|
|
1534
|
+
*
|
|
1535
|
+
* @param {string} path - The path to check.
|
|
1536
|
+
* @returns {boolean} True if the route exists.
|
|
1537
|
+
*
|
|
1538
|
+
* @example
|
|
1539
|
+
* if (router.hasRoute('/users/:id')) {
|
|
1540
|
+
* console.log('User route exists');
|
|
1541
|
+
* }
|
|
1542
|
+
*/
|
|
1543
|
+
hasRoute(path) {
|
|
1544
|
+
return this.routes.some((r) => r.path === path);
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
/**
|
|
1548
|
+
* Gets all registered routes.
|
|
1549
|
+
*
|
|
1550
|
+
* @returns {RouteDefinition[]} A copy of the routes array.
|
|
1551
|
+
*
|
|
1552
|
+
* @example
|
|
1553
|
+
* const routes = router.getRoutes();
|
|
1554
|
+
* console.log('Available routes:', routes.map(r => r.path));
|
|
1555
|
+
*/
|
|
1556
|
+
getRoutes() {
|
|
1557
|
+
return [...this.routes];
|
|
1558
|
+
}
|
|
1559
|
+
|
|
1560
|
+
/**
|
|
1561
|
+
* Gets a route by its path.
|
|
1562
|
+
*
|
|
1563
|
+
* @param {string} path - The path of the route to get.
|
|
1564
|
+
* @returns {RouteDefinition | undefined} The route definition or undefined.
|
|
1565
|
+
*
|
|
1566
|
+
* @example
|
|
1567
|
+
* const route = router.getRoute('/users/:id');
|
|
1568
|
+
* if (route) {
|
|
1569
|
+
* console.log('Route meta:', route.meta);
|
|
1570
|
+
* }
|
|
1571
|
+
*/
|
|
1572
|
+
getRoute(path) {
|
|
1573
|
+
return this.routes.find((r) => r.path === path);
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
// ============================================
|
|
1577
|
+
// Hook Registration Methods
|
|
1578
|
+
// ============================================
|
|
1579
|
+
|
|
1580
|
+
/**
|
|
1581
|
+
* Registers a global pre-navigation guard.
|
|
1582
|
+
* Multiple guards can be registered and will be executed in order.
|
|
1583
|
+
* Guards can also be registered via the emitter using `router:beforeEach` event.
|
|
1584
|
+
*
|
|
1585
|
+
* @param {NavigationGuard} guard - The guard function to register.
|
|
1586
|
+
* @returns {() => void} A function to unregister the guard.
|
|
1587
|
+
*
|
|
1588
|
+
* @example
|
|
1589
|
+
* // Register a guard
|
|
1590
|
+
* const unregister = router.onBeforeEach((to, from) => {
|
|
1591
|
+
* if (to.meta.requiresAuth && !isAuthenticated()) {
|
|
1592
|
+
* return '/login';
|
|
1593
|
+
* }
|
|
1594
|
+
* });
|
|
1595
|
+
*
|
|
1596
|
+
* // Later, unregister the guard
|
|
1597
|
+
* unregister();
|
|
1598
|
+
*/
|
|
1599
|
+
onBeforeEach(guard) {
|
|
1600
|
+
this._beforeEachGuards.push(guard);
|
|
1601
|
+
return () => {
|
|
1602
|
+
const index = this._beforeEachGuards.indexOf(guard);
|
|
1603
|
+
if (index > -1) {
|
|
1604
|
+
this._beforeEachGuards.splice(index, 1);
|
|
1605
|
+
}
|
|
1606
|
+
};
|
|
1607
|
+
}
|
|
1608
|
+
/**
|
|
1609
|
+
* Registers a global hook that runs after a new route component has been mounted.
|
|
1610
|
+
* @param {NavigationHook} hook - The hook function to register.
|
|
1611
|
+
* @returns {() => void} A function to unregister the hook.
|
|
1612
|
+
*/
|
|
1613
|
+
onAfterEnter(hook) {
|
|
1614
|
+
return this.emitter.on("router:afterEnter", hook);
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
/**
|
|
1618
|
+
* Registers a global hook that runs after a route component has been unmounted.
|
|
1619
|
+
* @param {NavigationHook} hook - The hook function to register.
|
|
1620
|
+
* @returns {() => void} A function to unregister the hook.
|
|
1621
|
+
*/
|
|
1622
|
+
onAfterLeave(hook) {
|
|
1623
|
+
return this.emitter.on("router:afterLeave", hook);
|
|
1624
|
+
}
|
|
1625
|
+
|
|
1626
|
+
/**
|
|
1627
|
+
* Registers a global hook that runs after a navigation has been confirmed and all hooks have completed.
|
|
1628
|
+
* @param {NavigationHook} hook - The hook function to register.
|
|
1629
|
+
* @returns {() => void} A function to unregister the hook.
|
|
1630
|
+
*/
|
|
1631
|
+
onAfterEach(hook) {
|
|
1632
|
+
return this.emitter.on("router:afterEach", hook);
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
/**
|
|
1636
|
+
* Registers a global error handler for navigation errors.
|
|
1637
|
+
* @param {(error: Error, to?: RouteLocation, from?: RouteLocation) => void} handler - The error handler function.
|
|
1638
|
+
* @returns {() => void} A function to unregister the handler.
|
|
1639
|
+
*/
|
|
1640
|
+
onError(handler) {
|
|
1641
|
+
return this.emitter.on("router:onError", handler);
|
|
1642
|
+
}
|
|
1643
|
+
|
|
1644
|
+
/**
|
|
1645
|
+
* Registers a plugin with the router.
|
|
1646
|
+
* @param {RouterPlugin} plugin - The plugin to register.
|
|
1647
|
+
*/
|
|
1648
|
+
use(plugin, options = {}) {
|
|
1649
|
+
if (typeof plugin.install !== "function") {
|
|
1650
|
+
this.errorHandler.handle(
|
|
1651
|
+
new Error("Plugin must have an install method"),
|
|
1652
|
+
"Plugin registration failed",
|
|
1653
|
+
{ plugin }
|
|
1654
|
+
);
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
// Check if plugin is already registered
|
|
1658
|
+
if (this.plugins.has(plugin.name)) {
|
|
1659
|
+
this.errorHandler.warn(`Plugin "${plugin.name}" is already registered`, {
|
|
1660
|
+
existingPlugin: this.plugins.get(plugin.name),
|
|
1661
|
+
});
|
|
1662
|
+
return;
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1665
|
+
this.plugins.set(plugin.name, plugin);
|
|
1666
|
+
plugin.install(this, options);
|
|
1667
|
+
}
|
|
1668
|
+
|
|
1669
|
+
/**
|
|
1670
|
+
* Gets all registered plugins.
|
|
1671
|
+
* @returns {RouterPlugin[]} Array of registered plugins.
|
|
1672
|
+
*/
|
|
1673
|
+
getPlugins() {
|
|
1674
|
+
return Array.from(this.plugins.values());
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
/**
|
|
1678
|
+
* Gets a plugin by name.
|
|
1679
|
+
* @param {string} name - The plugin name.
|
|
1680
|
+
* @returns {RouterPlugin | undefined} The plugin or undefined.
|
|
1681
|
+
*/
|
|
1682
|
+
getPlugin(name) {
|
|
1683
|
+
return this.plugins.get(name);
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
/**
|
|
1687
|
+
* Removes a plugin from the router.
|
|
1688
|
+
* @param {string} name - The plugin name.
|
|
1689
|
+
* @returns {boolean} True if the plugin was removed.
|
|
1690
|
+
*/
|
|
1691
|
+
removePlugin(name) {
|
|
1692
|
+
const plugin = this.plugins.get(name);
|
|
1693
|
+
if (!plugin) return false;
|
|
1694
|
+
|
|
1695
|
+
// Call destroy if available
|
|
1696
|
+
if (typeof plugin.destroy === "function") {
|
|
1697
|
+
try {
|
|
1698
|
+
plugin.destroy(this);
|
|
1699
|
+
} catch (error) {
|
|
1700
|
+
this.errorHandler.log(`Plugin ${name} destroy failed`, error);
|
|
1701
|
+
}
|
|
1702
|
+
}
|
|
1703
|
+
|
|
1704
|
+
return this.plugins.delete(name);
|
|
1705
|
+
}
|
|
1706
|
+
|
|
1707
|
+
/**
|
|
1708
|
+
* Sets a custom error handler. Used by error handling plugins.
|
|
1709
|
+
* @param {Object} errorHandler - The error handler object with handle, warn, and log methods.
|
|
1710
|
+
*/
|
|
1711
|
+
setErrorHandler(errorHandler) {
|
|
1712
|
+
if (
|
|
1713
|
+
errorHandler &&
|
|
1714
|
+
typeof errorHandler.handle === "function" &&
|
|
1715
|
+
typeof errorHandler.warn === "function" &&
|
|
1716
|
+
typeof errorHandler.log === "function"
|
|
1717
|
+
) {
|
|
1718
|
+
this.errorHandler = errorHandler;
|
|
1719
|
+
} else {
|
|
1720
|
+
console.warn(
|
|
1721
|
+
"[ElevaRouter] Invalid error handler provided. Must have handle, warn, and log methods."
|
|
1722
|
+
);
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
/**
|
|
1728
|
+
* @typedef {Object} RouterOptions
|
|
1729
|
+
* @property {string} mount - A CSS selector for the main element where the app is mounted.
|
|
1730
|
+
* @property {RouteDefinition[]} routes - An array of route definitions.
|
|
1731
|
+
* @property {'hash' | 'query' | 'history'} [mode='hash'] - The routing mode.
|
|
1732
|
+
* @property {string} [queryParam='page'] - The query parameter to use in 'query' mode.
|
|
1733
|
+
* @property {string} [viewSelector='view'] - The selector for the view element within a layout.
|
|
1734
|
+
* @property {boolean} [autoStart=true] - Whether to start the router automatically.
|
|
1735
|
+
* @property {NavigationGuard} [onBeforeEach] - A global guard executed before every navigation.
|
|
1736
|
+
* @property {string | ComponentDefinition | (() => Promise<{default: ComponentDefinition}>)} [globalLayout] - A global layout for all routes. Can be overridden by a route's specific layout.
|
|
1737
|
+
*/
|
|
1738
|
+
|
|
1739
|
+
/**
|
|
1740
|
+
* @class 🚀 RouterPlugin
|
|
1741
|
+
* @classdesc A powerful, reactive, and flexible Router Plugin for Eleva.js applications.
|
|
1742
|
+
* This plugin provides comprehensive client-side routing functionality including:
|
|
1743
|
+
* - Multiple routing modes (hash, history, query)
|
|
1744
|
+
* - Navigation guards and lifecycle hooks
|
|
1745
|
+
* - Reactive state management
|
|
1746
|
+
* - Component resolution and lazy loading
|
|
1747
|
+
* - Layout and page component separation
|
|
1748
|
+
* - Plugin system for extensibility
|
|
1749
|
+
* - Advanced error handling
|
|
1750
|
+
*
|
|
1751
|
+
* @example
|
|
1752
|
+
* // Install the plugin
|
|
1753
|
+
* const app = new Eleva("myApp");
|
|
1754
|
+
*
|
|
1755
|
+
* const HomePage = { template: () => `<h1>Home</h1>` };
|
|
1756
|
+
* const AboutPage = { template: () => `<h1>About Us</h1>` };
|
|
1757
|
+
* const UserPage = {
|
|
1758
|
+
* template: (ctx) => `<h1>User: ${ctx.router.params.id}</h1>`
|
|
1759
|
+
* };
|
|
1760
|
+
*
|
|
1761
|
+
* app.use(RouterPlugin, {
|
|
1762
|
+
* mount: '#app',
|
|
1763
|
+
* mode: 'hash',
|
|
1764
|
+
* routes: [
|
|
1765
|
+
* { path: '/', component: HomePage },
|
|
1766
|
+
* { path: '/about', component: AboutPage },
|
|
1767
|
+
* { path: '/users/:id', component: UserPage }
|
|
1768
|
+
* ]
|
|
1769
|
+
* });
|
|
1770
|
+
*/
|
|
1771
|
+
export const RouterPlugin = {
|
|
1772
|
+
/**
|
|
1773
|
+
* Unique identifier for the plugin
|
|
1774
|
+
* @type {string}
|
|
1775
|
+
*/
|
|
1776
|
+
name: "router",
|
|
1777
|
+
|
|
1778
|
+
/**
|
|
1779
|
+
* Plugin version
|
|
1780
|
+
* @type {string}
|
|
1781
|
+
*/
|
|
1782
|
+
version: "1.0.0-rc.10",
|
|
1783
|
+
|
|
1784
|
+
/**
|
|
1785
|
+
* Plugin description
|
|
1786
|
+
* @type {string}
|
|
1787
|
+
*/
|
|
1788
|
+
description: "Client-side routing for Eleva applications",
|
|
1789
|
+
|
|
1790
|
+
/**
|
|
1791
|
+
* Installs the RouterPlugin into an Eleva instance.
|
|
1792
|
+
*
|
|
1793
|
+
* @param {Eleva} eleva - The Eleva instance
|
|
1794
|
+
* @param {RouterOptions} options - Router configuration options
|
|
1795
|
+
* @param {string} options.mount - A CSS selector for the main element where the app is mounted
|
|
1796
|
+
* @param {RouteDefinition[]} options.routes - An array of route definitions
|
|
1797
|
+
* @param {'hash' | 'query' | 'history'} [options.mode='hash'] - The routing mode
|
|
1798
|
+
* @param {string} [options.queryParam='page'] - The query parameter to use in 'query' mode
|
|
1799
|
+
* @param {string} [options.viewSelector='view'] - The selector for the view element within a layout
|
|
1800
|
+
* @param {boolean} [options.autoStart=true] - Whether to start the router automatically
|
|
1801
|
+
* @param {NavigationGuard} [options.onBeforeEach] - A global guard executed before every navigation
|
|
1802
|
+
* @param {string | ComponentDefinition | (() => Promise<{default: ComponentDefinition}>)} [options.globalLayout] - A global layout for all routes
|
|
1803
|
+
*
|
|
1804
|
+
* @example
|
|
1805
|
+
* // main.js
|
|
1806
|
+
* import Eleva from './eleva.js';
|
|
1807
|
+
* import { RouterPlugin } from './plugins/RouterPlugin.js';
|
|
1808
|
+
*
|
|
1809
|
+
* const app = new Eleva('myApp');
|
|
1810
|
+
*
|
|
1811
|
+
* const HomePage = { template: () => `<h1>Home</h1>` };
|
|
1812
|
+
* const AboutPage = { template: () => `<h1>About Us</h1>` };
|
|
1813
|
+
*
|
|
1814
|
+
* app.use(RouterPlugin, {
|
|
1815
|
+
* mount: '#app',
|
|
1816
|
+
* routes: [
|
|
1817
|
+
* { path: '/', component: HomePage },
|
|
1818
|
+
* { path: '/about', component: AboutPage }
|
|
1819
|
+
* ]
|
|
1820
|
+
* });
|
|
1821
|
+
*/
|
|
1822
|
+
install(eleva, options = {}) {
|
|
1823
|
+
if (!options.mount) {
|
|
1824
|
+
throw new Error("[RouterPlugin] 'mount' option is required");
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
if (!options.routes || !Array.isArray(options.routes)) {
|
|
1828
|
+
throw new Error("[RouterPlugin] 'routes' option must be an array");
|
|
1829
|
+
}
|
|
1830
|
+
|
|
1831
|
+
/**
|
|
1832
|
+
* Registers a component definition with the Eleva instance.
|
|
1833
|
+
* This method handles both inline component objects and pre-registered component names.
|
|
1834
|
+
*
|
|
1835
|
+
* @param {any} def - The component definition to register
|
|
1836
|
+
* @param {string} type - The type of component for naming (e.g., "Route", "Layout")
|
|
1837
|
+
* @returns {string | null} The registered component name or null if no definition provided
|
|
1838
|
+
*/
|
|
1839
|
+
const register = (def, type) => {
|
|
1840
|
+
if (!def) return null;
|
|
1841
|
+
|
|
1842
|
+
if (typeof def === "object" && def !== null && !def.name) {
|
|
1843
|
+
const name = `Eleva${type}Component_${Math.random()
|
|
1844
|
+
.toString(36)
|
|
1845
|
+
.slice(2, 11)}`;
|
|
1846
|
+
|
|
1847
|
+
try {
|
|
1848
|
+
eleva.component(name, def);
|
|
1849
|
+
return name;
|
|
1850
|
+
} catch (error) {
|
|
1851
|
+
throw new Error(
|
|
1852
|
+
`[RouterPlugin] Failed to register ${type} component: ${error.message}`
|
|
1853
|
+
);
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
return def;
|
|
1857
|
+
};
|
|
1858
|
+
|
|
1859
|
+
if (options.globalLayout) {
|
|
1860
|
+
options.globalLayout = register(options.globalLayout, "GlobalLayout");
|
|
1861
|
+
}
|
|
1862
|
+
|
|
1863
|
+
(options.routes || []).forEach((route) => {
|
|
1864
|
+
route.component = register(route.component, "Route");
|
|
1865
|
+
if (route.layout) {
|
|
1866
|
+
route.layout = register(route.layout, "RouteLayout");
|
|
1867
|
+
}
|
|
1868
|
+
});
|
|
1869
|
+
|
|
1870
|
+
const router = new Router(eleva, options);
|
|
1871
|
+
eleva.router = router;
|
|
1872
|
+
|
|
1873
|
+
if (options.autoStart !== false) {
|
|
1874
|
+
queueMicrotask(() => router.start());
|
|
1875
|
+
}
|
|
1876
|
+
|
|
1877
|
+
// Add plugin metadata to the Eleva instance
|
|
1878
|
+
if (!eleva.plugins) {
|
|
1879
|
+
eleva.plugins = new Map();
|
|
1880
|
+
}
|
|
1881
|
+
eleva.plugins.set(this.name, {
|
|
1882
|
+
name: this.name,
|
|
1883
|
+
version: this.version,
|
|
1884
|
+
description: this.description,
|
|
1885
|
+
options,
|
|
1886
|
+
});
|
|
1887
|
+
|
|
1888
|
+
// Add utility methods for manual router access
|
|
1889
|
+
eleva.navigate = router.navigate.bind(router);
|
|
1890
|
+
eleva.getCurrentRoute = () => router.currentRoute.value;
|
|
1891
|
+
eleva.getRouteParams = () => router.currentParams.value;
|
|
1892
|
+
eleva.getRouteQuery = () => router.currentQuery.value;
|
|
1893
|
+
|
|
1894
|
+
return router;
|
|
1895
|
+
},
|
|
1896
|
+
|
|
1897
|
+
/**
|
|
1898
|
+
* Uninstalls the plugin from the Eleva instance
|
|
1899
|
+
*
|
|
1900
|
+
* @param {Eleva} eleva - The Eleva instance
|
|
1901
|
+
*/
|
|
1902
|
+
async uninstall(eleva) {
|
|
1903
|
+
if (eleva.router) {
|
|
1904
|
+
await eleva.router.destroy();
|
|
1905
|
+
delete eleva.router;
|
|
1906
|
+
}
|
|
1907
|
+
|
|
1908
|
+
// Remove plugin metadata
|
|
1909
|
+
if (eleva.plugins) {
|
|
1910
|
+
eleva.plugins.delete(this.name);
|
|
1911
|
+
}
|
|
1912
|
+
|
|
1913
|
+
// Remove utility methods
|
|
1914
|
+
delete eleva.navigate;
|
|
1915
|
+
delete eleva.getCurrentRoute;
|
|
1916
|
+
delete eleva.getRouteParams;
|
|
1917
|
+
delete eleva.getRouteQuery;
|
|
1918
|
+
},
|
|
1919
|
+
};
|