((res) => setTimeout(() => res(), ms));
9 | }
10 |
11 | export function dispatchCustomEvent(element: HTMLElement, eventName: string) {
12 | element.dispatchEvent(new CustomEvent(eventName, {
13 | bubbles: true,
14 | cancelable: true,
15 | }));
16 | }
17 |
--------------------------------------------------------------------------------
/src/App.svelte:
--------------------------------------------------------------------------------
1 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/src/StackRouter.svelte:
--------------------------------------------------------------------------------
1 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/src/_routes.js:
--------------------------------------------------------------------------------
1 | import { get } from 'svelte/store';
2 | import Home from './pages/Home.svelte';
3 | import Resumable from './pages/Resumable.svelte';
4 | import Throwaway from './pages/Throwaway.svelte';
5 | import Redirect from './pages/Redirect.svelte';
6 | import NotFound from './pages/NotFound.svelte';
7 | import Guarded from './pages/Guarded.svelte';
8 | import AsyncComponent from './pages/AsyncComponent.svelte';
9 | import youShallPass from './stores/you-shall-pass';
10 |
11 | export default {
12 | '/': Home,
13 | '/resumable/:aVariable?': Resumable,
14 | '/throwaway': Throwaway,
15 | '/guarded': {
16 | component: Guarded,
17 | guard: () => get(youShallPass),
18 | },
19 | '/async': {
20 | componentProvider: () => new Promise(
21 | (resolve, reject) => setTimeout(
22 | // Simulate lazy loading
23 | () => resolve(AsyncComponent),
24 |
25 | // Simulate a network error
26 | // The promise can fail. In that case the router will emit an appropriate "error" event
27 | // with the details and the original error returned by the failed promise
28 | // () => reject(new Error('oh no!')),
29 | 1000,
30 | ),
31 | ),
32 | },
33 | '/redirect': Redirect,
34 | '*': NotFound,
35 | };
36 |
--------------------------------------------------------------------------------
/src/components/Links.svelte:
--------------------------------------------------------------------------------
1 |
8 |
9 |
28 |
--------------------------------------------------------------------------------
/src/index.d.ts:
--------------------------------------------------------------------------------
1 | /* eslint-disable import/named */
2 | import type {
3 | NavigationType, TransitionFunction, CacheEntry, PageToUnloadAction, PageToLoadAction, Routes, Params
4 | } from './types';
5 |
6 | export * from './stack-router';
7 | export * from './transition-functions';
8 | export * from './types';
9 | export * from './utils';
10 | export class SvelteComponent {
11 | $$prop_def: {};
12 |
13 | $$slot_def: {};
14 |
15 | $on(event: string, handler: (e: CustomEvent) => any): () => void;
16 | }
17 | export class StackRouter extends SvelteComponent {
18 | $$prop_def: {
19 | /** Whether or not the default behavior should be to resume or recreate the components */
20 | defaultResumable?: boolean,
21 | /** Whether or not to prefix routes with '#' to implement a server-agnostic client side routing (e.g. no need to redirect 404 to index) */
22 | useHash?: boolean,
23 | /** Whether or not to restore the scroll position when navigating backwards */
24 | restoreScroll?: boolean,
25 | /** A key-value object associating a route path (e.g. '/a/route/path/:variable1?) to a SvelteComponent constructor */
26 | routes: Routes,
27 | /** A function that handles the transition between two pages */
28 | transitionFn?: TransitionFunction,
29 | }
30 |
31 | /** Triggered on errors such as "no route found" */
32 | $on(event: 'error', handler: (e: CustomEvent<{
33 | message: string,
34 | location: string,
35 | }>) => any): () => void;
36 |
37 | /** Triggered before unloading the old page and before loading the new page */
38 | $on(event: 'navigation-start', handler: (e: CustomEvent<{
39 | location: string,
40 | navigationType: NavigationType,
41 | pageToLoad: CacheEntry,
42 | pageToUnload: CacheEntry | null,
43 | pageToLoadAction: PageToLoadAction,
44 | pageToUnloadAction: PageToUnloadAction,
45 | }>) => any): () => void;
46 |
47 | /** Triggered after unloading the old page and after loading the new page */
48 | $on(event: 'navigation-end', handler: (e: CustomEvent<{
49 | location: string,
50 | navigationType: NavigationType,
51 | pageToLoad: CacheEntry,
52 | pageToUnload: CacheEntry | null,
53 | pageToLoadAction: PageToLoadAction,
54 | pageToUnloadAction: PageToUnloadAction,
55 | }>) => any): () => void;
56 |
57 | /** Triggered when a route couldn't be reached because a guard returned a falsy value */
58 | $on(event: 'forbidden', handler: (e: CustomEvent<{
59 | message: string,
60 | params?: Params,
61 | location: string
62 | }>) => any): () => void;
63 | }
64 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | export * from './stack-router';
2 | export * from './transition-functions';
3 | export * from './types';
4 | export * from './utils';
5 | export { default as StackRouter } from './StackRouter.svelte';
6 |
--------------------------------------------------------------------------------
/src/pages/AsyncComponent.svelte:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 |
I'm an asynchronously loaded component
12 |
13 |
14 | I'll take some time to get loaded the first time, but if you come back I'll be
15 | ready, even if I'm not resumable!
16 |
17 |
--------------------------------------------------------------------------------
/src/pages/Guarded.svelte:
--------------------------------------------------------------------------------
1 |
2 |
I'm a guarded component
3 |
4 |
5 | You shall be able to reach me only if you checked "Enable guarded route" first
6 |
7 |
--------------------------------------------------------------------------------
/src/pages/Home.svelte:
--------------------------------------------------------------------------------
1 |
2 |
Welcome to svelte-stack-router
3 |
4 |
5 |
A fast, app-like router that caches components
6 |
7 |
8 |
9 | Less re-renders, full state preservation and cool animations!
10 |
11 |
12 |
20 |
--------------------------------------------------------------------------------
/src/pages/NotFound.svelte:
--------------------------------------------------------------------------------
1 |
5 |
6 |
7 |
Not found
8 |
9 | Redirect
10 |
--------------------------------------------------------------------------------
/src/pages/Redirect.svelte:
--------------------------------------------------------------------------------
1 |
8 |
9 | I'm temporary... just wait a sec...
10 |
--------------------------------------------------------------------------------
/src/pages/Resumable.svelte:
--------------------------------------------------------------------------------
1 |
90 |
91 |
92 |
I'm a resumable component
93 |
94 |
95 |
101 |
102 |
107 | {#if params.aVariable}
108 |
113 | I have a param! "{params.aVariable}"
114 |
115 | {/if}
116 |
117 |
118 |
119 | This component will get cached. As a result the following video
120 | will be paused and resumed every time you visit this page
121 |
122 |
123 |
124 | Events so far:
125 |
126 |
127 | {#each events as event}
128 | -
129 | {event}
130 |
131 | {/each}
132 |
133 |
134 |
--------------------------------------------------------------------------------
/src/pages/Throwaway.svelte:
--------------------------------------------------------------------------------
1 |
48 |
49 |
50 |
I'm a non-resumable component
51 |
52 |
53 |
54 | This component won't get cached. As a result the following video
55 | will restart every time you visit this page
56 |
57 |
58 |
59 | Events so far:
60 |
61 |
62 | {#each events as event}
63 | -
64 | {event}
65 |
66 | {/each}
67 |
68 |
69 |
--------------------------------------------------------------------------------
/src/pages/_Layout.svelte:
--------------------------------------------------------------------------------
1 |
25 |
26 |
27 |
28 |
Location pathname: {$pathname}
29 |
30 |
31 |
39 |
40 |
41 |
45 |
46 |
47 |
51 |
52 |
53 | {#if !unmount}
54 |
62 | {:else}
63 |
64 | StackRouter unmounted, all cached components have been destroyed
65 |
66 | {/if}
67 |
68 |
--------------------------------------------------------------------------------
/src/preview.js:
--------------------------------------------------------------------------------
1 | import App from './App.svelte';
2 |
3 | const app = new App({
4 | target: document.body,
5 | props: {},
6 | });
7 |
8 | export default app;
9 |
--------------------------------------------------------------------------------
/src/stores/async-component-loaded.js:
--------------------------------------------------------------------------------
1 | import { writable } from 'svelte/store';
2 |
3 | export default writable(false);
4 |
--------------------------------------------------------------------------------
/src/stores/you-shall-pass.js:
--------------------------------------------------------------------------------
1 | import { writable } from 'svelte/store';
2 |
3 | export default writable(false);
4 |
--------------------------------------------------------------------------------
/src/style/main.css:
--------------------------------------------------------------------------------
1 | html, body {
2 | margin: 0;
3 | padding: 0;
4 | font-family: sans-serif;
5 | text-align: center;
6 | }
7 |
8 | body {
9 | color: white;
10 | background-color: #1c1c1c;
11 | }
12 |
13 | a {
14 | text-decoration: none;
15 | padding: 0.5em 1em;
16 | margin: 0.5em 1em;
17 | color: gray;
18 | background-color: lavender;
19 | display: inline-block;
20 | font-size: 1em;
21 | }
22 |
23 | button {
24 | border: none;
25 | background-color: antiquewhite;
26 | color: gray;
27 | font-size: 1em;
28 | padding: 0.5em 1em;
29 | margin: 0.5em 1em;
30 | }
31 |
32 | h1, h2 {
33 | display: inline-block;
34 | margin: 0;
35 | text-align: center;
36 | position: relative;
37 | padding-bottom: 20px;
38 | }
39 |
40 | h1::after {
41 | content: ' ';
42 | display: block;
43 | position: absolute;
44 | left: 5%;
45 | right: 5%;
46 | margin-top: 10px;
47 | height: 1px;
48 | background-color: gray;
49 | }
50 |
51 | select {
52 | background-color: #4c4c4c;
53 | border: none;
54 | padding: 0.5em 1em;
55 | margin: 0.5em 1em;
56 | color: white;
57 | font-size: 1em;
58 | }
59 |
60 | img.text {
61 | height: 1em;
62 | width: auto;
63 | vertical-align: middle;
64 | }
65 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | /* Basic Options */
4 | // "incremental": true, /* Enable incremental compilation */
5 | "target": "es2019", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
6 | "module": "es2020", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
7 | // "lib": [], /* Specify library files to be included in the compilation. */
8 | // "allowJs": true, /* Allow javascript files to be compiled. */
9 | // "checkJs": true, /* Report errors in .js files. */
10 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
11 | "declaration": false, /* Generates corresponding '.d.ts' file. */
12 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
13 | // "sourceMap": true, /* Generates corresponding '.map' file. */
14 | // "outFile": "./", /* Concatenate and emit output to single file. */
15 | "outDir": "./src", /* Redirect output structure to the directory. */
16 | "rootDir": "./src-ts", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
17 | // "composite": true, /* Enable project compilation */
18 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
19 | // "removeComments": true, /* Do not emit comments to output. */
20 | // "noEmit": true, /* Do not emit outputs. */
21 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */
22 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
23 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
24 |
25 | /* Strict Type-Checking Options */
26 | "strict": true, /* Enable all strict type-checking options. */
27 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
28 | // "strictNullChecks": true, /* Enable strict null checks. */
29 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */
30 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
31 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
32 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
33 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
34 |
35 | /* Additional Checks */
36 | // "noUnusedLocals": true, /* Report errors on unused locals. */
37 | // "noUnusedParameters": true, /* Report errors on unused parameters. */
38 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
39 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
40 |
41 | /* Module Resolution Options */
42 | "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
43 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
44 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
45 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
46 | // "typeRoots": [], /* List of folders to include type definitions from. */
47 | // "types": [], /* Type declaration files to be included in compilation. */
48 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
49 | "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
50 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
51 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
52 |
53 | /* Source Map Options */
54 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
55 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
56 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
57 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
58 |
59 | /* Experimental Options */
60 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
61 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
62 |
63 | /* Advanced Options */
64 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
65 | },
66 | "include": [
67 | "src-ts"
68 | ],
69 | "exclude": [
70 | "src"
71 | ]
72 | }
73 |
--------------------------------------------------------------------------------