### Install Svelte SPA Router v5.0 Source: https://svelte-spa-router.keenmate.dev/whats-new This command demonstrates how to install version 5.0 of the Svelte SPA Router using npm. It's the recommended way to get started with the latest features and performance improvements. ```bash npm install @keenmate/svelte-spa-router@5 ``` -------------------------------- ### Complete Svelte SPA Router Configuration Example Source: https://svelte-spa-router.keenmate.dev/features/route-configuration A comprehensive example demonstrating various route configurations including simple routes, routes with titles, loading components, breadcrumbs, parameters, protected routes, and static props. ```javascript // routes.js import { createRoute } from '@keenmate/svelte-spa-router/wrap' import Home from './routes/Home.svelte' import Loading from './routes/Loading.svelte' import NotFound from './routes/NotFound.svelte' // Auth check const requireAuth = (detail) => { const user = getCurrentUser() if (!user) { push('/login') return false } return true } export const routes = { // Simple route (no async loading) '/': Home, // Route with title and loading component '/about': createRoute({ component: () => import('./routes/About.svelte'), title: 'About Us', loadingComponent: Loading }), // Route with breadcrumbs '/products': createRoute({ component: () => import('./routes/Products.svelte'), title: 'Products', breadcrumbs: [ { label: 'Home', path: '/' }, { label: 'Products' } ], loadingComponent: Loading }), // Route with parameters and breadcrumbs '/products/:id': createRoute({ component: () => import('./routes/ProductDetail.svelte'), title: 'Product Details', breadcrumbs: [ { label: 'Home', path: '/' }, { label: 'Products', path: '/products' }, { label: 'Details' } ], loadingComponent: Loading }), // Protected route with condition '/dashboard': createRoute({ component: () => import('./routes/Dashboard.svelte'), title: 'Dashboard', conditions: [requireAuth], breadcrumbs: [ { label: 'Home', path: '/' }, { label: 'Dashboard' } ], loadingComponent: Loading }), // Route with static props '/help': createRoute({ component: () => import('./routes/Help.svelte'), title: 'Help Center', props: { showSearch: true, category: 'general' }, loadingComponent: Loading }), // Catch-all 404 '*': NotFound } ``` -------------------------------- ### Svelte 5 Runes Authentication Example Source: https://svelte-spa-router.keenmate.dev/features/permissions This Svelte 5 example demonstrates a basic runes-based authentication system. It manages the current user state, provides functions for login, logout, and checking authentication status. It assumes an external API for login requests. ```javascript // auth.svelte.js - Svelte 5 runes-based authentication let currentUserState = $state(null) export function getCurrentUser() { return currentUserState } export async function login(username, password) { // Call your API const response = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }) if (response.ok) { const user = await response.json() currentUserState = user return true } return false } export function logout() { currentUserState = null push('/login') } // Check if user is authenticated export function isAuthenticated() { return currentUserState !== null } ``` -------------------------------- ### Install @keenmate/svelte-spa-router Source: https://svelte-spa-router.keenmate.dev/about Installs the @keenmate/svelte-spa-router package using npm. This is the first step to integrate the router into your Svelte 5 application. ```bash npm install @keenmate/svelte-spa-router ``` -------------------------------- ### Configure @keenmate/svelte-spa-router in main.js Source: https://svelte-spa-router.keenmate.dev/user/123 Example of configuring the @keenmate/svelte-spa-router in your Svelte 5 application's main entry file (main.js). This involves importing and initializing the router. ```javascript import { Router } from "@keenmate/svelte-spa-router" const routes = [ { name: "home", path: "/" }, { name: "about", path: "/about" }, { name: "contact", path: "/contact" }, ]; new Router({ routes, target: "#app", }); ``` -------------------------------- ### Basic Svelte Route Component Example Source: https://svelte-spa-router.keenmate.dev/getting-started This is a simple Svelte component that can be used as a route in svelte-spa-router. It displays a basic welcome message and serves as a foundational example for creating route components. ```svelte # Welcome Home! This is your first route component. ``` -------------------------------- ### Navigation Guards with @keenmate/svelte-spa-router Source: https://svelte-spa-router.keenmate.dev/user/123 Example of implementing navigation guards in @keenmate/svelte-spa-router to control access to routes. This includes using beforeLeave callbacks for route protection. ```javascript function requireAuth(to, from, next) { if (isLoggedIn()) { next(); } else { next('/login'); // Redirect to login if not authenticated } } const routes = [ { name: "dashboard", path: "/dashboard", beforeEnter: requireAuth }, ]; // Or as a component method: // export default { // beforeLeave({ to, from, next }) { // // Logic to prevent leaving the current route // if (isFormDirty) { // if (confirm('You have unsaved changes. Are you sure you want to leave?')) { // next(); // } // } else { // next(); // } // } // }; ``` -------------------------------- ### Zone Component Examples for Multi-Zone Routing in Svelte Source: https://svelte-spa-router.keenmate.dev/features/multi-zone These Svelte code snippets show examples of components designed to be rendered within specific zones ('sidebar', 'main', 'panel') in a multi-zone routing setup. Components like `ProductsMenu.svelte`, `ProductsMain.svelte`, and `ProductsToolbar.svelte` receive route parameters and other props, functioning similarly to regular route components but within their designated layout areas. ```html ``` ```html

Product Catalog

``` ```html

Actions

``` -------------------------------- ### Nested Route Definition Example with createHierarchy Source: https://svelte-spa-router.keenmate.dev/features/nested-routes This example demonstrates defining nested routes using the `createHierarchy` helper function. This approach allows for a tree-like route structure, improving readability and reducing path repetition. ```javascript import { createHierarchy } from '@keenmate/svelte-spa-router/helpers/hierarchy' const routes = createHierarchy({ '/documents': { component: DocumentsLayout, breadcrumbs: [{ label: 'Documents' }], children: { ':id': { component: DocumentDetail, breadcrumbs: [{ label: 'Detail' }], children: { 'logs': { component: DocumentLogs, breadcrumbs: [{ label: 'Logs' }] } } } } } }) ``` -------------------------------- ### Use @keenmate/svelte-spa-router in App.svelte Source: https://svelte-spa-router.keenmate.dev/user/123 Example of integrating the @keenmate/svelte-spa-router into your main App.svelte component. This typically involves placing the router outlet where your routed components will be rendered. ```svelte ``` -------------------------------- ### Programmatic Navigation with push and replace Source: https://svelte-spa-router.keenmate.dev/features/named-routes Demonstrates how to navigate programmatically using push() and replace() functions. Supports array, object, and string formats for route definition. Ensure '@keenmate/svelte-spa-router' is installed. ```javascript import { push, replace } from '@keenmate/svelte-spa-router' // Array format (recommended) await push(['userProfile', { userId: 456 }, { pageNo: 12 }]) // Object format await push({ route: 'documentDetail', params: { documentId: 123 }, query: { tab: 'info', edit: 'true' } }) // String format (legacy - still works) await push('/about') // Same works with replace() await replace(['userProfile', { userId: 456 }]) ``` -------------------------------- ### Svelte Custom Route Metadata (userData) Example Source: https://svelte-spa-router.keenmate.dev/features/metadata Demonstrates how to attach and access custom metadata, such as authentication requirements or analytics data, to specific routes. The example shows route configuration with 'userData' and accessing it within a Svelte component using helper functions. Requires '@keenmate/svelte-spa-router/helpers/route-metadata'. ```javascript // Route configuration '/product/:id': wrap({ component: ProductDetail, title: 'Product', userData: { requiresAuth: true, analytics: { category: 'products', action: 'view' }, theme: 'dark' } }) // In your component
``` -------------------------------- ### Global Error Handling Configuration Source: https://svelte-spa-router.keenmate.dev/whats-new Provides an example of configuring global error handling for svelte-spa-router, including strategies like `navigateSafe` and `restart`. It also demonstrates how to integrate the `GlobalErrorHandler` component into the Svelte application. Dependencies include `@keenmate/svelte-spa-router/helpers/error-handler` and `@keenmate/svelte-spa-router/helpers/GlobalErrorHandler`. ```javascript import { configureGlobalErrorHandler } from '@keenmate/svelte-spa-router/helpers/error-handler' import { GlobalErrorHandler } from '@keenmate/svelte-spa-router/helpers/GlobalErrorHandler' // Configure error handling configureGlobalErrorHandler({ strategy: 'navigateSafe', // or 'restart', 'showError', 'custom' safeRoute: '/', maxRestarts: 3, showToast: true }) // Add to App.svelte ``` -------------------------------- ### Basic Router Usage in App.svelte Source: https://svelte-spa-router.keenmate.dev/about Sets up the Svelte SPA Router in the main App.svelte component by defining routes and rendering the Router component. This example demonstrates mapping paths to Svelte components. ```javascript ``` -------------------------------- ### Configure Querystring System - JavaScript Source: https://svelte-spa-router.keenmate.dev/features/querystring Initializes the querystring system for the router, allowing configuration of array formats. This setup is done once in your application's main entry point. ```javascript // main.js import { configureQuerystring } from '@keenmate/svelte-spa-router/helpers/querystring' configureQuerystring({ arrayFormat: 'auto' // 'auto', 'repeat', or 'comma' }) // Now mount your app mount(App, { target: document.body }) ``` -------------------------------- ### Synchronous Component Loading Example Source: https://svelte-spa-router.keenmate.dev/features/route-configuration Demonstrates how to define routes with synchronously loaded components. These components are part of the initial bundle, leading to faster navigation but a larger initial payload. Suitable for frequently accessed or small components. ```javascript import Home from './routes/Home.svelte' import About from './routes/About.svelte' const routes = { // Synchronous - component loaded immediately '/': Home, '/about': About, // Also synchronous with createRoute() '/contact': createRoute({ component: Contact, // Direct reference title: 'Contact' }) ``` -------------------------------- ### Asynchronous Component Loading Example Source: https://svelte-spa-router.keenmate.dev/features/route-configuration Shows how to define routes with asynchronously loaded (lazy-loaded) components using dynamic imports. This splits the code into chunks, loading components only when needed, which improves initial load time. Ideal for large or infrequently used components. ```javascript const routes = { '/': Home, // Sync - needed immediately // Async - loaded only when user visits these routes '/admin': createRoute({ component: () => import('./routes/Admin.svelte'), // Function returning Promise title: 'Admin Panel', loadingComponent: Loading // Show while loading }), '/reports': createRoute({ component: () => import('./routes/Reports.svelte'), title: 'Reports' }), '/settings': createRoute({ component: () => import('./routes/Settings.svelte'), title: 'Settings' }) ``` -------------------------------- ### Gradual Migration to Named Routes Source: https://svelte-spa-router.keenmate.dev/features/named-routes Provides guidance on migrating from traditional href-based links to named routes using the 'link' action. It shows examples of using both methods and how they can coexist during a transition. ```html View Document View Document ``` -------------------------------- ### E-commerce Product Detail Route Source: https://svelte-spa-router.keenmate.dev/features/parameters Example of defining a route for an e-commerce product detail page. It shows how to extract a product ID from the route parameters and use it to fetch product data. ```javascript const routes = { '/product/:id': ProductDetail } // ProductDetail.svelte let { routeParams = {} } = $props() const productId = routeParams.id // Fetch product data const product = $derived(fetchProduct(productId)) ``` -------------------------------- ### Protect Routes with ANY Permission (OR Logic) Source: https://svelte-spa-router.keenmate.dev/features/permissions Protect individual routes using `createProtectedRoute()`, which simplifies route protection without needing manual wrapping. This example demonstrates a route that requires the user to have at least one of the specified permissions ('admin.read' OR 'admin.write'). ```javascript import { createProtectedRoute } from '@keenmate/svelte-spa-router/helpers/permissions' const routes = { '/': Home, // No wrap() needed! createProtectedRoute() returns ready-to-use wrapped component // User needs 'admin.read' OR 'admin.write' '/admin': createProtectedRoute({ component: () => import('./Admin.svelte'), permissions: { any: ['admin.read', 'admin.write'] }, loadingComponent: Loading, title: 'Admin Panel', breadcrumbs: [ { label: 'Home', path: '/' }, { label: 'Admin' } ] }), '/unauthorized': Unauthorized, '*': NotFound } ``` -------------------------------- ### Configure Permissions with Svelte 5 Runes Source: https://svelte-spa-router.keenmate.dev/features/permissions Sets up the global permission configuration for the application. It defines how to check user permissions against route requirements and specifies an action to take on unauthorized access. This example uses Svelte 5 runes for state management. ```javascript // auth.svelte.js - User state with Svelte 5 runes let currentUserState = $state({ id: 1, name: 'John Doe', role: 'admin', permissions: [ 'admin.read', 'admin.write', 'settings.read', 'settings.write', 'reports.view' ] }) export function getCurrentUser() { return currentUserState } export function setCurrentUser(user) { currentUserState = user } // main.js - Configure permissions import { configurePermissions } from '@keenmate/svelte-spa-router/helpers/permissions' import { push } from '@keenmate/svelte-spa-router' import { getCurrentUser } from './auth.svelte.js' configurePermissions({ checkPermissions: (user, requirements) => { if (!user) return false if (!requirements) return true if (requirements.any) { return requirements.any.some(perm => user.permissions.includes(perm)) } if (requirements.all) { return requirements.all.every(perm => user.permissions.includes(perm)) } return true }, getCurrentUser, onUnauthorized: () => { push('/unauthorized') } }) ``` -------------------------------- ### Enable Hash Routing (Default) Source: https://svelte-spa-router.keenmate.dev/getting-started This JavaScript code demonstrates the setup for using svelte-spa-router in Hash Mode. Hash mode is the default and requires no special configuration, making it suitable for static hosting. It uses the standard Svelte mount function. ```javascript // No configuration needed! // Hash mode is the default import { mount } from 'svelte' import App from './App.svelte' mount(App, { target: document.body }) ``` -------------------------------- ### Hierarchical Route Inheritance Setup Source: https://svelte-spa-router.keenmate.dev/whats-new Demonstrates how to enable and configure hierarchical route inheritance in svelte-spa-router, allowing child routes to inherit properties like breadcrumbs and permissions from parent routes. This reduces code duplication and promotes a more organized route structure. Dependencies include `@keenmate/svelte-spa-router` and `@keenmate/svelte-spa-router/wrap`. ```javascript import { setHierarchicalRoutesEnabled } from '@keenmate/svelte-spa-router' import { createRoute } from '@keenmate/svelte-spa-router/wrap' setHierarchicalRoutesEnabled(true) const routes = { '/documents': createRoute({ component: Documents, breadcrumbs: [{ label: 'Home' }, { label: 'Documents' }], permissions: { any: ['read'] } }), // Child automatically inherits parent breadcrumbs + permissions '/documents/:id': createRoute({ component: DocumentDetail, breadcrumbs: [{ label: 'Detail' }], // Effective: [Home, Documents, Detail] // Must have both 'read' (parent) AND 'documents.view' (child) permissions: { any: ['documents.view'] } }) } ``` -------------------------------- ### Conditional Navigation Logic with svelte-spa-router Source: https://svelte-spa-router.keenmate.dev/features/programmatic-navigation Provides an example of conditional navigation based on user authentication and role. It uses 'push' and 'replace' from svelte-spa-router to direct users to different routes ('login', 'adminPanel', 'userProfile', 'createProfile') based on their status and properties. This ensures users are guided to the appropriate part of the application. ```javascript ``` -------------------------------- ### Configure and Use Protected Routes with Permissions Source: https://svelte-spa-router.keenmate.dev/api Demonstrates how to configure permissions globally and create protected routes using `createProtectedRoute`. Supports role-based and resource-based authorization with flexible checking logic (`any` or `all`). ```javascript import { configurePermissions, createProtectedRoute } from '@keenmate/svelte-spa-router/helpers/permissions' // Configure in main.js configurePermissions({ getUserPermissions: () => ['read', 'write', 'admin.view'] }) // Protected route with role-based permissions const routes = { '/admin': createProtectedRoute({ component: () => import('./Admin.svelte'), permissions: { any: ['admin.view', 'admin.edit'] } }), // With resource-based authorization '/document/:id': createProtectedRoute({ component: () => import('./Document.svelte'), permissions: { any: ['read'] }, authorizationCallback: async (detail) => { const hasAccess = await checkDocumentAccess(detail.routeParams.id) return hasAccess } }) } ``` -------------------------------- ### Basic Route Creation with createRoute() Source: https://svelte-spa-router.keenmate.dev/features/route-configuration Illustrates the basic usage of the createRoute() function for defining routes. This method simplifies route creation by automatically handling component wrapping, eliminating the need for manual wrap() calls. It supports asynchronous loading and provides options for title and loading components. ```javascript import { createRoute } from '@keenmate/svelte-spa-router/wrap' import Home from './routes/Home.svelte' import Loading from './routes/Loading.svelte' const routes = { '/': Home, // No wrap() needed! createRoute() handles it for you '/about': createRoute({ component: () => import('./routes/About.svelte'), title: 'About Us', loadingComponent: Loading }), '/contact': createRoute({ component: () => import('./routes/Contact.svelte'), title: 'Contact', loadingComponent: Loading, loadingParams: { message: 'Loading contact page...' } }) ``` -------------------------------- ### Common Use Cases for Static Prefix Parameters Source: https://svelte-spa-router.keenmate.dev/features/parameters Presents several common use cases for static prefix parameters, including distinguishing between different entity types, versioning API endpoints, and managing namespaced resources. ```javascript // Distinguish between different entity types const routes = { '/doc-:id': DocumentViewer, // /doc-123 '/ticket-:id': TicketViewer, // /ticket-456 '/invoice-:id': InvoiceViewer // /invoice-789 } // Versioned API endpoints const routes = { '/api-v1-:endpoint': ApiV1Handler, // /api-v1-users '/api-v2-:endpoint': ApiV2Handler // /api-v2-users } // Namespaced resources const routes = { '/org-:orgId/team-:teamId': TeamDetail // /org-acme/team-alpha } ``` -------------------------------- ### Integration with Error Tracking Services Source: https://svelte-spa-router.keenmate.dev/features/error-handling Guides on integrating the error handler with external services like Sentry and custom analytics platforms. ```APIDOC ## Integration with Error Tracking Services ### Sentry Integration #### Description Configure the global error handler to send errors to Sentry and then display a user-friendly error UI. #### Configuration Example ```javascript import * as Sentry from '@sentry/svelte' import { configureGlobalErrorHandler } from '@keenmate/svelte-spa-router/helpers/error-handler' configureGlobalErrorHandler({ strategy: 'custom', customHandler: (error, errorInfo) => { // Send to Sentry Sentry.captureException(error, { contexts: { svelte: { componentStack: errorInfo.componentStack } } }) // Then show error UI import { showError } from '@keenmate/svelte-spa-router/helpers/error-handler' showError(error, errorInfo) } }) ``` ### Custom Analytics #### Description Log errors to a custom analytics service before the application attempts to recover by navigating to a safe route. #### Configuration Example ```javascript configureGlobalErrorHandler({ strategy: 'navigateSafe', safeRoute: '/', customHandler: (error) => { // Log to analytics before recovery analytics.track('error_occurred', { error_message: error.message, error_type: error.name, stack_trace: error.stack, user_agent: navigator.userAgent, timestamp: new Date().toISOString() }) } }) ``` ### Parameters for `configureGlobalErrorHandler` - **strategy** (string) - `'custom'` for custom handlers, `'navigateSafe'` for navigating after handling. - **customHandler** (function) - A callback function that receives `error` and `errorInfo` objects. - **safeRoute** (string) - The route to navigate to when using the `'navigateSafe'` strategy. ``` -------------------------------- ### Get Svelte SPA Router Version (Console) Source: https://svelte-spa-router.keenmate.dev/features/logging Checks the currently deployed version of the svelte-spa-router library. This is useful for version compatibility checks and troubleshooting. ```javascript window.components['svelte-spa-router'].version() ``` -------------------------------- ### Reusable Breadcrumb Component Source: https://svelte-spa-router.keenmate.dev/features/metadata Provides an example of creating a reusable breadcrumb component that dynamically displays breadcrumbs based on route metadata, using `routeBreadcrumbs`. ```APIDOC ## Reusable Breadcrumb Component ### Description This section details how to create a flexible and reusable breadcrumb navigation component for your Svelte SPA. The component dynamically renders breadcrumbs based on the `routeBreadcrumbs` reactive store provided by the router. ### Method N/A (UI Component) ### Endpoint N/A ### Parameters None directly for the component itself, it consumes router state. ### Request Example (See `Breadcrumbs.svelte` usage below) ### Response N/A --- ## Breadcrumbs.svelte Component Implementation ### Description An example implementation of a reusable `Breadcrumbs.svelte` component. ### Method N/A ### Endpoint N/A ### Parameters None. ### Request Example ```html {#if hasBreadcrumbs} {/if} ``` --- ## BreadcrumbItem Interface Definition ### Description Defines the structure for individual items within the breadcrumbs array. ### Method N/A ### Endpoint N/A ### Parameters #### Path Parameters None. #### Query Parameters None. #### Request Body None. ### Request Example ```typescript interface BreadcrumbItem { /** Optional ID for partial updates */ id?: string /** Label to display */ label: string /** Optional path for the breadcrumb link */ path?: string } ``` ### Response N/A ``` -------------------------------- ### Implement SPA Navigation and Active Link Highlighting with Svelte Actions Source: https://svelte-spa-router.keenmate.dev/api Shows how to use the `link` and `active` Svelte actions to enable Single Page Application navigation on anchor tags and apply CSS classes to active links respectively. Supports various link configurations. ```javascript import { link } from '@keenmate/svelte-spa-router' import active from '@keenmate/svelte-spa-router/active' // Basic link About // With named route User Profile // Array shorthand Blog // Active highlighting About About ``` -------------------------------- ### Update Dependencies for svelte-spa-router v5 Source: https://svelte-spa-router.keenmate.dev/migration Install the latest versions of Svelte and svelte-spa-router to ensure compatibility with Svelte 5 features. This step is crucial for leveraging runes and other Svelte 5 improvements. ```json { "dependencies": { "svelte": "^5.0.0", "@keenmate/svelte-spa-router": "^5.0.0" } } ``` ```bash npm install svelte@5 @keenmate/svelte-spa-router@5 ``` -------------------------------- ### Configuration Functions Source: https://svelte-spa-router.keenmate.dev/api Configure router behavior before the application mounts, including hash routing, base path, and parameter placeholders. ```APIDOC ## Configuration Functions ### Description Configure the behavior of the Svelte SPA Router. These functions must be called before the application is mounted. ### Method N/A (These are function calls within your Svelte components) ### Endpoints N/A ### Parameters #### `setHashRoutingEnabled(value: boolean)` - **value** (boolean) - `true` to enable hash mode, `false` to enable history mode. Default is `true`. #### `setBasePath(value: string)` - **value** (string) - The base path for history mode (e.g., `'/app'`). #### `setParamReplacementPlaceholder(value: string)` - **value** (string) - The placeholder string for missing route parameters. Default is `'N-A'`. ### Request Example ```javascript import { setHashRoutingEnabled, setBasePath, setParamReplacementPlaceholder, getHashRoutingEnabled, getBasePath, getParamReplacementPlaceholder } from '@keenmate/svelte-spa-router' // Enable history mode setHashRoutingEnabled(false) // Set base path for history mode setBasePath('/my-app') // Set custom placeholder for missing parameters setParamReplacementPlaceholder('MISSING') // Get current settings const hashRouting = getHashRoutingEnabled() const basePath = getBasePath() const placeholder = getParamReplacementPlaceholder() ``` ### Response #### Success Response - **set... functions**: Return `void`. - **get... functions**: Return the current configuration value (`boolean` or `string`). #### Response Example ```json { "hashRoutingEnabled": false, "basePath": "/my-app", "paramReplacementPlaceholder": "MISSING" } ``` ``` -------------------------------- ### Simple Route Definition with createRoute() Source: https://svelte-spa-router.keenmate.dev/features/route-configuration The recommended createRoute() function provides a clean and simple syntax for most use cases. It returns a wrapped component, eliminating the need for manual wrap(). ```javascript // Simple and clean '/about': createRoute({ component: () => import('./About.svelte'), title: 'About', breadcrumbs: [...] }) ``` -------------------------------- ### Route Ordering with Static Prefixes Source: https://svelte-spa-router.keenmate.dev/features/parameters Highlights the critical importance of route order when using static prefix parameters. More specific routes with prefixes must be defined before generic parameter routes to ensure correct matching. ```javascript // ✅ Good - prefix routes before generic routes const routes = { '/route-data-demo': RouteDataDemo, // Specific prefix routes first '/route-data-demo/project-:projectCode': RouteDataDemo, '/route-data-demo/user-:id': RouteDataDemo, '/route-data-demo/project-:code/task-:taskId': RouteDataDemo, // Generic parameter routes after '/route-data-demo/:projectId/:taskId/:commentId': RouteDataDemo, '/route-data-demo/:docId/:versionId': RouteDataDemo, '/route-data-demo/:userId': RouteDataDemo } // ❌ Bad - generic route first catches everything const routes = { '/route-data-demo/:userId': RouteDataDemo, // Too generic, catches all! '/route-data-demo/project-:projectCode': RouteDataDemo, // Never reached! } // Example: /route-data-demo/project-gamma // ✅ Good order: matches project-:projectCode route → { projectCode: "gamma" } // ❌ Bad order: matches :userId route → { userId: "project-gamma" } ``` -------------------------------- ### Enable Specific Log Categories Source: https://svelte-spa-router.keenmate.dev/features/logging Configure the logger to enable only specific categories for debugging. This is useful for isolating issues. It starts by disabling all logging and then selectively enables categories based on the development environment. ```javascript import { disableLogging, setCategoryLevel } from '@keenmate/svelte-spa-router/logger' // Start with all logging disabled disableLogging() // Enable only what you need to debug if (import.meta.env.DEV) { setCategoryLevel('ROUTER', 'debug') setCategoryLevel('ROUTER:NAVIGATION', 'info') } ``` -------------------------------- ### Get all registered routes with getRoutes Source: https://svelte-spa-router.keenmate.dev/features/named-routes Retrieves all currently registered routes using the getRoutes() utility function. This is useful for debugging or introspection. The function returns an object mapping route names to their paths. ```javascript import { getRoutes } from '@keenmate/svelte-spa-router' const routes = getRoutes() console.log(routes) // { home: '/', about: '/about', userProfile: '/users/:userId', ... } ``` -------------------------------- ### Route Wrapping with Async Loading and Conditions Source: https://svelte-spa-router.keenmate.dev/api Wrap routes using the `wrap()` function to enable asynchronous component loading, route guard conditions, static props, and route metadata. Useful for code splitting and implementing route-specific logic. ```javascript import { wrap } from '@keenmate/svelte-spa-router/wrap' import Loading from './Loading.svelte' const routes = { // Async component with loading '/admin': wrap({ component: () => import('./Admin.svelte'), loadingComponent: Loading, conditions: [ async (detail) => { const user = await checkAuth() return user.isAdmin } ] }), // With route metadata '/dashboard': wrap({ component: () => import('./Dashboard.svelte'), routeContext: { title: 'Dashboard', breadcrumbs: [ { label: 'Home', path: '/' }, { label: 'Dashboard' } ] }, shouldDisplayLoadingOnRouteLoad: true }) } ``` -------------------------------- ### Register Before-Leave Navigation Guard (Svelte) Source: https://svelte-spa-router.keenmate.dev/features/callbacks-events Registers a callback function that executes before navigating away from the current route. Throw `NavigationCancelledError` to abort the navigation. This example prevents navigation if form data has unsaved changes. ```javascript
``` -------------------------------- ### Read Filters in Flat Mode (Svelte) Source: https://svelte-spa-router.keenmate.dev/features/filters Accesses filter values reactively in 'flat' mode, where each filter is a separate query parameter. This example demonstrates how to derive and display filter states like search, category, and status. ```svelte

Search: {search}

Category: {category}

Status: {status}

``` -------------------------------- ### Set Up Router and Global Error Handler Components Source: https://svelte-spa-router.keenmate.dev/api Illustrates the integration of the `Router` and `GlobalErrorHandler` components. The `Router` handles route rendering and navigation events, while `GlobalErrorHandler` catches unhandled errors. Configuration options for events and scroll restoration are shown. ```javascript import Router from '@keenmate/svelte-spa-router' import { GlobalErrorHandler } from '@keenmate/svelte-spa-router/helpers/GlobalErrorHandler' const routes = { '/': Home, '/about': About, '/user/:id': User, '*': NotFound } console.log('Loading:', e.detail)} onRouteLoaded={(e) => console.log('Loaded:', e.detail)} onConditionsFailed={() => push('/unauthorized')} onNotFound={() => console.log('404')} /> ``` -------------------------------- ### Navigation Menu with Named Routes Source: https://svelte-spa-router.keenmate.dev/features/named-routes Example of creating a navigation menu using named routes and the 'link' action. It first registers routes using registerRoutes and then uses the 'use:link' directive for navigation. ```html ``` -------------------------------- ### Get Current Restart Count with Error Handler Helpers (JavaScript) Source: https://svelte-spa-router.keenmate.dev/features/error-handling Retrieve the current count of restart attempts using the `getRestartCount` function from the error-handler module. This helps in monitoring and managing application restarts. ```javascript import { getRestartCount } from '@keenmate/svelte-spa-router/helpers/error-handler' const count = getRestartCount() console.log(`Restart attempts: ${count}`) ``` -------------------------------- ### Configuring Category-Based Debug Logging Source: https://svelte-spa-router.keenmate.dev/whats-new Shows how to enable and configure debug logging for svelte-spa-router using hierarchical categories. This facilitates easier debugging of routing issues. It requires `@keenmate/svelte-spa-router/logger` and relies on `import.meta.env.DEV` for development-specific logging. ```javascript import { enableLogging, setCategoryLevel } from '@keenmate/svelte-spa-router/logger' // Enable all debug logging if (import.meta.env.DEV) { enableLogging() } // Or enable specific categories setCategoryLevel('ROUTER:NAVIGATION', 'debug') setCategoryLevel('ROUTER:PERMISSIONS', 'warn') setCategoryLevel('ROUTER:SCROLL', 'info') ``` -------------------------------- ### Protected Routes: Avoiding Back Navigation to Unauthorized Pages Source: https://svelte-spa-router.keenmate.dev/features/referrer-tracking Illustrates how the referrer object automatically excludes routes that failed authorization. The example shows how to determine a safe return path, prioritizing the referrer or a default route. ```javascript // Unauthorized.svelte const referrer = $derived(navContext?.referrer) // Referrer tracks last SUCCESSFULLY loaded route // Won't return to routes that failed auth const returnPath = $derived( referrer?.location || navContext?.returnTo || '/' ) ``` -------------------------------- ### Navigate Programmatically with Svelte SPA Router Source: https://svelte-spa-router.keenmate.dev/api Navigate between routes using push, replace, pop, and goBack functions. These functions support string, array, object, and multi-parameter formats for specifying the target location. 'push' adds to history, 'replace' modifies the current history entry, 'pop' mimics the browser's back button, and 'goBack' navigates to the referrer with scroll restoration. ```javascript import { push, replace, pop, goBack } from '@keenmate/svelte-spa-router' // String format await push('/about') await push('/user/123') // Array format await push(['userProfile', { userId: 123 }]) await push(['search', {}, { q: 'svelte' }]) // Object format await push({ route: 'userProfile', params: { userId: 123 }, query: { tab: 'settings' } }) // Multi-parameter await push('userProfile', { userId: 123 }, { tab: 'settings' }) // Replace (no history) await replace('/login') // Go back (browser history) await pop() // Go back to referrer (with scroll restoration) await goBack() ``` -------------------------------- ### Flat Route Definition Example Source: https://svelte-spa-router.keenmate.dev/features/nested-routes This code snippet shows a typical flat route definition using the `wrap` function from Svelte SPA Router. It's suitable for simple routing structures where routes are not deeply nested. ```javascript import { wrap } from '@keenmate/svelte-spa-router/wrap' const routes = { '/documents': wrap({ component: DocumentsLayout, breadcrumbs: [{ label: 'Documents' }] }), '/documents/:id': wrap({ component: DocumentDetail, breadcrumbs: [{ label: 'Detail' }] }), '/documents/:id/logs': wrap({ component: DocumentLogs, breadcrumbs: [{ label: 'Logs' }] }) } ``` -------------------------------- ### Preserve Query Parameters During Navigation in Svelte Source: https://svelte-spa-router.keenmate.dev/features/programmatic-navigation This example shows how to navigate to a new route while preserving existing query parameters. It extracts current query parameters using `querystring()`, modifies them, and then uses `push` to navigate with the updated parameters. ```javascript import { push } from '@keenmate/svelte-spa-router' import { querystring } from '@keenmate/svelte-spa-router' async function viewItem(itemId) { // Get current filters from query string const currentQuery = querystring() const params = new URLSearchParams(currentQuery) // Preserve existing filters const filters = { category: params.get('category'), sort: params.get('sort'), view: params.get('view') } // Navigate to item with filters preserved await push(['itemDetail', { itemId }, filters]) } ``` -------------------------------- ### Implement Custom Permission Logic Source: https://svelte-spa-router.keenmate.dev/features/permissions Shows how to extend the default permission checking mechanism by providing a custom `checkPermissions` function to `configurePermissions`. This allows for more complex authorization rules, such as role-based access, specific user ID checks, or combining different permission types. ```javascript configurePermissions({ checkPermissions: (user, requirements) => { if (!user) return false // Allow super admin to access everything if (user.role === 'superadmin') { return true } // Check for required role if (requirements.role && user.role !== requirements.role) { return false } // Check for specific user IDs (e.g., beta testers) if (requirements.userIds && !requirements.userIds.includes(user.id)) { return false } // Standard permission checks if (requirements.any) { return requirements.any.some(perm => user.permissions.includes(perm)) } if (requirements.all) { return requirements.all.every(perm => user.permissions.includes(perm)) } return true }, getCurrentUser, onUnauthorized: () => push('/unauthorized') }) ``` -------------------------------- ### Displaying 'Go Back' Button on 404 Pages Source: https://svelte-spa-router.keenmate.dev/features/referrer-tracking Configures the router to include referrer information for 'notfound' routes and provides a Svelte component example to display a 'Go Back' button that returns the user to the last valid route. ```javascript // main.js setIncludeReferrer('notfound') // NotFound.svelte import { goBack, navigationContext } from '@keenmate/svelte-spa-router' const navContext = $derived(navigationContext()) const referrer = $derived(navContext?.referrer) const attemptedRoute = $derived(navContext?.attemptedRoute) {#if referrer} {/if} ``` -------------------------------- ### Configure Permissions in main.js Source: https://svelte-spa-router.keenmate.dev/features/permissions Configure the permission system globally in your application's main entry point (`main.js`). This involves providing functions for checking user permissions, retrieving the current user, and handling unauthorized access. It's crucial to call this before mounting your Svelte app. ```javascript // main.js import { configurePermissions } from '@keenmate/svelte-spa-router/helpers/permissions' import { getCurrentUser } from './auth.svelte.js' configurePermissions({ // Function to check if user has required permissions checkPermissions: (user, requirements) => { if (!user) return false if (!requirements) return true // Check if user has ANY of the required permissions (OR logic) if (requirements.any) { return requirements.any.some(perm => user.permissions.includes(perm) ) } // Check if user has ALL required permissions (AND logic) if (requirements.all) { return requirements.all.every(perm => user.permissions.includes(perm) ) } return true }, // Function to get current user getCurrentUser, // Handler for unauthorized access onUnauthorized: (detail) => { push('/unauthorized') } }) // Now mount your app mount(App, { target: document.body }) ```