### Full Eleva Router Application Setup
Source: https://github.com/tarekraafat/eleva-router/blob/master/README.md
A comprehensive example demonstrating the integration of Eleva Router into an Eleva.js application. It defines multiple routes, including dynamic parameters, and showcases component setup with template rendering and navigation.
```js
import Eleva from "eleva";
import ElevaRouter from "eleva-router";
const app = new Eleva("BlogApp");
const routes = [
{
path: "/",
component: {
template: () => `
`
}
}
});
```
--------------------------------
### Eleva Router start() Method API
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Documentation for the `start()` method of the `Router` class. This asynchronous method initializes the router, begins listening for route changes, and processes the initial route. It includes an example of error handling during startup.
```APIDOC
async start():
Description: Starts the router by listening for route changes and processing the initial route. Throws an error if startup fails.
Example:
try {
await app.router.start();
} catch (error) {
console.error("Router startup failed:", error);
}
```
--------------------------------
### Basic Eleva Router Setup with Eleva.js
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Example demonstrating how to import Eleva and Eleva Router, define components with route and navigate context, and configure the router with different routing modes and a default fallback route for 404 pages.
```js
import Eleva from "eleva";
import ElevaRouter from "eleva-router";
const app = new Eleva("MyApp");
// Define routed components (no need for separate registration)
const HomeComponent = {
setup: ({ route }) => {
console.log("Home route:", route.path);
return {};
},
template: () => `
`,
};
// Install the router plugin
app.use(ElevaRouter, {
container: document.getElementById("app"),
mode: "history", // Can be "hash", "query", or "history"
routes: [
{ path: "/", component: HomeComponent },
{ path: "/about", component: AboutComponent },
],
defaultRoute: { path: "/404", component: NotFoundComponent },
});
// Router starts automatically unless autoStart: false
```
--------------------------------
### Install Eleva Router via npm
Source: https://github.com/tarekraafat/eleva-router/blob/master/README.md
Instructions to install the Eleva Router package using npm.
```bash
npm install eleva-router
```
--------------------------------
### Install ElevaRouter plugin into Eleva.js instance
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
The `install` method is the entry point for integrating ElevaRouter with an Eleva.js application. It handles the registration of routed components, attaches the router instance to `eleva.router`, and can optionally initiate the router's startup process. The installation involves validating options, auto-registering components, creating the router, and deferring async startup.
```APIDOC
install(eleva, options):
Installs the router plugin into an Eleva.js instance.
Automatically registers routed components (if provided as definitions), attaches the Router instance to `eleva.router`, and optionally starts the router.
The installation process:
1. Validates options and container element
2. Auto-registers component definitions
3. Creates and attaches router instance
4. Defers async startup using `queueMicrotask` if `autoStart` is true
```
--------------------------------
### Initialize Eleva Router with Manual Start
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
This snippet demonstrates how to initialize Eleva Router with `autoStart` disabled, allowing for manual control over when the router begins listening for route changes. It also shows how to manually start and destroy the router instance, including error handling for startup.
```js
app.use(ElevaRouter, {
container: document.getElementById("app"),
mode: "history",
routes: [
{ path: "/", component: HomeComponent },
{ path: "/about", component: AboutComponent }
],
autoStart: false
});
// Start the router manually when ready
try {
await app.router.start();
console.log("Router started successfully");
} catch (error) {
console.error("Failed to start router:", error);
}
// Clean up when done (e.g., during app shutdown)
await app.router.destroy();
```
--------------------------------
### Start Eleva Router Development Server
Source: https://github.com/tarekraafat/eleva-router/blob/master/CONTRIBUTING.md
Command to start the local development server for Eleva Router, typically used for live reloading and testing changes.
```bash
npm run dev
```
--------------------------------
### Access Route Information in Eleva Components
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
This example illustrates how to access injected route information (`route`) within an Eleva.js component's `setup` context. It shows how to retrieve current path, query parameters, route parameters, matched route pattern, and the full URL, along with an example of programmatic navigation.
```js
const MyComponent = {
setup: ({ route, navigate }) => {
console.log("Current path:", route.path);
console.log("Query parameters:", route.query);
console.log("Route parameters:", route.params);
console.log("Matched route pattern:", route.matchedRoute);
console.log("Full URL:", route.fullUrl);
// You can also navigate programmatically:
// navigate("/about");
return {};
},
template: (ctx) => `
Content here
`
};
```
--------------------------------
### When to Use autoStart: false in Eleva Router
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Advises using manual router start (autoStart: false) when specific conditions, such as user authentication or data loading, must be met before routing begins.
```APIDOC
Manual Router Start (autoStart: false):
Purpose: Ensure conditions are met before routing begins
Examples: User authentication, data loading
```
--------------------------------
### Troubleshooting: Eleva Router Startup Failures
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Advises checking the browser console for specific error messages and ensuring the container element exists when the router starts.
```APIDOC
Troubleshooting: Router Startup Failures
Checks:
- Browser console for specific error messages
- Container element exists when router starts
```
--------------------------------
### Programmatic navigation and router lifecycle control
Source: https://github.com/tarekraafat/eleva-router/blob/master/README.md
Shows how to navigate programmatically using the `app.router` instance and how to manually start or destroy the router instance.
```js
// Navigate from anywhere
await app.router.navigate("/about");
await app.router.navigate("/users/:id", { id: 123 });
// Router control
await app.router.start(); // Manual start
await app.router.destroy(); // Cleanup
```
--------------------------------
### Install Eleva Router via npm
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Command to install Eleva Router using the npm package manager, which is the recommended method for project integration.
```bash
npm install eleva-router
```
--------------------------------
### Install Eleva Router Project Dependencies
Source: https://github.com/tarekraafat/eleva-router/blob/master/CONTRIBUTING.md
Command to install all necessary Node.js dependencies for the Eleva Router project using npm.
```bash
npm install
```
--------------------------------
### Eleva Router Configuration Options
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Detailed documentation for the configuration object passed to `app.use()` when installing Eleva Router, covering routing modes, route definitions, default route behavior, auto-start control, and query parameter customization.
```APIDOC
Configuration Object:
mode: string
Description: The routing mode to use.
Options:
"hash": Uses window.location.hash (e.g., #pageName).
"query": Uses window.location.search with a configurable query parameter (e.g., ?page=pageName or ?view=pageName).
"history": Uses window.location.pathname with the History API (e.g., /pageName).
Default: "hash"
routes: array
Description: An array of route objects.
Route Object:
path: string
Description: The route path (e.g., "/", "/about", or dynamic paths like "/users/:id").
component: string | Object
Description: Either a globally registered component name or a component definition.
props: object (optional)
Description: Additional props to pass to the routed component.
defaultRoute: object (optional)
Description: A route object to be used as a fallback when no other route matches. It has the same structure as the other route objects.
autoStart: boolean (default: true)
Description: Whether to automatically start the router after plugin installation. If set to false, you must manually call await app.router.start().
queryParam: string (default: "page")
Description: The query parameter name used for query mode routing. Only applies when mode is set to "query".
```
--------------------------------
### Define and access dynamic route parameters in ElevaRouter
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
This example shows how to define routes with dynamic parameters (e.g., `:category`, `:id`) and catch-all segments (`:path*`). It also illustrates how to access these extracted parameters within a component's `setup` function via the `route.params` object, enabling dynamic content rendering based on URL segments.
```js
app.use(ElevaRouter, {
container: document.getElementById("app"),
mode: "history",
routes: [
{ path: "/", component: HomeComponent },
{ path: "/products/:category", component: ProductCategoryComponent },
{ path: "/products/:category/:id", component: ProductDetailComponent },
{ path: "/files/:path*", component: FileViewerComponent } // Catch-all
]
});
```
```js
// In your component:
const ProductDetailComponent = {
setup: ({ route }) => {
// For URL "/products/electronics/12345"
console.log(route.params.category); // "electronics"
console.log(route.params.id); // "12345"
return {
category: route.params.category,
productId: route.params.id
};
},
template: (ctx) => `
Product: ${ctx.productId}
Category: ${ctx.category}
`
};
```
--------------------------------
### Define dynamic routes and access parameters
Source: https://github.com/tarekraafat/eleva-router/blob/master/README.md
Shows how to define routes with dynamic parameters (e.g., `:id`) and catch-all segments (`:path*`), and how to access these parameters within a component's setup function.
```js
// Route with parameters
{ path: "/users/:id", component: UserProfile }
// Catch-all route
{ path: "/files/:path*", component: FileViewer }
// Access parameters in component
const UserProfile = {
setup: ({ route }) => ({
userId: route.params.id // "123" for "/users/123"
}),
template: (ctx) => `
User: ${ctx.userId}
`
};
```
--------------------------------
### Conventional Commit Message Example
Source: https://github.com/tarekraafat/eleva-router/blob/master/CONTRIBUTING.md
An example of a commit message following the Conventional Commits specification for adding a new feature.
```text
feat: add support for custom middleware
```
--------------------------------
### Configure Eleva Router for History Mode
Source: https://github.com/tarekraafat/eleva-router/blob/master/README.md
Example of setting Eleva Router to use 'history' mode, resulting in clean URLs like `http://example.com/about`.
```js
// URLs: http://example.com/about
app.use(ElevaRouter, { mode: "history", ... });
```
--------------------------------
### Troubleshooting: Eleva Router Navigation Not Working
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Guides users to ensure navigate() is called correctly and to check the JavaScript console for errors if navigation fails.
```APIDOC
Troubleshooting: Navigation Not Working
Checks:
- navigate() called correctly (from context or app.router.navigate())
- JavaScript errors in console
```
--------------------------------
### Eleva Router: Validating Route Parameters in Components
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
This example shows how to validate route parameters (`route.params`) within an Eleva Router component's `setup` function. It demonstrates checking for the presence and validity of a `userId` parameter and redirecting the user to a default route if the parameter is invalid, ensuring data integrity and a better user experience.
```js
const UserComponent = {
setup: ({ route, navigate }) => {
// Validate parameters
const userId = route.params.id;
if (!userId || isNaN(parseInt(userId))) {
navigate("/users"); // Redirect to user list
return {};
}
return { userId };
},
template: (ctx) => `
User: ${ctx.userId}
`,
};
```
--------------------------------
### Configure Eleva Router for Hash Mode
Source: https://github.com/tarekraafat/eleva-router/blob/master/README.md
Example of setting Eleva Router to use 'hash' mode, resulting in URLs like `http://example.com/#/about`.
```js
// URLs: http://example.com/#/about
app.use(ElevaRouter, { mode: "hash", ... });
```
--------------------------------
### Configure Eleva Router with Query Mode
Source: https://github.com/tarekraafat/eleva-router/blob/master/README.md
Illustrates how to initialize Eleva Router in 'query' mode, enabling routing based on custom URL query parameters. Examples include an e-commerce site using '?category=' and an admin panel using '?section='.
```js
// E-commerce with custom parameter
app.use(ElevaRouter, {
container: document.getElementById("app"),
mode: "query",
queryParam: "category", // ?category=electronics
routes: [
{ path: "/", component: Home },
{ path: "/electronics", component: Electronics },
{ path: "/books", component: Books }
]
});
// Admin panel
app.use(ElevaRouter, {
container: document.getElementById("app"),
mode: "query",
queryParam: "section", // ?section=users
routes: [
{ path: "/", component: Dashboard },
{ path: "/users", component: UserManagement },
{ path: "/settings", component: Settings }
]
});
```
--------------------------------
### Configure ElevaRouter for basic hash routing
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
This example demonstrates how to set up ElevaRouter to use hash-based routing. Routes are defined with a path and a corresponding component, and a default route is provided for unmatched paths.
```js
app.use(ElevaRouter, {
container: document.getElementById("app"),
mode: "hash",
routes: [
{ path: "/", component: HomeComponent },
{ path: "/contact", component: ContactComponent }
],
defaultRoute: { path: "/404", component: NotFoundComponent }
});
```
--------------------------------
### Manage Eleva Router Lifecycle
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
This snippet provides examples for managing the Eleva Router's lifecycle. It shows how to check if the router is active, how to destroy the router instance for cleanup, and how to integrate router destruction with browser `beforeunload` events for proper resource release.
```js
// Check if router is running
console.log("Router is active:", app.router.isStarted);
// Clean up the router when your application shuts down
await app.router.destroy();
// Add cleanup to page unload for browser applications
window.addEventListener("beforeunload", async () => {
await app.router.destroy();
});
```
--------------------------------
### Navigate and access route information within components
Source: https://github.com/tarekraafat/eleva-router/blob/master/README.md
Illustrates how to use the `navigate` function provided to component setup for simple or parameterized navigation, and how to access current route details like path, parameters, and query parameters.
```js
const MyComponent = {
setup: ({ navigate, route }) => ({
// Simple navigation
goToAbout: () => navigate("/about"),
// With parameters
goToUser: (id) => navigate("/users/:id", { id }),
// Current route info
currentPath: route.path,
routeParams: route.params,
queryParams: route.query,
}),
};
```
--------------------------------
### Access Route Parameters in Eleva Router Components
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Explains that route parameters are available in the route.params object, which is injected into the component's setup context.
```APIDOC
Accessing Route Parameters:
Location: route.params object
Context: Injected into component's setup context
```
--------------------------------
### Configure Eleva Router for Query Mode
Source: https://github.com/tarekraafat/eleva-router/blob/master/README.md
Examples of setting Eleva Router to use 'query' mode, including how to customize the query parameter name (e.g., `?view=about` instead of `?page=about`).
```js
// Default: ?page=about
app.use(ElevaRouter, { mode: "query", ... });
// Custom: ?view=about
app.use(ElevaRouter, {
mode: "query",
queryParam: "view",
...
});
```
--------------------------------
### Eleva Router: Manual Initialization and Cleanup
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
This snippet demonstrates how to manually control the Eleva Router's lifecycle. It shows disabling `autoStart` during initialization, then explicitly starting the router after the DOM is loaded, and finally destroying it before the page unloads to prevent memory leaks.
```js
const app = new Eleva("MyApp");
app.use(ElevaRouter, {
container: document.getElementById("app"),
mode: "history",
routes: [
{ path: "/", component: HomeComponent },
{ path: "/dashboard", component: DashboardComponent }
],
autoStart: false // Manual control
});
// Start when ready
document.addEventListener("DOMContentLoaded", async () => {
try {
await app.router.start();
console.log("Application routing initialized");
} catch (error) {
console.error("Failed to initialize routing:", error);
}
});
// Clean up on page unload
window.addEventListener("beforeunload", async () => {
await app.router.destroy();
});
```
--------------------------------
### Access Route Information and Navigation Function in Eleva Router Components
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
States that route information (route) and the navigate function are directly injected into the component's setup context.
```APIDOC
Accessing Route Information & Navigation:
Injected: route object and navigate function
Context: Component's setup context
```
--------------------------------
### Programmatic Navigation from Eleva Component
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
This snippet illustrates how to perform programmatic navigation from within an Eleva.js component using the `navigate` function provided in the setup context. It covers simple navigation, navigation with route parameters, and error handling for navigation attempts.
```js
// Simple navigation
navigate("/about");
// With route parameters
navigate("/users/:id", { id: 123 });
// Navigation with error handling
try {
await navigate("/dashboard");
} catch (error) {
console.error("Navigation failed:", error);
}
```
--------------------------------
### Configure ElevaRouter for HTML5 history routing
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
This example demonstrates setting up ElevaRouter to utilize the HTML5 History API for cleaner URLs without hash symbols. It defines a set of routes that will be managed by the browser's history.
```js
app.use(ElevaRouter, {
container: document.getElementById("app"),
mode: "history",
routes: [
{ path: "/", component: HomeComponent },
{ path: "/about", component: AboutComponent }
]
});
```
--------------------------------
### Implement custom query parameters for different application sections with ElevaRouter
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
This example demonstrates the flexibility of ElevaRouter's query mode by showing how to use different custom query parameters (`queryParam`) for distinct sections of an application, such as an e-commerce site, an admin panel, or a content management system. This allows for clear separation of concerns and tailored URL structures based on context.
```js
// E-commerce application
app.use(ElevaRouter, {
container: document.getElementById("app"),
mode: "query",
queryParam: "category",
routes: [
{ path: "/", component: HomeComponent },
{ path: "/electronics", component: ElectronicsComponent },
{ path: "/books", component: BooksComponent }
]
});
// URLs: ?category=/, ?category=/electronics, ?category=/books
```
```js
// Admin panel
app.use(ElevaRouter, {
container: document.getElementById("app"),
mode: "query",
queryParam: "section",
routes: [
{ path: "/", component: DashboardComponent },
{ path: "/users", component: UsersComponent },
{ path: "/settings", component: SettingsComponent }
]
});
// URLs: ?section=/, ?section=/users, ?section=/settings
```
```js
// Content management
app.use(ElevaRouter, {
container: document.getElementById("app"),
mode: "query",
queryParam: "content",
routes: [
{ path: "/", component: OverviewComponent },
{ path: "/articles", component: ArticlesComponent },
{ path: "/pages", component: PagesComponent }
]
});
// URLs: ?content=/, ?content=/articles, ?content=/pages
```
--------------------------------
### Internal method to wrap components for ElevaRouter
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
This internal utility method modifies a component definition, ensuring its setup function receives `route` and `navigate` properties directly. It's crucial for integrating components seamlessly with the router's context.
```APIDOC
wrapComponentWithRoute(comp, routeInfo):
Internal method that wraps a component definition so that its setup function receives the `route` and `navigate` properties directly.
```
--------------------------------
### Customize Query Parameter Name in Eleva Router Query Mode
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Explains how to change the default query parameter name (e.g., from ?page to ?view) using the queryParam option during router installation.
```APIDOC
Customize Query Parameter Name:
Option: queryParam
Usage: Set during router installation (e.g., queryParam: "view")
Example: Uses ?view=about instead of ?page=about
```
--------------------------------
### Manually Control Eleva Router Lifecycle
Source: https://github.com/tarekraafat/eleva-router/blob/master/README.md
Demonstrates how to disable automatic router startup and manually control the Eleva Router's lifecycle. It shows how to explicitly start the router after DOM content is loaded and destroy it before the page unloads for proper resource management.
```js
app.use(ElevaRouter, {
container: document.getElementById("app"),
routes: [...],
autoStart: false // Don't start automatically
});
// Start when ready
document.addEventListener("DOMContentLoaded", async () => {
try {
await app.router.start();
console.log("Router started!");
} catch (error) {
console.error("Router failed:", error);
}
});
// Cleanup on exit
window.addEventListener("beforeunload", () => {
app.router.destroy();
});
```
--------------------------------
### Access Dynamic Route Parameters in Eleva Components
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
This example demonstrates how to retrieve dynamic route parameters (e.g., `:id`, `:category`, `:slug`) from the `route.params` object within an Eleva.js component. It also shows how to use these parameters for programmatic navigation.
```js
const UserDetailComponent = {
setup: ({ route, navigate }) => {
console.log("User ID:", route.params.id);
return {
userId: route.params.id,
goToUser: (id) => navigate("/users/:id", { id })
};
},
template: (ctx) => `
User Profile: ${ctx.userId}
`
};
```
--------------------------------
### Configure ElevaRouter for query parameter routing
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
This example illustrates how to configure ElevaRouter to use query parameters for routing. It shows both the default query parameter behavior (`?page=/`) and how to specify a custom query parameter name (e.g., `?view=/`). This mode is useful for applications where URL paths are not desired.
```js
// Default query parameter
app.use(ElevaRouter, {
container: document.getElementById("app"),
mode: "query",
routes: [
{ path: "/", component: HomeComponent },
{ path: "/services", component: ServicesComponent }
]
});
// URLs: ?page=/, ?page=/services
```
```js
// Custom query parameter
app.use(ElevaRouter, {
container: document.getElementById("app"),
mode: "query",
queryParam: "view", // Custom parameter name
routes: [
{ path: "/", component: HomeComponent },
{ path: "/services", component: ServicesComponent }
]
});
// URLs: ?view=/, ?view=/services
```
--------------------------------
### Eleva Router: Custom Error Boundary with Default Route
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
This example illustrates how to implement a custom error boundary component and configure it as the `defaultRoute` in Eleva Router. This ensures that users are gracefully redirected to a dedicated error page when a route is not found or other unhandled routing issues occur.
```js
const ErrorBoundaryComponent = {
setup: ({ route, navigate }) => {
const handleRetry = () => {
// Navigate back to home or reload current route
navigate("/");
};
return { handleRetry };
},
template: (ctx) => `
Something went wrong
`,
};
app.use(ElevaRouter, {
container: document.getElementById("app"),
mode: "history",
routes: [
{ path: "/", component: HomeComponent },
{ path: "/about", component: AboutComponent }
],
defaultRoute: { path: "/error", component: ErrorBoundaryComponent }
});
```
--------------------------------
### Initialize Eleva Router with basic routes
Source: https://github.com/tarekraafat/eleva-router/blob/master/README.md
Demonstrates how to import and use Eleva Router with an Eleva.js application, defining simple components and routes for hash, query, or history modes.
```js
import Eleva from "eleva";
import ElevaRouter from "eleva-router";
const app = new Eleva("MyApp");
// Define components
const Home = {
template: () => `
`,
};
// Setup router
app.use(ElevaRouter, {
container: document.getElementById("app"),
mode: "history", // "hash" | "query" | "history"
routes: [
{ path: "/", component: Home },
{ path: "/about", component: About },
],
});
```
--------------------------------
### Eleva Router configuration options
Source: https://github.com/tarekraafat/eleva-router/blob/master/README.md
Reference for available configuration options when initializing Eleva Router, including container, routing mode, query parameter name, routes array, default route, and auto-start.
```APIDOC
Option Type Default Description
container HTMLElement required DOM element where components mount
mode string "hash" Routing mode: "hash", "query", or "history"
queryParam string "page" Query parameter name for query mode (`?page=about` vs `?view=about`)
routes array [] Array of route objects
defaultRoute object null Fallback route for unmatched paths
autoStart boolean true Auto-start router after installation
```
--------------------------------
### Clone Eleva Router Repository
Source: https://github.com/tarekraafat/eleva-router/blob/master/CONTRIBUTING.md
Instructions to clone the Eleva Router Git repository and navigate into its directory for local development.
```bash
git clone https://github.com/TarekRaafat/eleva-router.git
cd eleva
```
--------------------------------
### Eleva Router Class Constructor API
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Documentation for the `Router` class constructor, detailing its `eleva` instance and `options` parameter. The `options` object includes properties like `container`, `mode`, `queryParam`, `routes`, and `defaultRoute` for configuring the router.
```APIDOC
new Router(eleva, options);
Parameters:
eleva: The Eleva.js instance.
options: Configuration object with:
container: (HTMLElement) Where routed components will be mounted.
mode: (string) "hash" (default), "query", or "history".
queryParam: (string) Query parameter name for query mode (default: "page").
routes: (array) Array of route objects.
defaultRoute: (object, optional) A fallback route object.
```
--------------------------------
### Run Eleva Router Tests
Source: https://github.com/tarekraafat/eleva-router/blob/master/CONTRIBUTING.md
Command to execute the test suite for the Eleva Router project, ensuring all functionalities work as expected.
```bash
npm test
```
--------------------------------
### Troubleshooting: No Eleva Router Matches
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Provides guidance for when no route matches, advising to check route definitions, URL matching, console warnings, and the defaultRoute usage.
```APIDOC
Troubleshooting: No Route Matches
Checks:
- Correct route definitions
- Exact URL matching route paths/patterns
- Console warnings for unmatched routes
- Usage of defaultRoute (if provided)
```
--------------------------------
### Eleva Router navigate() Method API
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Documentation for the `navigate()` method of the `Router` class. This asynchronous method programmatically navigates to a specified path, optionally accepting a `params` object for dynamic route parameters.
```APIDOC
async navigate(path, params):
Description: Programmatically navigates to a given path. Optionally accepts a params object for route parameters.
Example:
await app.router.navigate("/users/:id", { id: 123 });
```
--------------------------------
### Define Dynamic Route Parameters in Eleva Router (FAQ)
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Describes how to define dynamic route parameters using colon syntax (e.g., /users/:id) and catch-all parameters with an asterisk (e.g., /files/:path*).
```APIDOC
Dynamic Route Parameters:
Syntax: Use colon syntax (e.g., /users/:id)
Catch-all: Add an asterisk (e.g., /files/:path*)
```
--------------------------------
### Include Eleva Router via unpkg CDN
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
HTML script tag to include Eleva Router directly from the unpkg CDN, providing an alternative for direct browser inclusion.
```html
```
--------------------------------
### Troubleshooting: Eleva Router Parameters Not Matching
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Suggests verifying that the route pattern syntax is correct (e.g., /users/:id) and that the URL structure matches the pattern.
```APIDOC
Troubleshooting: Route Parameters Not Matching
Checks:
- Route pattern follows correct syntax (e.g., /users/:id)
- URL structure matches the pattern
```
--------------------------------
### Add Routes Dynamically to Eleva Router
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Explains that new routes can be added after initialization using the addRoute(route) method on the router instance.
```APIDOC
Dynamic Route Addition:
Method: addRoute(route)
Usage: Call on the router instance after initialization
```
--------------------------------
### Include Eleva Router via jsDelivr CDN
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
HTML script tag to include Eleva Router directly from the jsDelivr CDN, suitable for quick prototyping or projects without a build step.
```html
```
--------------------------------
### Define Dynamic Route Parameters in Eleva Router
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Demonstrates the new syntax for defining dynamic route parameters (e.g., :id) compared to old static routes, enabling more flexible routing.
```js
// Old static routes
{ path: "/user", component: UserComponent }
// New dynamic routes
{ path: "/users/:id", component: UserDetailComponent }
```
--------------------------------
### Troubleshooting: Enable Eleva Router Debug Mode
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Explains how to enable verbose logging for debugging by opening the browser console, where Eleva Router logs important events and errors.
```APIDOC
Troubleshooting: Debug Mode
Action: Open browser console
Effect: Eleva Router logs important events and errors for debugging
```
--------------------------------
### Programmatic Navigation Using Eleva Router Instance
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
This snippet demonstrates how to perform programmatic navigation from outside an Eleva.js component by directly calling the `navigate` method on the `app.router` instance. It shows how to navigate to a path with or without route parameters.
```js
await app.router.navigate("/about");
await app.router.navigate("/users/:id", { id: 123 });
```
--------------------------------
### Define Dynamic Route Parameters in Eleva Router
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
This snippet shows how to define routes with dynamic segments using colon syntax (`:param`) and catch-all parameters (`:path*`) in Eleva Router. It demonstrates various patterns for creating flexible routing structures.
```js
app.use(ElevaRouter, {
container: document.getElementById("app"),
mode: "history",
routes: [
{ path: "/", component: HomeComponent },
{ path: "/users/:id", component: UserDetailComponent },
{ path: "/blog/:category/:slug", component: BlogPostComponent },
{ path: "/files/:path*", component: FileViewerComponent }
]
});
```
--------------------------------
### Implement Error Handling for Eleva Router Navigation
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Shows the recommended way to handle navigation errors using a try-catch block, improving application robustness compared to the old approach.
```js
// Old way
app.router.navigate("/path");
// New way (recommended)
try {
await app.router.navigate("/path");
} catch (error) {
console.error("Navigation failed:", error);
}
```
--------------------------------
### Use Different Query Parameters for Multiple Eleva Router Instances
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Confirms that each router instance can have its own queryParam setting, allowing multiple applications or routers to use distinct parameter names.
```APIDOC
Multiple Query Parameters:
Support: Yes, each router instance can have its own queryParam setting
Benefit: Allows different parameter names for multiple routers/applications
```
--------------------------------
### Eleva Router Supported Routing Modes
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Explains the available routing modes: "hash", "query", and "history", which can be configured via plugin options.
```APIDOC
Supported Routing Modes:
- "hash"
- "query"
- "history"
Configuration: via plugin options
```
--------------------------------
### Troubleshooting: Eleva Router Component Not Mounted
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Offers solutions for components failing to mount, suggesting verification of the container DOM element and proper component definition.
```APIDOC
Troubleshooting: Component Not Mounted
Checks:
- Container DOM element exists and is valid
- Component is properly defined
```
--------------------------------
### Clean Up Eleva Router Instance
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Instructs users to call await app.router.destroy() to properly clean up event listeners and unmount components when the application shuts down.
```APIDOC
Router Cleanup:
Method: await app.router.destroy()
Purpose: Clean up event listeners and unmount components
```
--------------------------------
### Troubleshooting: Eleva Router Mode Issues
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Advises double-checking that the specified routing mode is one of "hash", "query", or "history", and to check the browser console for validation errors.
```APIDOC
Troubleshooting: Routing Mode Issues
Checks:
- Mode is "hash", "query", or "history"
- Browser console for validation errors
```
--------------------------------
### Update Eleva Router Package Version
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Instructions to update the Eleva Router package to the latest version using npm.
```bash
npm update eleva-router
```
--------------------------------
### Handle Routing Errors in Eleva Router
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Recommends wrapping navigation calls in try-catch blocks and implementing error boundaries using default routes for robust error handling.
```APIDOC
Error Handling in Routing:
Method 1: Wrap navigation calls in try-catch blocks
Method 2: Implement error boundaries using default routes
```
--------------------------------
### Eleva Router: Implementing Safe Navigation with Try-Catch
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
This snippet demonstrates how to implement custom error handling for navigation attempts within an Eleva Router component. By wrapping `navigate` calls in a `try-catch` block, applications can gracefully handle navigation failures, log errors, and provide fallback behavior, such as redirecting to a safe route.
```js
const RobustComponent = {
setup: ({ route, navigate }) => {
const safeNavigate = async (path) => {
try {
await navigate(path);
} catch (error) {
console.error("Navigation failed:", error);
// Fallback behavior
await navigate("/");
}
};
return { safeNavigate };
},
template: (ctx) => `
`,
};
```
--------------------------------
### Troubleshooting: Eleva Router Memory Leaks
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Recommends calling app.router.destroy() on application shutdown and checking for duplicate router instances to prevent memory leaks.
```APIDOC
Troubleshooting: Memory Leaks
Checks:
- Call app.router.destroy() on application shutdown
- Check for duplicate router instances
```
--------------------------------
### Clean Up Eleva Router on Application Shutdown
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Provides a recommended method to ensure proper cleanup of the router instance and its resources when the application is about to unload, preventing memory leaks.
```js
window.addEventListener("beforeunload", async () => {
await app.router.destroy();
});
```
--------------------------------
### Match a path to an existing route with ElevaRouter
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
This function attempts to find a route that matches the given path. If a match is found, it returns an object containing the matched route definition and any extracted parameters from the path. Otherwise, it returns null.
```js
const match = app.router.matchRoute("/users/123");
// Returns: { route: {...}, params: { id: "123" } }
```
--------------------------------
### Define Default Route in Eleva Router
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Details how to specify a fallback route using the defaultRoute option in the plugin configuration, used when no other route matches.
```APIDOC
Default Route Definition:
Option: defaultRoute
Purpose: Specifies a fallback route if no match is found
```
--------------------------------
### Troubleshooting: Eleva Router Hash Mode Issues
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Warns against manually manipulating window.location.hash outside of the router's navigation methods when using hash mode.
```APIDOC
Troubleshooting: Hash Mode Issues
Warning: Do not manually manipulate window.location.hash outside of router's navigation methods
```
--------------------------------
### Eleva Router routeChanged() Method API
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Documentation for the `routeChanged()` method of the `Router` class. This is an internal method invoked on URL changes, responsible for extracting path and query parameters and mounting the corresponding component. It includes comprehensive error handling.
```APIDOC
async routeChanged():
Description: Internal method called on URL changes; extracts the current path and query parameters, and mounts the corresponding component. Includes comprehensive error handling.
```
--------------------------------
### Add a new route dynamically with ElevaRouter
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
This method allows for the dynamic addition of new routes to the router instance. It performs validation on the provided route structure to ensure correctness before integration.
```js
app.router.addRoute({
path: "/new-page",
component: NewPageComponent,
props: { title: "New Page" }
});
```
--------------------------------
### Eleva Router destroy() Method API
Source: https://github.com/tarekraafat/eleva-router/blob/master/docs/index.md
Documentation for the `destroy()` method of the `Router` class. This asynchronous method stops the router, cleans up all event listeners, and unmounts the current component. It is safe to call multiple times.
```APIDOC
async destroy():
Description: Stops the router, cleans up all event listeners, and unmounts the current component. Safe to call multiple times.
Example:
await app.router.destroy();
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.