# Svelte Client Router (SCR) ## Svelte Client Router makes SPA routes easy! Svelte Client Router is everything you need and think when routing SPA's. This is THE SVELTE ROUTER for SPA! Designed to help make you in control of the routing of your Single Page Applications (SPA)! ## Index - [Svelte Client Router (SCR)](#svelte-client-router-scr) - [Svelte Client Router makes SPA routes easy!](#svelte-client-router-makes-spa-routes-easy) - [Index](#index) - [Features](#features) - [Install](#install) - [Usage](#usage) - [SCR - Documentation and Test It!](#scr---documentation-and-test-it) - [SCR - Example](#scr---example) - [SCR - Configuration Store](#scr---configuration-store) - [SCR - Route Object Definition](#scr---route-object-definition) - [SCR - Router Svelte Component](#scr---router-svelte-component) - [SCR - Navigation](#scr---navigation) - [SCR - Router Link Component](#scr---router-link-component) - [SCR - Router Store](#scr---router-store) ## Features - Lazy Load Components - Lazy Load Loading Components - Routes Based in Svelte Stores - Before Enter Global Functions - Ignore Global Before Enter Function Per Route - Before Enter Per Route Functions - Execute Before Enter Router Functions before Global Before Enter Functions - After Function (Before Enter Function Sequence Array) - Route Title - Global Route Error Function - Route Error Functions - Loading Component on Route Changing ## Install To install Svelte Router on your svelte app: with npm ```bash npm i svelte-client-router ``` ## Usage Ensure your local server is configured in SPA mode. In a default Svelte installation you need to edit your package.json and add _-s_ to `sirv public`. ```javascript "start": "sirv public -s" ``` ### SCR - Documentation and Test It! Click here to see Svelte Client Router - In Action! ### SCR - Example Configuration Options
Global On Error
Route Object Options
SCR Component Properties
SCR Component Components
```javascript ``` ### SCR - Configuration Store Configuration Store manages the behavior of the SCR. Let's see the options we have here:
Configuration Options
Global Before Enter Functions
Global On Error
```javascript { // ## Hash Mode checks route using #/ before the location path // ## for example http://localhost:5000/pathAAA#/pathBBB // ## it will consider only pathBBB and ignore pathAAA as path! // ## Boolean hashMode: false, // ## Default is false // ## Navigation History Limit is the amount of route history is added // ## in the route navigation history list // ## 0 or -1 equals to "no limit" // ## Integer navigationHistoryLimit: 200, // ## Default is 200 // ## Not Found Route Path // ## is the path that should redirect when not found a path in the application // ## String - must include "/" notFoundRoute: "/notFound", // ## Default is "/notFound" // ## Console Log Error Messages logs in the console // ## any error messages of the SCR for debugging purposes // ## Boolean consoleLogErrorMessages: true, // ## Default is true // ## Console Log Stores logs in the console // ## any changes in the Router Store for debugging purposes // ## Boolean consoleLogStores: true, // ## Default is true // ## Consider Trailing Slash On Matching Route // ## add an slash in the end of the route path to search in the route definitions // ## Boolean considerTrailingSlashOnMatchingRoute: true // ## Default is true // ## Max Redirect Before Enter // ## the maximum value to before enter execute when redirecting // ## Integer maxRedirectBeforeEnter: 30, // ## Default is 30 // ## Use Scroll - enable or disables scrolling on entering the route // ## Boolean useScroll: true // ## Default is true // ## Scroll Props // ## The scrolling props on entering the route if enabled // ## Default Values: // ## scrollProps: { // ## target: false, // ## top: 0, // ## left: 0, // ## behavior: "smooth", // ## timeout: 10, // timeout must be greater than 10 milliseconds // ## }, // ## Object scrollProps: { target: false, top: 100, left: 100, behavior: "smooth", timeout: 1000, }, // ## Before Enter defines a function or array of Functions // ## that must execute before each route // ## Function or Array - of Functions beforeEnter: [], // ## On Error defines a function when an error occurs // ## when routing // ## Function onError: (error) => console.log(error), } // ## EXAMPLE import { configStore } from "svelte-client-router"; configStore.setHashMode(false); configStore.setNavigationHistoryLimit(100); configStore.setNotFoundRoute("/myCustomNotFoundRoute"); configStore.setConsoleLogErrorMessages(true); configStore.setConsoleLogStores(true); configStore.setMaxRedirectBeforeEnter(30); configStore.setUsesRouteLayout(true); configStore.setConsiderTrailingSlashOnMatchingRoute(true); // ## Callback receives 2 params // ## 1) Error // ## 2) Parameters defined for the route, current route, from route, etc.. configStore.setOnError((error) => { // ## Error Object console.log("GLOBAL ERROR CONFIG", error); }); // ## Receives a Function or an Array of Functions // ## Callback receives 2 params // ## 1) resolve function // ## Should resolve with: // ## - true - when everything went OK // ## - false - when just ignore routing and stop // ## - { redirect: "/some_route" } // ## - { path: "/some_route" } // ## - { name: "route_name" } // ## // ## Route coming from // ## Route going to // ## reject function - throws exception // ## 2) payload object - to pass info between before enter functions - do not override this variable! configStore.setBeforeEnter([ ({resolve, routeFrom, routeTo, reject}, payload) => { payload.test = "have some variable passing"; console.log("Global Before Enter Route - 1"); resolve(true); }, ({resolve, routeFrom, routeTo, reject}, payload) => { console.log("Global Before Enter Route - 2"); console.log(payload.test) // will print - have some variable passing resolve(true); }, ]); // ## You can set the entire object with the following configStore.setConfig({ hashMode: false, navigationHistoryLimit: 200, notFoundRoute: "/notFound", consoleLogErrorMessages: true, consoleLogStores: false, considerTrailingSlashOnMatchingRoute: true, maxRedirectBeforeEnter: 30, useScroll: false, scrollProps: { target: false, top: 0, left: 0, behavior: "smooth", timeout: 10, }, onError: (error) => { console.log("GLOBAL ERROR CONFIG", error); }, beforeEnter: [ (resolve, routeFrom, routeTo, routeObjParams, payload) => { payload.GBER1 = "My Custom Param to Pass"; console.log("Global Before Enter Route - 1"); resolve(true); }, (resolve, routeFrom, routeTo, routeObjParams, payload) => { if (payload.GBER1) { payload.GBER2 = "Yes, I will be set too!"; } console.log("Global Before Enter Route - 2"); resolve(true); } ] }) ``` ### SCR - Route Object Definition Route Object is the definition of every route we have in the SPA application and is below our SCR Route Component. Let's see the object format:
Route Object Options
Route Object Before Enter Functions
Route Object After Before Enter Function
Route Object On Error
```javascript import { SCR_Router } from "svelte-client-router"; import SCR_C1 from "./testComponents/SCR_C1.svelte"; import SCR_Loading from "./testComponents/SCR_Loading.svelte"; { // ## Route Name // ## The name identifying this route // ## String - Obrigatory name: "routeName1", // ## Route Path // ## The path identifying this route // ## String - Obrigatory // ## Can declare regex like /test1/:paramA/test2/:paramB // ## Can declare any route wildcard like /test1/:paramA/*/:paramB // ## This property value is Case Sensitive. // ## The regex must have the format ":string" path: "/test1", // ## Component - the component that is going to be used // ## for this route // ## Function - Imported component for this route component: SCR_C1, // ## Lazy Load Component - the component that must be loaded to be used // ## for this route // ## Function - Function to load the component for this route lazyLoadComponent: () => import("./testComponents/SCR_C1.svelte"), // ## Lazy Load Loading Component - the loading component that must be loaded to be used // ## for this route // ## Function - Function to load the loading component for this route lazyLoadLoadingComponent: () => import("./testComponents/SCR_Loading.svelte"), // ## Loading Component - the loading component that is going to be used // ## for this route // ## Function - Imported loading component for this route loadingComponent: SRC_Loading, // ## Ignore Layout - if should ignore layout component // ## when you do not want to use global or local layout component // ## Boolean ignoreLayout: false, // ## Ignore Scroll - if this route should ignore scrolling // ## Boolean ignoreScroll: true, // ## Scroll Props // ## The scrolling props on entering the specific route if enabled // ## Default Values: configuration store // ## Object scrollProps: { target: false, top: 0, left: 0, behavior: "smooth", timeout: 10, // timeout must be greater than 10 milliseconds }, // ## Title - it defines the route title // ## String title: "First Route Title", // ## Params - all the params the should be available // for this route on any Before Enter Execution or // After Before Enter Execution // ## Object params: { myCustomParam: "OK THEN SHALL WE!", }, // ## Force Reload - when in opened route try to push the same route // by using pushRoute function // When enabled it will reload the current route as if it was not opened // ## Boolean forceReload: false, // ## Ignore Global Before Function - // ## if should ignore defined global before function // ## Boolean ignoreGlobalBeforeFunction: false, // ## Execute Route Before Enter Function Before Global Before Function // ## if should execute route before function sequence before // ## global before enter execution // ## Boolean executeRouteBEFBeforeGlobalBEF: false, // ## Loading Props - all props that must be available to // loading component when it is triggered loadingParams: { loadingText: "Carregando..." }, afterBeforeEnter: ( { toRoute, fromRoute, payload } ) => { console.log("AFTER ENTER", toRoute, fromRoute, payload); }, // ## Before Enter - a function or array of Functions // ## defining all functions that must be executed for this specific route // ## Function or Array (Functions) beforeEnter: [ ({resolve, routeFrom, routeTo, reject}, payload) => { payload.passingToNextBeforeEnter: "yes, I will be there!", payload.passingToComponents: "yes, I will be there either!", setTimeout(() => resolve(true), 2000); console.log("beforeEnter Executed"); resolve(true); }, ({resolve, routeFrom, routeTo, reject}, payload) => { console.log(payload); setTimeout(() => resolve(true), 1000); console.log("beforeEnter Executed2"); resolve({ redirect: "/test2" }); }, ], // ## On Error - a function to execute when somenthing goes wrong on loading // ## this specific route // ## Error Object // ## Function onError: (error) => { console.log("ERROR DEFINED ROUTER C1", error); }, }, ``` ### SCR - Router Svelte Component Route Svelte Component will control the selection of the route, execute all the logic and return accordingly you specified in the router object. Let's see this component properties and possibilities:
Route Component Properties
Route Component Components
```javascript import { SCR_Router } from "svelte-client-router"; // ## Your route definitions as exampled above const routes = [ ... ] // ## THE SVELTE CLIENT ROUTER COMPONENT! // ## Properties // ## the route object definition // ## Array of routes export let routes; // ## The Default Loading Component - SCR has a Loading Component by Default - // ## If you not specify nothing will appear between routes - unless defined per route // ## It is used when it is executing Before Enter Route or Global Before Enter // ## Function export let defaultLoadingComponent = SCR_Loading; // ## defaultLoadingParams - loading params to be available on loading component // ## Object - default is an empty object export let defaultLoadingParams = {}; ``` ### SCR - Navigation SCR navigation can be very simple. You can import the navigation store or just the methods to navigate. Let's see them:
Navigate Routing
```javascript // < -- You Svelte Component Definition-- >
My Svelte Component


``` The assinature of the methods ```javascript // ## Push Route Function // ## ----------------------------------------------------------------------------------- // ## -- First Property of Param is where to send accepts the following: // ## String /pathToRoute // ## Object { path: "/pathToRoute" } // ## Object { name: "myRouteName" } // ## ----------------------------------------------------------------------------------- // ## -- Second Property of Param custom params to pass to route they will be considered // ## and made available on before functions after enter route function and component // ## Object { someCustomParams: { isAvailable: "Hell ya" }} // ## ----------------------------------------------------------------------------------- // ## -- Third Property of Param a custom onError to execute if something goes wrong. // ## it will override, ONLY WHEN SET, the route on error defined in the routes object // ## ----------------------------------------------------------------------------------- // ## Function pushRoute({ name: "someRouteName", params: { myParam: "OK" }, onError: (error) => console.log("Some customization of an error function") }); // ## Back Route Function - returns last route definition // ## Function backRoute() ``` ### SCR - Router Link Component SCR RouterLink Component is a component to make easy clickable go to route. Let's see it:
Router Link Properties
```javascript // < -- You Svelte Component Definition-- >
console.log("Execute this instead error defined on router object! - Only if something goes wrong") }} elementProps={{ style:"background-color: green" }} >
``` ### SCR - Router Store SCR Router Store is the store where all the route definitions are updated and controlled. You can check real time what is happening. Let's see it:
Router Store Properties
```javascript // < -- You Svelte Component Definition-- > { // ## Routes // ## The Array object defined on initialization of the application // ## Array routes: [], // ## Current Route // ## The object with current route information // ## Updated before "after before enter function" execution // ## Object currentRoute: { routeId: undefined, name: undefined, path: undefined, pathname: undefined, fullPath: undefined, queryParams: {}, pathParams: {}, params: {}, host: undefined, protocol: undefined, port: undefined, origin: undefined, hash: undefined, routeObj: {}, redirected: undefined, }, // ## From Route // ## The object with from route information // ## Updated before "after before enter function" execution // ## Object fromRoute: { routeId: undefined, name: undefined, path: undefined, pathname: undefined, fullPath: undefined, queryParams: {}, pathParams: {}, params: {}, host: undefined, protocol: undefined, port: undefined, origin: undefined, hash: undefined, routeObj: {}, redirected: undefined, }, // ## Navigation History // ## An array with all the route history objects - the limit is // ## defined in the configuration store // ## Updated before "after before enter function" execution // ## Array navigationHistory: [], } // ## Methods available on the STORE OBJECTS // ## ----------------------------------------------------------------------------------- // ## setRoutes, // ## getRoutes, // ## setCurrentRoute, // ## getCurrentRoute, // ## setFromRoute, // ## getFromRoute, // ## setNavigationHistory, // ## getNavigationHistory, // ## pushNavigationHistory, // ## getNotFoundRoute, ```