Skip to content

Instantly share code, notes, and snippets.

@tomatrow
Forked from RedHatter/Route.svelte
Last active December 4, 2020 08:47
Show Gist options
  • Select an option

  • Save tomatrow/46c5d5360e5ebf11c49124b3f147ac24 to your computer and use it in GitHub Desktop.

Select an option

Save tomatrow/46c5d5360e5ebf11c49124b3f147ac24 to your computer and use it in GitHub Desktop.

Revisions

  1. tomatrow revised this gist Dec 4, 2020. 1 changed file with 4 additions and 1 deletion.
    5 changes: 4 additions & 1 deletion package.json
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,6 @@
    {
    "name": "singularity-router"
    "name": "singularity-router",
    "dependencies": {
    "url-pattern": "^1.0.3"
    }
    }
  2. tomatrow revised this gist Dec 4, 2020. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions package.json
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,3 @@
    {
    "name": "singularity-router"
    }
  3. @RedHatter RedHatter created this gist Dec 4, 2020.
    28 changes: 28 additions & 0 deletions Route.svelte
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    <script>
    import UrlPattern from 'url-pattern'
    import location, { navigate, noMatch } from './location.js'
    export let path
    export let component = undefined
    export let redirect = undefined
    $: pattern = new UrlPattern(path)
    $: router = {
    params: pattern.match($location),
    path: $location,
    }
    $: {
    if (router.params !== null) {
    $noMatch = false
    if (redirect) navigate(redirect, true)
    }
    }
    </script>

    {#if router.params !== null}
    {#if component}
    <svelte:component this={component} {router} {...$$restProps} />
    {:else}
    <slot {router} />
    {/if}
    {/if}
    23 changes: 23 additions & 0 deletions location.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    import { writable } from 'svelte/store'

    const location = writable(window.location.pathname)
    export default location

    export let noMatch = writable(true)
    location.subscribe(_ => noMatch.set(true))

    window.addEventListener('popstate', e => location.set(window.location.pathname))

    let hasPrevious = false

    export function navigate(_path, replace = false) {
    hasPrevious = true
    const fn = replace ? 'replaceState' : 'pushState'
    history[fn](null, '', _path)
    location.set(window.location.pathname)
    }

    export function back() {
    if (hasPrevious) history.back()
    else navigate(window.location.pathname.replace(/[^/]+\/?$/, ''))
    }