### Navigate to Sample and Install Dependencies
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/README.md
Commands to navigate into a specific sample application directory (e.g., basic-routing) and install its unique dependencies. This is a prerequisite for running the sample.
```sh
# Navigate to a sample
cd examples/…
# For example
cd examples/basic-routing
# Start a development server
pnpm install
pnpm run dev
```
--------------------------------
### Complete Router Configuration Example
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/configuration.md
This example demonstrates a full configuration of the svelte-spa-router, including defining routes with static and asynchronous components, setting up loading components, and implementing route guards. It also shows how to handle various route lifecycle events.
```svelte
```
--------------------------------
### Install Dependencies and Build Package
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/README.md
Commands to install project dependencies and build the svelte-spa-router package from the repository root. These are necessary before running any sample applications.
```sh
# From the repo root: install deps and build the package
pnpm install
pnpm run build
```
--------------------------------
### Dynamic Routes Example
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/README.md
Configure routes to use dynamically-imported components by wrapping them with the 'wrap' method. This example shows dynamic imports for Author and Book routes.
```js
// Import the wrap method
import {wrap} from 'svelte-spa-router/wrap'
// Note that Author and Book are not imported here anymore, so they can be imported at runtime
import Home from './routes/Home.svelte'
import NotFound from './routes/NotFound.svelte'
const routes = {
'/': Home,
// Wrapping the Author component
'/author/:first/:last?': wrap({
asyncComponent: () => import('./routes/Author.svelte')
}),
// Wrapping the Book component
'/book/*': wrap({
asyncComponent: () => import('./routes/Book.svelte')
}),
// Catch-all route last
'*': NotFound,
}
```
--------------------------------
### Install svelte-spa-router
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/README.md
Install the svelte-spa-router package using your preferred package manager.
```sh
# Using npm
npm install svelte-spa-router
# Using yarn
yarn install svelte-spa-router
# Using pnpm
pnpm install svelte-spa-router
```
--------------------------------
### Navigation Examples
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/REFERENCE.md
Navigate programmatically using the push function or declaratively in templates using the link action.
```javascript
import {push, link} from 'svelte-spa-router'
// Programmatic navigation
push('/books')
// In templates: use link action
View Books
```
--------------------------------
### Example Usage of onRouteLoading and onRouteLoaded
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/Advanced Usage.md
This example demonstrates how to implement and use the `onRouteLoading` and `onRouteLoaded` callbacks within a Svelte `Router` component to log route-related information.
```svelte
```
--------------------------------
### Basic Routing Setup
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/REFERENCE.md
Define routes for your Svelte SPA. Import necessary components and map URL paths to them. Use '*' for a catch-all 404 route.
```javascript
import Router from 'svelte-spa-router'
import Home from './Home.svelte'
import Books from './Books.svelte'
import NotFound from './NotFound.svelte'
const routes = {
'/': Home,
'/books': Books,
'*': NotFound
}
```
--------------------------------
### Route Pre-condition Example
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/types.md
Demonstrates how to implement both synchronous and asynchronous pre-condition functions for route protection. These functions check for authentication and authorization before loading a route.
```javascript
import {wrap} from 'svelte-spa-router/wrap'
// Synchronous pre-condition
const isAuthenticated = (detail) => {
return !!localStorage.getItem('token')
}
// Asynchronous pre-condition
const checkAuthorization = async (detail) => {
const response = await fetch('/api/check-role', {
method: 'POST',
body: JSON.stringify({route: detail.route})
})
return response.ok
}
const routes = {
'/dashboard': wrap({
component: Dashboard,
conditions: [isAuthenticated, checkAuthorization]
})
}
```
--------------------------------
### Combined Features Example
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/api-reference/wrap.md
An example showcasing the combination of multiple features within wrap(): async component, loading component, route guard, static props, and user data.
```javascript
import AdminPanel from './AdminPanel.svelte'
import AdminLoading from './AdminLoading.svelte'
import {wrap} from 'svelte-spa-router/wrap'
const requireAdmin = (detail) => {
return detail.userData?.roles?.includes('admin') ?? false
}
const routes = {
'/admin': wrap({
asyncComponent: () => import('./Admin.svelte'),
loadingComponent: AdminLoading,
loadingParams: {message: 'Loading admin panel...'},
conditions: [requireAdmin],
props: {sidebar: true},
userData: {
roles: ['admin'],
title: 'Administration'
}
})
}
```
--------------------------------
### Regular Expression Path Matching Example
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/api-reference/active.md
An example of using a regular expression directly in the `use:active` directive to match paths starting with '/'. This is useful for dynamic route segments.
```javascript
use:active={/^\/*\/hi$/} // matches /hi, /foo/hi, etc.
```
--------------------------------
### Link Action Usage Example
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/types.md
Demonstrates how to use the `use:link` action with options to navigate to a specific route, with the ability to update the destination reactively.
```svelte
Navigate
```
--------------------------------
### wrap() Function
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/README.md
Documentation for the wrap() function, including its options and usage examples.
```APIDOC
## wrap() Function
### Description
A utility function used for advanced routing configurations or integrations.
### Options
(Details on options for `wrap()` would be listed here if available in the source)
### Examples
(Usage examples for `wrap()` would be listed here if available in the source)
```
--------------------------------
### Nested Routers Example
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/patterns.md
Demonstrates how to implement nested routing by defining separate route maps for main and nested routers. The nested router is activated based on a prefix.
```svelte
My App
```
```javascript
// routes.js
import Home from './routes/Home.svelte'
import NotFound from './routes/NotFound.svelte'
import AdminHome from './routes/admin/Home.svelte'
import AdminUsers from './routes/admin/Users.svelte'
import AdminSettings from './routes/admin/Settings.svelte'
export const mainRoutes = {
'/': Home,
'*': NotFound
}
export const adminRoutes = {
'/': AdminHome,
'/users': AdminUsers,
'/settings': AdminSettings,
'*': NotFound
}
```
--------------------------------
### Route Pattern Syntax Examples
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/INDEX.md
Demonstrates the various syntaxes for defining route patterns, including exact paths, named and optional parameters, wildcards, and regular expressions with named capture groups. This covers flexible route matching.
```javascript
'/' // Exact root
'/about' // Exact path
'/user/:id' // Named parameter
'/user/:id?' // Optional parameter
'/files/*' // Wildcard (captures remainder as params.wild)
'*' // Catch-all (must be last)
// RegExp routes
/^\/user\/(\d+)$/
/^\[(?
[a-z]+)$/ // Named capture groups
```
--------------------------------
### Loading Placeholder Component Example
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/Advanced Usage.md
Define a Svelte component to be displayed while a route's module is being downloaded. The `params` prop can be used to pass data to this component.
```svelte
Loading
{#if params && params.message}
Message is {params.message}
{/if}
```
--------------------------------
### Active Action Usage Example
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/types.md
Demonstrates how to use the `use:active` action on an anchor tag to apply CSS classes based on the current route's activity.
```svelte
Books
```
--------------------------------
### String Path Matching Example
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/api-reference/active.md
Basic usage of the `use:active` directive with a string path for exact matching. The 'active' class is added when the link's href exactly matches the current location.
```svelte
Books
```
--------------------------------
### Define Component with Props
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/Advanced Usage.md
Example of a Svelte component that accepts a 'num' prop.
```svelte
The secret number is {num}
```
--------------------------------
### Parsing Querystring with qs Library
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/Advanced Usage.md
Parse the querystring into a JavaScript object using the 'qs' library for easier data access. Ensure 'qs' is installed and imported. Use a derived store to react to querystring changes.
```svelte
{JSON.stringify(parsed)}
```
--------------------------------
### Admin Section Routes
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/route-matching.md
Define routes for an admin section with multiple sub-sections. This example shows a flat structure for admin routes.
```javascript
const routes = {
'/admin': AdminHome,
'/admin/users': AdminUsers,
'/admin/users/:id': AdminUserDetail,
'/admin/settings': AdminSettings
}
```
--------------------------------
### RouteDetailLoaded Usage Example
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/types.md
Demonstrates how to use the onRouteLoaded callback to access details of a loaded route component, including its name and the component instance.
```svelte
```
--------------------------------
### Display Specific Parameter
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/api-reference/router-state.md
A Svelte template example showing how to access and display a specific route parameter, such as 'id', using optional chaining for safety.
```svelte
Book ID: {router.params?.id}
```
--------------------------------
### Conditional Rendering Based on Route
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/api-reference/router-state.md
An example of using Svelte's block syntax to conditionally render different components based on the current router location.
```svelte
{#if router.location === '/'}
{:else if router.location === '/about'}
{:else}
{/if}
```
--------------------------------
### Define Synchronous Route Pre-conditions
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/Advanced Usage.md
Use `wrap` with a `conditions` array containing synchronous functions to guard routes. Each function receives route details and must return a boolean. This example shows a route with two pre-conditions: one that randomly succeeds 50% of the time and another that always succeeds.
```svelte
```
--------------------------------
### Import Paths
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/MANIFEST.txt
Demonstrates the correct import paths for accessing the router's functionalities.
```APIDOC
## Import Paths
### Main Entry
```javascript
import Router from 'svelte-spa-router'
import { router, push, pop, replace, link } from 'svelte-spa-router'
```
### wrap() Function
```javascript
import { wrap } from 'svelte-spa-router/wrap'
```
### active Action
```javascript
import active from 'svelte-spa-router/active'
```
```
--------------------------------
### Displaying Current Page Location and Querystring
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/README.md
Use `router.loc` to get both the current page location and its associated querystring.
```svelte
The current page is: {router.loc}
```
--------------------------------
### Conditional Navigation
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/patterns.md
Perform navigation based on certain conditions, such as user authentication. This example shows navigating to the dashboard only after successful authentication.
```svelte
```
--------------------------------
### Code-Splitting with wrap()
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/README.md
Demonstrates how to implement code-splitting for dynamic routes using the `wrap` function. This is useful for lazy-loading components.
```javascript
wrap({asyncComponent: () => import('./Page.svelte')})
```
--------------------------------
### Run Tests
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/REFERENCE.md
Execute the end-to-end tests for the svelte-spa-router package using pnpm.
```bash
pnpm test
```
--------------------------------
### Import Router
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/api-reference/router-state.md
Import the router singleton from the svelte-spa-router library.
```javascript
import {router} from 'svelte-spa-router'
```
--------------------------------
### Loading UI with wrap()
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/README.md
Explains how to specify a loading component that is displayed while a route's component is being loaded, using the `wrap` function. This enhances user experience during navigation.
```javascript
wrap({loadingComponent: Loading})
```
--------------------------------
### Regular Expression with Named Groups
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/api-reference/active.md
Uses a regular expression with capturing groups to define the active state. This example matches the base admin path and any sub-paths.
```svelte
Admin Panel
```
--------------------------------
### Navigate to a New Page with push()
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/api-reference/navigation.md
Use the push() function to navigate to a new location and add an entry to the browser's history. This is typically used for forward navigation.
```svelte
```
--------------------------------
### Configure Async Route with Loading Component
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/Advanced Usage.md
Configure an asynchronous route using `wrap`, specifying the `asyncComponent`, a `loadingComponent` to display during download, and `loadingParams` to pass data to the loading component.
```javascript
// Import the wrap method
import {wrap} from 'svelte-spa-router/wrap'
// Statically-included components
import Loading from './Loading.svelte'
// Route definition object
const routes = {
// Wrapping the Book component
'/book/*': wrap({
// Dynamically import the Book component
asyncComponent: () => import('./Book.svelte'),
// Display the Loading component while the request for the Book component is pending
loadingComponent: Loading,
// Value for `params` in the Loading component
loadingParams: {
message: 'secret',
foo: 'bar'
}
})
}
```
--------------------------------
### Import Navigation Functions
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/api-reference/navigation.md
Import the necessary navigation functions from the 'svelte-spa-router' library.
```javascript
import {push, pop, replace} from 'svelte-spa-router'
```
--------------------------------
### Route Guards with wrap()
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/README.md
Shows how to use route guards (conditions) with the `wrap` function to control access to routes. This is essential for implementing authentication and authorization.
```javascript
wrap({conditions: [isLoggedIn, isAdmin]})
```
--------------------------------
### Importing Router Utilities
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/MANIFEST.txt
Import essential utilities like the router state singleton and navigation functions.
```typescript
import {router, push, pop, replace, link} from 'svelte-spa-router'
```
--------------------------------
### Wrapped Component Configuration
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/INDEX.md
Defines the structure for wrapping components, enabling features like asynchronous loading, route guards (conditions), and custom props. This is used for advanced route setups.
```typescript
// Advanced
interface WrappedComponent {
component: AsyncSvelteComponent
conditions?: RoutePrecondition[]
props?: Record
userData?: object
}
type RoutePrecondition = (detail: RouteDetail) => boolean | Promise
```
--------------------------------
### Migrate component events to callback props in svelte-spa-router 5.x
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/UPGRADING.md
Change custom component event listeners to callback props when upgrading to svelte-spa-router 5.x. For example, 'on:routeLoading' becomes 'onRouteLoading'.
```diff
-
+
```
```diff
-
+
```
--------------------------------
### Update use:active syntax for options (v1.x to v2.x)
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/UPGRADING.md
The `use:active` action now accepts a single object argument for its options, including `path` and `className`. A string argument is still supported as a shorthand for `path`.
```svelte
Say hi!Say hi with a default className!Say hi with all default options!
```
```svelte
Say hi!Say hi with a default className!Say hi with all default options!
```
--------------------------------
### Main Entry Point Exports
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/REFERENCE.md
Exports available from the main 'svelte-spa-router' entry point. Includes router components, navigation functions, and related types.
```typescript
export {Router, router, push, pop, replace, link}
export type {RouterProps, RouterState, ...} // All types
```
--------------------------------
### Handle Failed Route Pre-conditions
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/Advanced Usage.md
Implement the `onConditionsFailed` callback prop on the `Router` component to handle scenarios where a route fails its pre-condition checks. This example logs the failure details and conditionally replaces the route.
```svelte
```
--------------------------------
### Project File Structure
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/README.md
This snippet shows the directory structure of the svelte-spa-router project, highlighting key markdown files and their purpose.
```tree
output/
├── README.md ← Start here for overview
├── INDEX.md ← Navigation index
├── REFERENCE.md ← Project overview
├── configuration.md ← Props and configuration
├── types.md ← Type definitions
├── route-matching.md ← Route patterns
├── patterns.md ← Usage patterns
└── api-reference/
├── Router.md ← Router component
├── router-state.md ← Router state object
├── navigation.md ← Navigation functions
├── wrap.md ← wrap() function
└── active.md ← active action
```
--------------------------------
### Creating Nested Routers
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/api-reference/Router.md
Use the `prefix` prop on the `Router` component to define nested routes that activate only when the URL path starts with a specified string. The prefix is removed before matching routes within the nested router.
```svelte
```
--------------------------------
### Dynamic Import for Code-Splitting
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/api-reference/wrap.md
Demonstrates using wrap() with asyncComponent for dynamic imports, enabling code-splitting for route components. This improves initial load performance.
```javascript
import {wrap} from 'svelte-spa-router/wrap'
const routes = {
'/book/:id': wrap({
asyncComponent: () => import('./BookDetail.svelte')
})
}
```
--------------------------------
### Automatic URL parameter decoding in svelte-spa-router 3.x
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/UPGRADING.md
Starting with svelte-spa-router 3.x, URL parameters are automatically decoded using decodeURIComponent. If your application previously performed manual decoding, remove that step to avoid issues.
```text
For example, if you have a route similar to `/book/:name` and your users navigate to `/book/dante%27s%20inferno`:
- ❌ The **old** behavior (svelte-spa-router 2 and older) was to assign `dante%27s%20inferno` to `params.name`
- ✅ The **new** behavior in svelte-spa-router 3 is to assign `dante's inferno` to `params.name`
This is done by invoking [`decodeURIComponent`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent).
```
--------------------------------
### Import Link Action
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/api-reference/navigation.md
Import the `link` action from 'svelte-spa-router' to enable hash-based routing for anchor elements.
```javascript
import {link} from 'svelte-spa-router'
```
--------------------------------
### Define Asynchronous Route Pre-conditions
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/Advanced Usage.md
Pre-conditions can be asynchronous functions, allowing for operations like network requests. This example uses an `async` function to check user admin status via a `fetch` call before loading the `/admin` route.
```javascript
const routes = {
// This route has an async function as pre-condition
'/admin': wrap({
// Use a dynamically-loaded component for this
asyncComponent: () => import('./Admin.svelte'),
// Adding one pre-condition that's an async function
conditions: [
async (detail) => {
// Make a network request, which are async operations
const response = await fetch('/user/profile')
const data = await response.json()
// Return true to continue loading the component, or false otherwise
if (data.isAdmin) {
return true
}
else {
return false
}
}
]
})
}
```
--------------------------------
### Dynamic Routes with Code-Splitting
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/patterns.md
Implement dynamic route loading using code-splitting for better performance. Supports async components and loading components.
```javascript
import {wrap} from 'svelte-spa-router/wrap'
import Loading from './Loading.svelte'
const routes = {
'/': () => import('./routes/Home.svelte'),
'/dashboard': wrap({
asyncComponent: () => import('./routes/Dashboard.svelte'),
loadingComponent: Loading
}),
'/admin': wrap({
asyncComponent: () => import('./routes/Admin.svelte'),
loadingComponent: Loading,
conditions: [isAdmin]
})
}
```
--------------------------------
### Handle Failed Route Conditions
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/configuration.md
Use this callback to intercept and handle situations where a route's pre-conditions are not met. It allows for custom logic such as logging the failed navigation attempt and redirecting the user, for example, to a login page. The callback receives detailed information about the attempted route.
```javascript
import {push} from 'svelte-spa-router'
function handleConditionsFailed(detail) {
console.log('Access denied to:', detail.location)
// Redirect to login
push('/login')
}
```
--------------------------------
### onRouteLoading
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/api-reference/Router.md
Fired when a route is matched and begins loading, before the component renders. It receives route details, location, query string, parameters, and custom user data.
```APIDOC
## onRouteLoading
### Description
Fired when a route is matched and begins loading, before the component renders.
### Parameters
#### RouteDetail parameter:
- `route` (object) - the matched route definition
- `location` (string) - current path
- `querystring` (string) - current query string
- `params` (object) - matched route parameters
- `userData` (any) - custom data from `wrap()`
### Example
```svelte
```
```
--------------------------------
### Routes with Parameters
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/patterns.md
Define routes that accept parameters in the URL path. Parameters are denoted by a colon (:). Wildcards (*) are also supported.
```javascript
const routes = {
'/': Home,
'/blog/:slug': BlogPost,
'/user/:id/settings': UserSettings,
'/user/:id/settings/:tab?': UserSettingsTab,
'/files/*': FileExplorer,
'*': NotFound
}
```
--------------------------------
### API Versioning with Regex Routes
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/route-matching.md
Implement API versioning by using regular expressions to match different API versions. This allows for gradual rollout of new API versions without breaking existing clients.
```javascript
const routes = new Map()
routes.set(/^\/api\/v(\d+)\/users$/, ApiUsers)
routes.set(/^\/api\/v(\d+)\/posts$/, ApiPosts)
```
--------------------------------
### Version 2.x Route Pre-conditions and Events
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/UPGRADING.md
Demonstrates the updated approach in version 2.x using a unified 'detail' object for route pre-conditions and events. This object provides component, name, location, querystring, and userData.
```javascript
// Route pre-conditions
const routes = {
'/hello': wrap(
Hello,
(detail) => {
console.log(detail.location, detail.querystring, detail.name, detail.component, detail.userData)
return true
}
),
// This route adds custom user data
'/foo': wrap(
Foo,
{foo: 'bar'},
(detail) => {
console.log(detail.location, detail.querystring, detail.name, detail.component, detail.userData)
return true
}
)
}
// Handles the "conditionsFailed" event
function conditionsFailed(event) {
// Component name is now on event.detail.name
console.error(event.detail.name)
}
// Handles the "routeLoaded" event
function routeLoaded(event) {
// Component name is now on event.detail.name
console.error(event.detail.name)
}
```
--------------------------------
### Dynamic Imports for Code-Splitting
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/REFERENCE.md
Implement code-splitting by using the 'wrap' utility to dynamically import components. This defers loading until the route is accessed.
```javascript
import {wrap} from 'svelte-spa-router/wrap'
const routes = {
'/books/:id': wrap({
asyncComponent: () => import('./BookDetail.svelte'),
loadingComponent: LoadingScreen
})
}
```
--------------------------------
### Passing Props with wrap()
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/README.md
Illustrates how to pass static props to components when defining routes using the `wrap` function. This allows for pre-configuration of component data.
```javascript
wrap({props: {title: 'Hello'}})
```
--------------------------------
### Parsing Querystring with qs library
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/api-reference/router-state.md
Use the 'qs' third-party library to parse the router's querystring.
```javascript
import qs from 'qs'
const params = qs.parse(router.querystring)
```
--------------------------------
### Catch-All Route for Not Found
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/route-matching.md
Define a '*' route as the last entry to catch any paths not matched by preceding routes. This route results in null parameters.
```javascript
const routes = {
'/': Home,
'/about': About,
'*': NotFound // Catch-all (must be last)
}
```
--------------------------------
### Programmatic Navigation with push, pop, replace
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/README.md
Navigate programmatically using `push` for forward navigation, `pop` for back navigation, and `replace` to change the current history entry. These functions are imported from 'svelte-spa-router'.
```js
import {push, pop, replace} from 'svelte-spa-router'
// The push(url) method navigates to another page, just like clicking on a link
push('/book/42')
// The pop() method is equivalent to hitting the back button in the browser
pop()
// The replace(url) method navigates to a new page, but without adding a new entry in the browser's history stack
// So, clicking on the back button in the browser would not lead to the page users were visiting before the call to replace()
replace('/book/3')
```
--------------------------------
### Define routes using wrap with a static component
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/Advanced Usage.md
Configure routes using the `wrap` method with a statically imported Svelte component. The `userData` option can pass custom data to route callbacks.
```js
import Books from './Books.svelte'
// Using a dictionary to define the route object
const routes = {
'/books': wrap({
component: Books,
userData: {foo: 'bar'}
})
}
```
```js
import Books from './Books.svelte'
// Using a map
const routes = new Map()
routes.set('/books', wrap({
component: Books,
userData: {foo: 'bar'}
}))
```
--------------------------------
### Route Definition Order
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/route-matching.md
Routes are tested in definition order, and the first matching route wins. More specific routes should be defined before less specific ones.
```javascript
const routes = {
'/': Home,
'/user/:id': UserDetail, // More specific
'/user/:id/edit': UserEdit, // More specific still
'/user/*': UserProfile, // Less specific
'/blog/*': Blog,
'*': NotFound // Catch-all (must be last)
}
```
--------------------------------
### Custom User Data with wrap()
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/README.md
Demonstrates how to attach custom user data to a route definition using the `wrap` function. This data can be accessed during route processing.
```javascript
wrap({userData: {role: 'admin'}})
```
--------------------------------
### use:link Action with String Shorthand
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/README.md
A string can be used as a shorthand for the `use:link` action's options object, directly specifying the destination URL.
```svelte
The Biggest Princess
```
--------------------------------
### push(location: string)
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/REFERENCE.md
Navigates to a new page by adding an entry to the browser's history.
```APIDOC
## push(location: string)
### Description
Navigates to a new page by adding an entry to the browser's history.
### Parameters
#### Path Parameters
- **location** (string) - Required - The new location to navigate to.
```
--------------------------------
### onRouteLoading
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/configuration.md
Callback fired when a route is matched and begins loading, before the component renders. It receives a RouteDetail object containing information about the matched route, location, query string, and parameters.
```APIDOC
## onRouteLoading
### Description
Callback fired when a route is matched and begins loading, before the component renders.
### Parameters
- **detail** (RouteDetail) - The route detail object containing information about the matched route.
- **route** (string | RegExp) - The matched route definition.
- **location** (string) - Current path.
- **querystring** (string) - Query params from hash.
- **params** (Record | null) - Matched parameters.
- **userData**? (object) - Data from wrap().
### Example
```javascript
function handleLoading(detail) {
console.log('Navigating to:', detail.location)
console.log('Route:', detail.route)
// Show progress indicator
}
```
```
--------------------------------
### Implementing a Router Progress Indicator
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/patterns.md
Show a visual indicator, like a progress bar, while a new route is loading. This involves using the `onRouteLoading` and `onRouteLoaded` lifecycle callbacks to manage the loading state.
```svelte
{#if isLoading}
{/if}
```
--------------------------------
### wrap(options)
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/REFERENCE.md
A utility function to wrap routes, enabling features like asynchronous loading, guards, props, and data fetching.
```APIDOC
## wrap(options)
### Description
Wraps routes to enable async, guards, props, and data.
### Parameters
#### Path Parameters
- **options** (object) - Required - Configuration options for wrapping the route.
```
--------------------------------
### Route Matching with String Patterns
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/REFERENCE.md
Define routes using string patterns for exact matches, named parameters, optional parameters, and wildcards. The first matching route is used.
```javascript
const routes = {
'/': Home, // Exact match
'/books': Books, // Exact match
'/books/:id': BookDetail, // Named parameter
'/books/:id/:chapter?': Chapter, // Optional parameter
'/admin/*': Admin, // Wildcard
'*': NotFound // Catch-all (must be last)
}
```
--------------------------------
### Import wrap function from svelte-spa-router/wrap
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/Advanced Usage.md
Import the `wrap` function from the `svelte-spa-router/wrap` module to enable advanced route configurations.
```js
import { wrap } from 'svelte-spa-router/wrap'
```
--------------------------------
### AsyncSvelteComponent Usage with wrap()
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/types.md
Illustrates the correct way to define an async component for code-splitting using the wrap() function, ensuring it's a function returning a Promise.
```javascript
// Correct: function definition
const asyncRoute = () => import('./BookDetail.svelte')
// Incorrect: function invocation (don't do this)
const asyncRoute = import('./BookDetail.svelte')
// Usage with wrap()
import {wrap} from 'svelte-spa-router/wrap'
const routes = {
'/book/:id': wrap({
asyncComponent: () => import('./BookDetail.svelte')
})
}
```
--------------------------------
### Core Navigation and Action Functions
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/INDEX.md
Reference for core navigation functions like push, pop, and replace, as well as actions for linking and activating routes. These are essential for controlling application flow.
```typescript
// Navigation
push(location: string): Promise
pop(): Promise
replace(location: string): Promise
// Actions
link(node: HTMLElement, opts?: LinkActionOpts | string)
active(node: HTMLElement, opts?: ActiveOptions | string | RegExp)
// Utilities
wrap(args: WrapOptions): WrappedComponent
```
--------------------------------
### Update wrap method import and signature (v2.x to v3.x)
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/UPGRADING.md
The `wrap` method has been moved to a new import path and its signature changed to accept an options object. This facilitates new features like dynamically-imported routes.
```javascript
// Old import path
import {wrap} from 'svelte-spa-router'
const routes = {
// Method signature: wrap(component, userData, ...conditions)
'/foo': wrap(
// Component
Foo,
// Custom data
{foo: 'bar'},
// Pre-condition function
(detail) => {
// ...
},
// ...more pre-condition functions
)
}
```
```javascript
// New import path
import {wrap} from 'svelte-spa-router/wrap'
const routes = {
// Method signature: wrap(options)
'/foo': wrap({
// Component
component: Foo,
// Custom data
customData: {foo: 'bar'},
// Pre-condition function
conditions: [
(detail) => {
// ...
},
// ...more pre-condition functions
]
// See the documentation for the other possible properties for wrap
})
}
```
--------------------------------
### Wrap Entry Point Exports
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/REFERENCE.md
Exports available from the 'svelte-spa-router/wrap' entry point. Primarily used for wrapping components for routing purposes.
```typescript
export {wrap}
export {WrapOptions, WrappedComponent, AsyncSvelteComponent, RoutePrecondition}
```
--------------------------------
### Loading Placeholder Component
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/api-reference/wrap.md
Configures a loading component to be displayed while the async component for a route is being loaded. Specify the component and any parameters it needs.
```javascript
import Loading from './Loading.svelte'
import {wrap} from 'svelte-spa-router/wrap'
const routes = {
'/book/:id': wrap({
asyncComponent: () => import('./BookDetail.svelte'),
loadingComponent: Loading,
loadingParams: {message: 'Loading book...'}
})
}
```
```svelte
Loading: {params.message}
```
--------------------------------
### Import Main Router Components
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/README.md
Import the main Router component and essential routing functions like push, pop, replace, and link from the svelte-spa-router library.
```javascript
// Main entry
import Router from 'svelte-spa-router'
import {router, push, pop, replace, link} from 'svelte-spa-router'
```
--------------------------------
### wrap() Function
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/INDEX.md
Documentation for the wrap() function, used for advanced route features like dynamic imports, route guards, and loading placeholders.
```APIDOC
## wrap() Function
### Description
A utility function for enhancing route definitions with advanced features such as code-splitting, route guards, and custom props.
### Options
- **WrapOptions** (interface) - Configuration options for the wrap function.
### Features
- **Dynamic Imports**: Enables code-splitting by dynamically importing route components.
- **Route Pre-conditions (Guards)**: Allows defining functions that must pass before a route can be activated.
- **Loading Placeholders**: Specifies components to display while a route's content is loading.
- **Static Props and User Data**: Facilitates passing static props or user-defined data to routes.
```
--------------------------------
### Basic RegExp Routes
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/route-matching.md
Define routes using JavaScript regular expressions with a Map. The entire match result is passed as params. Use parentheses to capture groups.
```javascript
const routes = new Map()
// String routes can still be used with Map
routes.set('/', HomePage)
routes.set('/about', AboutPage)
// RegExp routes for custom matching
routes.set(/^\/user\/(\d+)$/, UserDetail)
routes.set(/^\/api\/v(\d+)\/$/, ApiHandler)
routes.set('*', NotFound)
```
--------------------------------
### Programmatic Navigation Triggered by Button Click
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/README.md
Demonstrates triggering programmatic navigation using the `push` function within an `onclick` event handler for a button.
```svelte
```
--------------------------------
### Exact String-Based Routes
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/route-matching.md
Define routes that must match the URL exactly. Trailing slashes are significant and must match.
```javascript
const routes = {
'/': HomePage,
'/about': AboutPage,
'/contact': ContactPage
}
```
--------------------------------
### Define Routes with Regular Expressions using Map
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/README.md
Use a JavaScript Map to define routes with string and regular expression patterns. Regular expression keys allow for flexible URL matching. The '*' key acts as a catch-all for undefined routes.
```javascript
import Home from './routes/Home.svelte'
import Name from './routes/Name.svelte'
import NotFound from './routes/NotFound.svelte'
const routes = new Map()
// You can still use strings to define routes
routes.set('/', Home)
routes.set('/hello/:first/:last?', Name)
// The keys for the next routes are regular expressions
// You will very likely always want to start the regular expression with ^
routes.set(/^\/hola\/(.*)/i, Name)
routes.set(/^\/buongiorno(\/([a-z]+))/i, Name)
// Catch-all, must be last
routes.set('*', NotFound)
```
--------------------------------
### Optional Parameters in Routes
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/route-matching.md
Mark parameters with '?' to make them optional. If not provided, they are set to null. The parameter position must still exist.
```javascript
const routes = {
'/page/:slug?': Page,
'/settings/:tab?/:subtab?': Settings
}
```
--------------------------------
### Push to New Page
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/REFERENCE.md
Navigates to a new page and adds an entry to the browser history.
```javascript
push(location: string)
```
--------------------------------
### Version 1.x Route Pre-conditions and Events
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/UPGRADING.md
Illustrates the older method of defining route pre-conditions and handling 'conditionsFailed' and 'routeLoaded' events in version 1.x. Note the separate location and querystring arguments for pre-conditions and the component directly in event.detail.
```javascript
// Route pre-conditions
const routes = {
'/hello': wrap(
Hello,
(location, querystring) => {
console.log(location, querystring)
return true
}
)
}
// Handles the "conditionsFailed" event
function conditionsFailed(event) {
console.error(event.detail.component)
}
// Handles the "routeLoaded" event
function routeLoaded(event) {
console.error(event.detail.component)
}
```
--------------------------------
### Handling Route Loading with onRouteLoading
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/api-reference/Router.md
Fires when a route is matched and begins loading, before the component renders. Pass a handler function to the onRouteLoading prop.
```svelte
```
--------------------------------
### Navigate Back in History with pop()
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/api-reference/navigation.md
Use the pop() function to navigate back in the browser's history, similar to clicking the back button. This function does not take any parameters.
```svelte
```
--------------------------------
### Handle Route Loading Callback
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/configuration.md
Use the onRouteLoading callback to execute logic before a route component begins loading. This is useful for showing progress indicators or logging navigation details.
```javascript
function handleLoading(detail) {
console.log('Navigating to:', detail.location)
console.log('Route:', detail.route)
// Show progress indicator
}
```
```javascript
```
--------------------------------
### String Shorthand for Path Matching
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/api-reference/active.md
A concise way to specify the path for active matching by passing the path string directly to the `use:active` directive, instead of using an options object.
```svelte
Books
```
--------------------------------
### Basic Routing Component
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/REFERENCE.md
Render the Router component in your main Svelte file, passing the defined routes as a prop.
```svelte
```
--------------------------------
### Accessing Router State
Source: https://github.com/italypaleale/svelte-spa-router/blob/main/_autodocs/types.md
Illustrates how to import and access the reactive properties of the `router` object to retrieve current routing information.
```javascript
import {router} from 'svelte-spa-router'
router.loc // { location: '/book/42', querystring: 'ch=3' }
router.location // '/book/42'
router.querystring // 'ch=3'
router.params // { id: '42' }
```