This repository has been archived by the owner on Dec 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chyk.tsx
199 lines (181 loc) · 5.6 KB
/
chyk.tsx
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
import { createBrowserHistory, createLocation, History, Location } from "history"
import { StaticRouterContext } from "react-router"
import { MatchedRoute, matchRoutes } from "react-router-config"
import { loadBranchComponents, loadBranchDataObject, TLocationData, TRouteConfig } from "./match"
import { chykHydrateOrRender } from "./render"
import { ComponentType } from "react"
export type TStatusCode = number
export type TChykLocationState = {
pathname: string
matches: MatchedRoute<{}>[]
abortController: AbortController
location: Location
loading: boolean
statusCode: TStatusCode
data?: TLocationData
}
export type TChykLocationsStates = Record<string, TChykLocationState>
type TChykProps<D = any> = {
routes: TRouteConfig[]
el?: HTMLElement | null
data?: TLocationData
statusCode?: TStatusCode
deps: D extends undefined ? never : D
component?: ComponentType
history?: History
onLoadError?: (err: Error) => void
}
export class Chyk<D = any> {
private _el: HTMLElement | undefined | null = null
get el(): HTMLElement {
if (!this._el) {
throw "No element"
}
return this._el
}
history: History | null
onLoadError: (err: Error) => void = err => {
throw err
}
staticRouterContext: StaticRouterContext = {}
routes: TRouteConfig[]
deps: D extends undefined ? never : D
component?: ComponentType
get isBrowser(): boolean {
return Boolean(this.history)
}
get loading(): boolean {
return Object.values(this.locationStates).some(state => state.loading)
}
private locationStates: TChykLocationsStates = {}
private location: Location = { pathname: "" } as any
constructor(props: TChykProps<D>) {
this.routes = props.routes
this.deps = props.deps
this.component = props.component
this._el = props.el
this.history = props.history || props.el ? createBrowserHistory() : null
if (props.onLoadError) {
this.onLoadError = props.onLoadError
}
if (this.history) {
this.location = this.history.location
this.mergeLocationState(this.location.pathname, {
data: props.data,
location: this.history.location,
...(props.statusCode ? { statusCode: props.statusCode } : null),
})
this.loadAndRender(Boolean(props.data))
}
}
async loadAndRender(disableDataLoading: boolean) {
if (!this.history) {
throw "No history"
}
if (!disableDataLoading) {
await this.loadData(this.history.location)
} else {
const matches = matchRoutes(this.routes, this.history.location.pathname)
await loadBranchComponents(matches)
}
chykHydrateOrRender(this)
}
upsertLocationStateLoading(
abortController: AbortController,
pathname: string,
matches: MatchedRoute<{}>[],
location: Location
) {
this.mergeLocationState(pathname, {
matches,
pathname,
location,
abortController,
statusCode: 200,
loading: true,
})
}
updateLocationStateLoaded(pathname: string, data: any) {
this.mergeLocationState(pathname, {
data,
loading: false,
})
}
private mergeLocationState(pathname: string, state: Partial<TChykLocationState>) {
const _state = this.locationStates[pathname] || {}
this.locationStates[pathname] = Object.assign(_state, state)
}
getLocationState(pathname: string): TChykLocationState {
return this.locationStates[pathname]
}
get locationState(): TChykLocationState {
return this.locationStates[this.location.pathname]
}
get statusCode(): TStatusCode {
return this.locationState.statusCode
}
get data(): any {
return this.locationState.data
}
cleanLocationState(pathname: string) {
delete this.locationStates[pathname]
}
loadData = async (_location: string | Location): Promise<boolean> => {
try {
const abortController = this.isBrowser
? new AbortController()
: ({ signal: { aborted: false } } as AbortController) // mock on server
const location = typeof _location === "string" ? createLocation(_location) : _location
const { pathname } = location
const matches = matchRoutes(this.routes, pathname)
this.upsertLocationStateLoading(abortController, pathname, matches, location)
const [data] = await Promise.all([
loadBranchDataObject(this, matches, abortController),
loadBranchComponents(matches),
])
this.location = location
this.updateLocationStateLoaded(pathname, data)
return true
} catch (err) {
if (err.name === "AbortError") {
// request was aborted, so we don't care about this error
// console.log("AbortError", err)
} else {
this.onLoadError(err)
}
return false
}
}
abortLoading() {
Object.values(this.locationStates).forEach(state => {
state.abortController && state.abortController.abort()
state.loading = false
})
}
get is404(): boolean {
return this.statusCode === 404
}
setStatus(statusCode: TStatusCode) {
Object.values(this.locationStates).forEach(state => {
if (state.loading) {
state.statusCode = statusCode
}
})
}
set404 = (): void => {
this.setStatus(404)
}
handleLocationChange = async (new_location: Location): Promise<boolean> => {
const location = this.locationState.location
if (location.pathname === new_location.pathname) {
return false
}
this.abortLoading()
if (this.getLocationState(new_location.pathname)) {
return false
}
const is_success = await this.loadData(new_location)
this.cleanLocationState(is_success ? location.pathname : new_location.pathname)
return true
}
}