-
-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy pathrouter.ts
216 lines (185 loc) · 5.26 KB
/
router.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
import { App } from '@capacitor/app'
import Rlite from 'rlite-router'
import render from 'mithril/render'
import Vnode from 'mithril/render/vnode'
import isFunction from 'lodash-es/isFunction'
import signals from './signals'
import { serializeQueryParameters } from './utils'
import redraw from './utils/redraw'
interface Backbutton {
(): void
stack: Array<(fromBB?: string) => void>
}
const uid = (function() {
let id = 0
return () => id++
})()
const router = new Rlite()
// unique incremented state id to determine slide direction
let currentStateId = 0
let viewSlideDirection = 'fwd'
let previousPath = '/'
const mountPoint = document.body
export function withRouter(f: (r: Rlite.Rlite) => void): void {
f(router)
}
export function onRouteMatch<T>(component: Mithril.Component, params: T): void {
const RouteComponent = {view() {
return Vnode(component, undefined, params)
}}
function redraw() {
render(mountPoint, Vnode(RouteComponent))
}
signals.redraw.removeAll()
signals.redraw.add(redraw)
// some error may be thrown during component initialization
// in that case shutdown redraws to avoid multiple execution of oninit
// hook of buggy component
try {
redraw()
} catch (e) {
signals.redraw.removeAll()
throw e
}
}
export function processWindowLocation(e?: PopStateEvent): void {
if (e && e.state) {
if (e.state.id < currentStateId) {
viewSlideDirection = 'bwd'
} else {
viewSlideDirection = 'fwd'
}
currentStateId = e.state.id
}
previousPath = getPath()
const qs = window.location.search || '?='
const matched = router.run(qs.slice(2))
if (!matched) router.run('/')
}
const History = {
replaceState(state?: { [k: string]: unknown }, path?: string): void {
// try catch to avoid ios 9 100th pushState call DOM error
// see https://forums.developer.apple.com/thread/36650
// and https://bugs.webkit.org/show_bug.cgi?id=156115
// (may be only 100 calls per 30s interval in ios 10... need to test)
try {
const newState = state ?
Object.assign({}, window.history.state, state) :
window.history.state
if (path !== undefined) {
window.history.replaceState(newState, '', '?=' + path)
} else {
window.history.replaceState(newState, '')
}
} catch (e) { console.error(e) }
},
pushState(path: string): void {
const stateId = uid()
currentStateId = stateId
viewSlideDirection = 'fwd'
try {
window.history.pushState({ id: stateId }, '', '?=' + path)
} catch (e) { console.error(e) }
},
}
function setQueryParams(params: Record<string, string>, newState = false): void {
const path = (window.location.search || '?=/').substring(2).replace(/\?.+$/, '')
const newPath = path + `?${serializeQueryParameters(params)}`
if (newState) {
setPath(newPath, true)
} else {
History.replaceState(undefined, newPath)
}
}
function deleteQueryParam(name: string, newState = false): void {
const params = getQueryParams()
if (params) {
delete params[name]
setQueryParams(params, newState)
}
}
function getQueryParams(): Record<string, string> {
const path = getPath()
const match = /\?.+$/.exec(path)
const params: Record<string, string> = {}
if (match && match[0]) {
for (const [k, v] of new URLSearchParams(match[0])) {
params[k] = v
}
}
return params
}
const backbutton: Backbutton = (() => {
type BBHandler = (fromBB?: string) => void
interface X {
(): void
stack?: Array<BBHandler>
}
const x: X = () => {
const b = x.stack!.pop()
if (isFunction(b)) {
b('backbutton')
redraw()
} else if (!/^\/$/.test(getPath())) {
// disable back history on game to prevent accidental quitting of a game
// see src/ui/shared/round/OnlineRound.ts for the backbutton behavior during
// a game
if (/^\/game\/[a-zA-Z0-9]{12}/.test(getPath())) {
signals.gameBackButton.dispatch(event)
} else {
backHistory()
}
} else {
App.exitApp()
}
}
x.stack = [] as Array<BBHandler>
return <Backbutton>x
})();
// for debug purposes
(window as any)['backButton'] = backbutton
function doSet(path: string, replace = false) {
// reset backbutton stack when changing route
backbutton.stack = []
previousPath = getPath()
if (replace) {
History.replaceState(undefined, path)
} else {
History.pushState(path)
}
const matched = router.run(path)
if (!matched) router.run('/')
}
// sync call to router.set must be avoided in any `oninit` mithril component
// otherwise it makes mithril create another root component on top of the
// existing one
// making router.set async makes it safe everywhere
function setPath(path: string, replace = false): void {
setTimeout(() => doSet(path, replace), 0)
}
function getPath(): string {
const path = window.location.search || '?=/'
return decodeURIComponent(path.substring(2))
}
function backHistory(): void {
window.history.go(-1)
}
export default {
get: getPath,
set: setPath,
reload(): void {
setPath(getPath(), true)
},
setQueryParams,
getQueryParams,
deleteQueryParam,
History,
backHistory,
getViewSlideDirection(): string {
return viewSlideDirection
},
backbutton,
getPreviousPath(): string {
return previousPath
},
}