-
-
Notifications
You must be signed in to change notification settings - Fork 743
/
Copy pathindex.ts
421 lines (373 loc) · 11.1 KB
/
index.ts
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
// While the public API was clearly inspired by the "history" npm package,
// This implementation attempts to be more lightweight by
// making assumptions about the way TanStack Router works
export interface RouterHistory {
location: HistoryLocation
subscribe: (cb: () => void) => () => void
push: (path: string, state?: any) => void
replace: (path: string, state?: any) => void
go: (index: number) => void
back: () => void
forward: () => void
createHref: (href: string) => string
block: (blocker: BlockerFn) => () => void
flush: () => void
destroy: () => void
notify: () => void
}
export interface HistoryLocation extends ParsedPath {
state: HistoryState
}
export interface ParsedPath {
href: string
pathname: string
search: string
hash: string
}
export interface HistoryState {
key?: string
}
type ShouldAllowNavigation = any
export type BlockerFn = () =>
| Promise<ShouldAllowNavigation>
| ShouldAllowNavigation
const pushStateEvent = 'pushstate'
const popStateEvent = 'popstate'
const beforeUnloadEvent = 'beforeunload'
const beforeUnloadListener = (event: Event) => {
event.preventDefault()
// @ts-ignore
return (event.returnValue = '')
}
const stopBlocking = () => {
removeEventListener(beforeUnloadEvent, beforeUnloadListener, {
capture: true,
})
}
export function createHistory(opts: {
getLocation: () => HistoryLocation
pushState: (path: string, state: any) => void
replaceState: (path: string, state: any) => void
go: (n: number) => void
back: () => void
forward: () => void
createHref: (path: string) => string
flush?: () => void
destroy?: () => void
onBlocked?: (onUpdate: () => void) => void
}): RouterHistory {
let location = opts.getLocation()
const subscribers = new Set<() => void>()
let blockers: Array<BlockerFn> = []
const onUpdate = () => {
location = opts.getLocation()
subscribers.forEach((subscriber) => subscriber())
}
const tryNavigation = async (task: () => void) => {
if (typeof document !== 'undefined' && blockers.length) {
for (const blocker of blockers) {
const allowed = await blocker()
if (!allowed) {
opts.onBlocked?.(onUpdate)
return
}
}
}
task()
}
return {
get location() {
return location
},
subscribe: (cb: () => void) => {
subscribers.add(cb)
return () => {
subscribers.delete(cb)
}
},
push: (path: string, state: any) => {
state = assignKey(state)
tryNavigation(() => {
opts.pushState(path, state)
onUpdate()
})
},
replace: (path: string, state: any) => {
state = assignKey(state)
tryNavigation(() => {
opts.replaceState(path, state)
onUpdate()
})
},
go: (index) => {
tryNavigation(() => {
opts.go(index)
onUpdate()
})
},
back: () => {
tryNavigation(() => {
opts.back()
onUpdate()
})
},
forward: () => {
tryNavigation(() => {
opts.forward()
onUpdate()
})
},
createHref: (str) => opts.createHref(str),
block: (blocker) => {
blockers.push(blocker)
if (blockers.length === 1) {
addEventListener(beforeUnloadEvent, beforeUnloadListener, {
capture: true,
})
}
return () => {
blockers = blockers.filter((b) => b !== blocker)
if (!blockers.length) {
stopBlocking()
}
}
},
flush: () => opts.flush?.(),
destroy: () => opts.destroy?.(),
notify: onUpdate,
}
}
function assignKey(state: HistoryState | undefined) {
if (!state) {
state = {} as HistoryState
}
return {
...state,
key: createRandomKey(),
}
}
/**
* Creates a history object that can be used to interact with the browser's
* navigation. This is a lightweight API wrapping the browser's native methods.
* It is designed to work with TanStack Router, but could be used as a standalone API as well.
* IMPORTANT: This API implements history throttling via a microtask to prevent
* excessive calls to the history API. In some browsers, calling history.pushState or
* history.replaceState in quick succession can cause the browser to ignore subsequent
* calls. This API smooths out those differences and ensures that your application
* state will *eventually* match the browser state. In most cases, this is not a problem,
* but if you need to ensure that the browser state is up to date, you can use the
* `history.flush` method to immediately flush all pending state changes to the browser URL.
* @param opts
* @param opts.getHref A function that returns the current href (path + search + hash)
* @param opts.createHref A function that takes a path and returns a href (path + search + hash)
* @returns A history instance
*/
export function createBrowserHistory(opts?: {
parseLocation?: () => HistoryLocation
createHref?: (path: string) => string
window?: any
}): RouterHistory {
const win =
opts?.window ??
(typeof document !== 'undefined' ? window : (undefined as any))
const createHref = opts?.createHref ?? ((path) => path)
const parseLocation =
opts?.parseLocation ??
(() =>
parseHref(
`${win.location.pathname}${win.location.search}${win.location.hash}`,
win.history.state,
))
let currentLocation = parseLocation()
let rollbackLocation: HistoryLocation | undefined
const getLocation = () => currentLocation
let next:
| undefined
| {
// This is the latest location that we were attempting to push/replace
href: string
// This is the latest state that we were attempting to push/replace
state: any
// This is the latest type that we were attempting to push/replace
isPush: boolean
}
// Because we are proactively updating the location
// in memory before actually updating the browser history,
// we need to track when we are doing this so we don't
// notify subscribers twice on the last update.
let tracking = true
// We need to track the current scheduled update to prevent
// multiple updates from being scheduled at the same time.
let scheduled: Promise<void> | undefined
// This function is a wrapper to prevent any of the callback's
// side effects from causing a subscriber notification
const untrack = (fn: () => void) => {
tracking = false
fn()
tracking = true
}
// This function flushes the next update to the browser history
const flush = () => {
// Do not notify subscribers about this push/replace call
untrack(() => {
if (!next) return
win.history[next.isPush ? 'pushState' : 'replaceState'](
next.state,
'',
next.href,
)
// Reset the nextIsPush flag and clear the scheduled update
next = undefined
scheduled = undefined
rollbackLocation = undefined
})
}
// This function queues up a call to update the browser history
const queueHistoryAction = (
type: 'push' | 'replace',
destHref: string,
state: any,
) => {
const href = createHref(destHref)
if (!scheduled) {
rollbackLocation = currentLocation
}
// Update the location in memory
currentLocation = parseHref(destHref, state)
// Keep track of the next location we need to flush to the URL
next = {
href,
state,
isPush: next?.isPush || type === 'push',
}
if (!scheduled) {
// Schedule an update to the browser history
scheduled = Promise.resolve().then(() => flush())
}
}
const onPushPop = () => {
currentLocation = parseLocation()
history.notify()
}
const originalPushState = win.history.pushState
const originalReplaceState = win.history.replaceState
const history = createHistory({
getLocation,
pushState: (href, state) => queueHistoryAction('push', href, state),
replaceState: (href, state) => queueHistoryAction('replace', href, state),
back: () => win.history.back(),
forward: () => win.history.forward(),
go: (n) => win.history.go(n),
createHref: (href) => createHref(href),
flush,
destroy: () => {
win.history.pushState = originalPushState
win.history.replaceState = originalReplaceState
win.removeEventListener(pushStateEvent, onPushPop)
win.removeEventListener(popStateEvent, onPushPop)
},
onBlocked: (onUpdate) => {
// If a navigation is blocked, we need to rollback the location
// that we optimistically updated in memory.
if (rollbackLocation && currentLocation !== rollbackLocation) {
currentLocation = rollbackLocation
// Notify subscribers
onUpdate()
}
},
})
win.addEventListener(pushStateEvent, onPushPop)
win.addEventListener(popStateEvent, onPushPop)
win.history.pushState = function (...args: Array<any>) {
const res = originalPushState.apply(win.history, args)
if (tracking) history.notify()
return res
}
win.history.replaceState = function (...args: Array<any>) {
const res = originalReplaceState.apply(win.history, args)
if (tracking) history.notify()
return res
}
return history
}
export function createHashHistory(opts?: { window?: any }): RouterHistory {
const win =
opts?.window ??
(typeof document !== 'undefined' ? window : (undefined as any))
return createBrowserHistory({
window: win,
parseLocation: () => {
const hashHref = win.location.hash.split('#').slice(1).join('#') ?? '/'
return parseHref(hashHref, win.history.state)
},
createHref: (href) =>
`${win.location.pathname}${win.location.search}#${href}`,
})
}
export function createMemoryHistory(
opts: {
initialEntries: Array<string>
initialIndex?: number
} = {
initialEntries: ['/'],
},
): RouterHistory {
const entries = opts.initialEntries
let index = opts.initialIndex ?? entries.length - 1
let currentState = {
key: createRandomKey(),
} as HistoryState
const getLocation = () => parseHref(entries[index]!, currentState)
return createHistory({
getLocation,
pushState: (path, state) => {
currentState = state
entries.push(path)
index++
},
replaceState: (path, state) => {
currentState = state
entries[index] = path
},
back: () => {
index--
},
forward: () => {
index = Math.min(index + 1, entries.length - 1)
},
go: (n) => {
index = Math.min(Math.max(index + n, 0), entries.length - 1)
},
createHref: (path) => path,
})
}
function parseHref(
href: string,
state: HistoryState | undefined,
): HistoryLocation {
const hashIndex = href.indexOf('#')
const searchIndex = href.indexOf('?')
return {
href,
pathname: href.substring(
0,
hashIndex > 0
? searchIndex > 0
? Math.min(hashIndex, searchIndex)
: hashIndex
: searchIndex > 0
? searchIndex
: href.length,
),
hash: hashIndex > -1 ? href.substring(hashIndex) : '',
search:
searchIndex > -1
? href.slice(searchIndex, hashIndex === -1 ? undefined : hashIndex)
: '',
state: state || {},
}
}
// Thanks co-pilot!
function createRandomKey() {
return (Math.random() + 1).toString(36).substring(7)
}