forked from ItalyPaleAle/svelte-spa-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRouter.svelte
386 lines (340 loc) · 11.9 KB
/
Router.svelte
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
<script context="module">
// Something's wrong with eslint on this file
/* eslint-disable no-multiple-empty-lines */
import {readable, derived} from 'svelte/store'
/**
* Wraps a route to add route pre-conditions.
*
* @param {SvelteComponent} route - Svelte component for the route
* @param {Object} [userData] - Optional object that will be passed to each `conditionsFailed` event
* @param {...Function} conditions - Route pre-conditions to add, which will be executed in order
* @returns {Object} Wrapped route
*/
export function wrap(route, userData, ...conditions) {
// Check if we don't have userData
if (userData && typeof userData == 'function') {
conditions = (conditions && conditions.length) ? conditions : []
conditions.unshift(userData)
userData = undefined
}
// Parameter route and each item of conditions must be functions
if (!route || typeof route != 'function') {
throw Error('Invalid parameter route')
}
if (conditions && conditions.length) {
for (let i = 0; i < conditions.length; i++) {
if (!conditions[i] || typeof conditions[i] != 'function') {
throw Error('Invalid parameter conditions[' + i + ']')
}
}
}
// Returns an object that contains all the functions to execute too
const obj = {route, userData}
if (conditions && conditions.length) {
obj.conditions = conditions
}
// The _sveltesparouter flag is to confirm the object was created by this router
Object.defineProperty(obj, '_sveltesparouter', {
value: true
})
return obj
}
/**
* @typedef {Object} Location
* @property {string} location - Location (page/view), for example `/book`
* @property {string} [querystring] - Querystring from the hash, as a string not parsed
*/
/**
* Returns the current location from the hash.
*
* @returns {Location} Location object
* @private
*/
function getLocation() {
const hashPosition = window.location.href.indexOf('#/')
let location = (hashPosition > -1) ? window.location.href.substr(hashPosition + 1) : '/'
// Check if there's a querystring
const qsPosition = location.indexOf('?')
let querystring = ''
if (qsPosition > -1) {
querystring = location.substr(qsPosition + 1)
location = location.substr(0, qsPosition)
}
return {location, querystring}
}
/**
* Readable store that returns the current full location (incl. querystring)
*/
export const loc = readable(
getLocation(),
// eslint-disable-next-line prefer-arrow-callback
function start(set) {
const update = () => {
set(getLocation())
}
window.addEventListener('hashchange', update, false)
return function stop() {
window.removeEventListener('hashchange', update, false)
}
}
)
/**
* Readable store that returns the current location
*/
export const location = derived(
loc,
($loc) => $loc.location
)
/**
* Readable store that returns the current querystring
*/
export const querystring = derived(
loc,
($loc) => $loc.querystring
)
/**
* Navigates to a new page programmatically.
*
* @param {string} location - Path to navigate to (must start with `/` or '#/')
*/
export function push(location) {
if (!location || location.length < 1 || (location.charAt(0) != '/' && location.indexOf('#/') !== 0)) {
throw Error('Invalid parameter location')
}
// Execute this code when the current call stack is complete
setTimeout(() => {
window.location.hash = (location.charAt(0) == '#' ? '' : '#') + location
}, 0)
}
/**
* Navigates back in history (equivalent to pressing the browser's back button).
*/
export function pop() {
// Execute this code when the current call stack is complete
setTimeout(() => {
window.history.back()
}, 0)
}
/**
* Replaces the current page but without modifying the history stack.
*
* @param {string} location - Path to navigate to (must start with `/` or '#/')
*/
export function replace(location) {
if (!location || location.length < 1 || (location.charAt(0) != '/' && location.indexOf('#/') !== 0)) {
throw Error('Invalid parameter location')
}
// Execute this code when the current call stack is complete
setTimeout(() => {
const dest = (location.charAt(0) == '#' ? '' : '#') + location
history.replaceState(undefined, undefined, dest)
// The method above doesn't trigger the hashchange event, so let's do that manually
window.dispatchEvent(new Event('hashchange'))
}, 0)
}
/**
* Svelte Action that enables a link element (`<a>`) to use our history management.
*
* For example:
*
* ````html
* <a href="/books" use:link>View books</a>
* ````
*
* @param {HTMLElement} node - The target node (automatically set by Svelte). Must be an anchor tag (`<a>`) with a href attribute starting in `/`
*/
export function link(node) {
// Only apply to <a> tags
if (!node || !node.tagName || node.tagName.toLowerCase() != 'a') {
throw Error('Action "link" can only be used with <a> tags')
}
// Destination must start with '/'
const href = node.getAttribute('href')
if (!href || href.length < 1 || href.charAt(0) != '/') {
throw Error('Invalid value for "href" attribute')
}
// Add # to every href attribute
node.setAttribute('href', '#' + href)
}
</script>
{#if componentParams}
<svelte:component this="{component}" params="{componentParams}" />
{:else}
<svelte:component this="{component}" />
{/if}
<script>
import {createEventDispatcher} from 'svelte'
import regexparam from 'regexparam'
/**
* Dictionary of all routes, in the format `'/path': component`.
*
* For example:
* ````js
* import HomeRoute from './routes/HomeRoute.svelte'
* import BooksRoute from './routes/BooksRoute.svelte'
* import NotFoundRoute from './routes/NotFoundRoute.svelte'
* routes = {
* '/': HomeRoute,
* '/books': BooksRoute,
* '*': NotFoundRoute
* }
* ````
*/
export let routes = {}
/**
* Optional prefix for the routes in this router. This is useful for example in the case of nested routers.
*/
export let prefix = ''
/**
* Container for a route: path, component
*/
class RouteItem {
/**
* Initializes the object and creates a regular expression from the path, using regexparam.
*
* @param {string} path - Path to the route (must start with '/' or '*')
* @param {SvelteComponent} component - Svelte component for the route
*/
constructor(path, component) {
if (!component || (typeof component != 'function' && (typeof component != 'object' || component._sveltesparouter !== true))) {
throw Error('Invalid component object')
}
// Path must be a regular or expression, or a string starting with '/' or '*'
if (!path ||
(typeof path == 'string' && (path.length < 1 || (path.charAt(0) != '/' && path.charAt(0) != '*'))) ||
(typeof path == 'object' && !(path instanceof RegExp))
) {
throw Error('Invalid value for "path" argument')
}
const {pattern, keys} = regexparam(path)
this.path = path
// Check if the component is wrapped and we have conditions
if (typeof component == 'object' && component._sveltesparouter === true) {
this.component = component.route
this.conditions = component.conditions || []
this.userData = component.userData
}
else {
this.component = component
this.conditions = []
this.userData = undefined
}
this._pattern = pattern
this._keys = keys
}
/**
* Checks if `path` matches the current route.
* If there's a match, will return the list of parameters from the URL (if any).
* In case of no match, the method will return `null`.
*
* @param {string} path - Path to test
* @returns {null|Object.<string, string>} List of paramters from the URL if there's a match, or `null` otherwise.
*/
match(path) {
// If there's a prefix, remove it before we run the matching
if (prefix && path.startsWith(prefix)) {
path = path.substr(prefix.length) || '/'
}
// Check if the pattern matches
const matches = this._pattern.exec(path)
if (matches === null) {
return null
}
// If the input was a regular expression, this._keys would be false, so return matches as is
if (this._keys === false) {
return matches
}
const out = {}
let i = 0
while (i < this._keys.length) {
out[this._keys[i]] = matches[++i] || null
}
return out
}
/**
* Dictionary with route details passed to the pre-conditions functions, as well as the `routeLoaded` and `conditionsFailed` events
* @typedef {Object} RouteDetail
* @property {SvelteComponent} component - Svelte component
* @property {string} name - Name of the Svelte component
* @property {string} location - Location path
* @property {string} querystring - Querystring from the hash
* @property {Object} [userData] - Custom data passed by the user
*/
/**
* Executes all conditions (if any) to control whether the route can be shown. Conditions are executed in the order they are defined, and if a condition fails, the following ones aren't executed.
*
* @param {RouteDetail} detail - Route detail
* @returns {bool} Returns true if all the conditions succeeded
*/
checkConditions(detail) {
for (let i = 0; i < this.conditions.length; i++) {
if (!this.conditions[i](detail)) {
return false
}
}
return true
}
}
// Set up all routes
const routesList = []
if (routes instanceof Map) {
// If it's a map, iterate on it right away
routes.forEach((route, path) => {
routesList.push(new RouteItem(path, route))
})
}
else {
// We have an object, so iterate on its own properties
Object.keys(routes).forEach((path) => {
routesList.push(new RouteItem(path, routes[path]))
})
}
// Props for the component to render
let component = null
let componentParams = null
// Event dispatcher from Svelte
const dispatch = createEventDispatcher()
// Just like dispatch, but executes on the next iteration of the event loop
const dispatchNextTick = (name, detail) => {
// Execute this code when the current call stack is complete
setTimeout(() => {
dispatch(name, detail)
}, 0)
}
// Handle hash change events
// Listen to changes in the $loc store and update the page
$: {
// Find a route matching the location
component = null
let i = 0
while (!component && i < routesList.length) {
const match = routesList[i].match($loc.location)
if (match) {
const detail = {
component: routesList[i].component,
name: routesList[i].component.name,
location: $loc.location,
querystring: $loc.querystring,
userData: routesList[i].userData
}
// Check if the route can be loaded - if all conditions succeed
if (!routesList[i].checkConditions(detail)) {
// Trigger an event to notify the user
dispatchNextTick('conditionsFailed', detail)
break
}
component = routesList[i].component
// Set componentParams onloy if we have a match, to avoid a warning similar to `<Component> was created with unknown prop 'params'`
// Of course, this assumes that developers always add a "params" prop when they are expecting parameters
if (match && typeof match == 'object' && Object.keys(match).length) {
componentParams = match
}
else {
componentParams = null
}
dispatchNextTick('routeLoaded', detail)
}
i++
}
}
</script>