[](https://app.netlify.com/sites/elegua/deploys) # What is Elegua? Elegua: the best Svelte micro client router you'll ever see. ## Small example It's hopefully very straighforward: there are no components, just some stores reflecting current path/parts of url, and a [`resolve()`](#resolve) function for more complex (regexp/named routes) routings. The rest is just your plain Svelte logical blocks. ```svelte {#if $path === '/'}
Not found: {$path}
{/if} ``` ## Demo Online: [https://elegua.netlify.app/](https://elegua.netlify.app/) ... or run yourself: ```sh git clone http://github.com/howesteve/elegua cd elegua pnpm install pnpm run dev ``` ## Features - Dependency free (except for Svelte, of course) - Easy api, feels very natural and intuitive. - Minimalist: it's all in a single file (**2.2KB** gzipped/**6.7KB** unpacked) - It's tree-shakable, could end up smaller than that depending on what you use. - Fully reactive: changes to api reflect the browser's url, and vice versa. - No `This is the page for user {$match[1]} {:else}
Page {$path} not found
{/if} ``` > **Note** > > Implementation detail. One might wonder why I left a [`$path`](#path) param in the [`resolve(path, route)`](#resolve) api - it might seem cumbersome, why not using just `resolve('/')`? It's because otherwise Svelte wouldn't know it has to re-render the template containing the resolve block. With [`$path`](#path) explicitly appearing in template block, Svelte will re-render it every time [`$path`](#path) changes, and [`resolve()`](#resolve) gets called. Otherwise, path changes would not be perceived. ## goto() `goto(href: string|URL)` The [`goto(href)`](#goto) method navigates to some url/path programmatically. Internally, it uses [`history.pushState()`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState). Calls to [`goto(href)`](#goto) will trigger updates in all the expected reactive stores: [$path](#path), [$url](#url), [$hash](#hash), [$oldUrl](#oldurl), etc. - and also will update the current browser's url. ## preventChange() `preventChange : (()=> boolean|undefined) | undefined` This function allows setting a callback for preventing exiting a route/page from either clicking `` links or using [`goto()`](goto). If the callback function returns `true`, the link change will be blocked. If it returns anything else, it will be allowed. For instance, for preventing going away from a form has been changed: ```ts preventChange(() => { if (formIsDirty) { alert('Please save or cancel changes before navigating away.'); return true; } }); ``` To unset the callback, just call [`preventChange()`](preventchange) without arguments: ```ts preventChange() ``` For a more useful example of calling [`preventChange()`](preventchange) inside the `onMount()`/`onDestroy()` handlers, check [our demo app](https://elegua.netlify.app/preventchange) and [it's source](https://github.com/howesteve/elegua/blob/master/src/PreventChange.svelte). > **Note** > > This method will not prevent the user from closing the window/reloading the page. That is accomplished by handiling the [beforeload event](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event). But check the [`preventUnload` action](#preventunload) for a nice wrapper. I don't know of any other routers that have this feature. ## preventUnload() `preventUnload(callback: () => boolean | string| undefined)` This is a svelte action that will prevent the user from closing the current window if a condition is met. It can be used in set with [`preventChange`](#preventchange) to prevent the user from closing or navigating away from the changed forms. ```svelteThis is post id {$params["post"]}
``` or: ```svelte ``` - See it working [in our demo](https://elegua.netlify.app/dynamic) - See the demo's [source code](https://github.com/howesteve/elegua/tree/master/src/Dynamic) ## Stores ### $path A writable store that reflects the current url's path. If you load `http://localhost/blog`, `$path` will be set as `"/blog"`. If you set [`$path`](#path) using `path.set("/")` or `$path = "/"`, it will update the value store and the browser will load home route (similar to using [`goto("/")`](#goto)). This is used very often for simple, fixed routings. ```svelteSet path:
``` Use Svelte's `{#if}` blocks for routing using [`$path`](#path): ```svelte {#if $path === '/'}x is {$searchParams.get('x')}.
x is 1.
{:else if x === 2}
Param x is 2.
{:else}
Param x is {x}.
{/if}
Not found
{/if}No such path: {$path}
{/if} ``` ### Named routes Named routes are routes that can have named variables, prefixed with `":"`, such as `/blog/:slug`: ```svelte {#if resolve('/blog/:slug')}Rendering user {$match[1]} page
{/if} ``` - `\/users` will *not* match this route. - `\/users\/howe` will *not* match this route. - `\/users\/123` *will* match this route, and `$match[1]` will be `123` You could use other patterns in the same way. Ex: - `resolve($path, '\/users\/(howe|steve)')` => $match[1] will match `"/users/howe"` or `"/users/steve"` - `resolve($path, '\/users\/([a-zA-Z\_\\])*')` => inspect $match[1], $match[2] Named groups work as expected, and captured groups will be reflected in [`$params`](#params). After (and *only* after ) [`resolve()`](#resolve) is called, [`$match`](#match) and [`$params`](#params) will be redefined. ```svelte {#if resolve($path, /users\/(?User by $match: {$match && $match[1]}
User by $param: {$param['user_id']}
{/if} ``` ### Nav menu highlighting Often you want to highlight a nav menu item when user is on that page, so that he can see at a glance where they are. For instance, if you are in `"/about"` and your nav menu has the following links: `BLOG | ORDERS | ABOUT` ... and you want `ABOUT` highlighted when user is on that page (`/about`). In this case, just set a dynamic class inspecting [`$path`](#path): ```svelte ``` Now when you are on `/about`, nav menu will show something as:BLOG | ORDERS | ABOUT
### How do I handle any other kind of url changes?
Subscribe to [$url](#url). It's the DOM [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) object for the current browser's url. Then you can do anything you want with it.
### Redirects
No need to bloat [Elegua](https://github.com/howesteve/elegua) with that. Just use ``:
```svelte
{#if $path ==="/old_blog"}
Loading post {$hash}...
{:then post}