-
Notifications
You must be signed in to change notification settings - Fork 2
/
MarkoRouter.js
541 lines (458 loc) · 15.6 KB
/
MarkoRouter.js
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
/*
* @Author: Matteo Zambon
* @Date: 2017-03-18 17:26:56
* @Last Modified by: Matteo Zambon
* @Last Modified time: 2017-03-30 07:47:43
*/
'use strict'
const EventEmitter = require('events')
const page = require('page')
const objectPath = require('object-path')
const UrlAssembler = require('url-assembler')
class MarkoRouter extends EventEmitter {
constructor(attr) {
super()
this._debug = typeof attr === 'object' && attr.debug ? attr.debug : false
this._logLine('[MarkoRouter] constructor')
if(this._debug) {
this._logLine('[MarkoRouter] You can check the PageJS instance on _pageInstance')
this._pageInstance = page
}
this._config = null
this._stateRoot = null
this._state = null
this._route = null
this._ctx = {}
}
/**
* Set config
* @created 2017-03-21T22:32:05-0300
* @param {object} newConfig Configuration object
* @return {null} no-return
*/
set config(newConfig) {
this._logLine('[MarkoRouter] set config.{newConfig}:')
this._logLine(newConfig)
this._config = newConfig
}
/**
* Get config
* @created 2017-03-21T22:32:50-0300
* @return {object} Configuration object
*/
get config() {
return this._config
}
/**
* Get Config property
* @private
* @created 2017-03-21T18:21:24-0300
* @param {string} keyPath Key Path for Page Config except State Root
* @param {string} stateRoot Override current State Root
* @return {any} Property related to State Root and Key Path
*/
_getConfig(keyPath, stateRoot) {
this._logLine('[MarkoRouter] _getConfig.{keyPath}: ' + keyPath)
this._logLine('[MarkoRouter] _getConfig.{stateRoot}: ' + stateRoot)
// Define whether use current State Root or override it
stateRoot = stateRoot || this._stateRoot
// Update Key Path including or isolating State Root
keyPath = keyPath ? [stateRoot, keyPath].join('.') : stateRoot
this._logLine('[MarkoRouter] _getConfig.{keyPath}:' + keyPath)
// Return value in Key Path of Config
const property = objectPath.get(this._config, keyPath)
this._logLine('[MarkoRouter] _getConfig.{property}:' + JSON.stringify(property))
return property
}
/**
* Log a line just if _debug is enabled
* @created 2017-03-28T16:30:45-0300
* @param {any} line Whatever needs to log
* @return {none} no-return
*/
_logLine(line) {
if(this._debug) {
/* eslint-disable */
console.log(line)
/* eslint-enable */
}
}
/**
* Get state root base property for specified stateRoot
* @private
* @created 2017-03-22T17:01:39-0300
* @param {string} stateRoot State root
* @return {string} State root base
*/
_getStateRootBase(stateRoot) {
stateRoot = stateRoot || this._stateRoot
this._logLine('[MarkoRouter] _getStatePath.{stateRoot}: ' + stateRoot)
// Get State Root Base
const stateRootBase = this._getConfig('_base', stateRoot)
this._logLine('[MarkoRouter] _getStateRootBase.{stateRootBase}: ' + stateRootBase)
if(!stateRootBase) {
throw new Error('Cannot find State Root Base of State Root (' + stateRoot + ')')
}
return stateRootBase
}
/**
* Get state root default state property for specified stateRoot
* @private
* @created 2017-03-22T17:01:39-0300
* @param {string} stateRoot State root
* @return {string} State root Default state
*/
_getStateRootDefaultState(stateRoot) {
stateRoot = stateRoot || this._stateRoot
this._logLine('[MarkoRouter] _getStatePath.{stateRoot}: ' + stateRoot)
// Get State Root DefaultState
const stateRootDefaultState = this._getConfig('_default', stateRoot)
this._logLine('[MarkoRouter] _getStateRootDefaultState.{stateRootDefaultState}: ' + stateRootDefaultState)
if(!stateRootDefaultState) {
throw new Error('Cannot find State Root Default State of State Root (' + stateRoot + ')')
}
return stateRootDefaultState
}
/**
* Get state root routes for specified stateRoot
* @private
* @created 2017-03-22T17:01:39-0300
* @param {string} stateRoot State root
* @return {object} State root routes
*/
_getStateRootRoutes(stateRoot) {
stateRoot = stateRoot || this._stateRoot
this._logLine('[MarkoRouter] _getStatePath.{stateRoot}: ' + stateRoot)
const stateRootConfig = this._getConfig(undefined, stateRoot)
const routes = {}
for(const r in stateRootConfig) {
const route = stateRootConfig[r]
if(r.match(/^_/)) {
this._logLine('[MarkoRouter] _getStateRootRoutes.{r}: ' + r + ' < SKIPPED >')
continue
}
routes[r] = route
this._logLine('[MarkoRouter] _getStateRootRoutes.{r}: ' + r)
}
return routes
}
/**
* Get state property for specified stateRoot
* @private
* @created 2017-03-22T17:01:39-0300
* @param {string} state State
* @param {string} stateRoot State root
* @return {object} State
*/
_getStateRoute(state, stateRoot) {
stateRoot = stateRoot || this._stateRoot
this._logLine('[MarkoRouter] _getStatePath.{state}: ' + state)
this._logLine('[MarkoRouter] _getStatePath.{stateRoot}: ' + stateRoot)
// Get State Route
const stateRoute = this._getConfig(state, stateRoot)
this._logLine('[MarkoRouter] _getStateRoute.{stateRoute}: ' + stateRoute)
if(!stateRoute) {
throw new Error('Cannot find State (' + state + ') on State Root (' + stateRoot + ')')
}
return stateRoute
}
/**
* Get state path property for specified stateRoot
* @private
* @created 2017-03-22T17:01:39-0300
* @param {string} state State
* @param {string} stateRoot State root
* @return {string} State path
*/
_getStatePath(state, stateRoot) {
stateRoot = stateRoot || this._stateRoot
this._logLine('[MarkoRouter] _getStatePath.{state}: ' + state)
this._logLine('[MarkoRouter] _getStatePath.{stateRoot}: ' + stateRoot)
// Get Path of State
const statePath = this._getConfig(state + '.path', stateRoot)
this._logLine('[MarkoRouter] _getStatePath.{statePath}: ' + statePath)
if(!statePath) {
throw new Error('Cannot find State (' + state + ') Path on State Root (' + stateRoot + ')')
}
return statePath
}
/**
* Get path from state, params and stateRoot
* @private
* @created 2017-03-22T17:01:39-0300
* @param {string} state State
* @param {object} params Url parameters
* @param {string} stateRoot State root
* @param {object} queries Query string parameters
* @return {string} Url path computed
*/
_getStatePathUrl(state, params, stateRoot, queries) {
stateRoot = stateRoot || this._stateRoot
this._logLine('[MarkoRouter] _getStatePathUrl.{state}: ' + state)
this._logLine('[MarkoRouter] _getStatePathUrl.{params}: ' + JSON.stringify(params))
this._logLine('[MarkoRouter] _getStatePathUrl.{stateRoot}: ' + stateRoot)
this._logLine('[MarkoRouter] _getStatePathUrl.{queries}: ' + JSON.stringify(queries))
// Get Path of State
const url = this._getStatePath(state, stateRoot)
// Initialize UrlAssembler instance
let urlAssembler = UrlAssembler()
// Check if prefix is needed
if(stateRoot !== this._stateRoot) {
const base = this._getStateRootBase(stateRoot)
urlAssembler = urlAssembler.prefix(base)
}
// Add template
urlAssembler = urlAssembler.template(url)
// Compute params
if(params) {
urlAssembler = urlAssembler.param(params)
}
// Compute query strings
if(queries) {
urlAssembler = urlAssembler.query(queries)
}
// Get assembled url
const urlAssembled = urlAssembler.toString()
this._logLine('[MarkoRouter] _getStatePathUrl.{urlAssembled}: ' + urlAssembled)
return urlAssembled
}
/**
* Define Page Base based on '_base' key in State Root Config
* @private
* @created 2017-03-21T18:26:26-0300
* @return {none} no-return
*/
_defPageBase() {
// {this.stateRoot}._base
const base = this._getStateRootBase()
// Set Page Base
page.base(base)
}
/**
* Define Page Default (redirect / to correct state)
* @private
* @created 2017-03-21T18:27:58-0300
* @return {none} no-return
*/
_defPageDefault() {
// {this._stateRoot}._default
const stateDefault = this._getStateRootDefaultState()
// {this._stateRoot}.{stateDefault}.path
const stateDefaultPath = this._getStatePath(stateDefault)
// redirect / to {this._stateRoot}.{stateDefault}.path
page('/', stateDefaultPath)
}
/**
* Define Page Routes
* @private
* @created 2017-03-21T18:40:15-0300
* @return {none} no-return
*/
_defPageRoutes() {
const stateRootRoutes = this._getStateRootRoutes()
// For each public property of State Root Config
for(const routeState in stateRootRoutes) {
// Get property as route
const route = stateRootRoutes[routeState]
this._logLine('[MarkoRouter] _defPageRoutes.{routeState}: ' + routeState)
// If {route} is string means it's a redirect
if(typeof route === 'string') {
this._logLine('[MarkoRouter] _defPageRoutes.{route}: ' + route + ' < IS REDIRECT >')
// Setup page redirect from {r} to {route} ({r} and {route} must be paths of the same State Root)
page(routeState, route)
continue
}
// Define Page with {r} as state and {route}
this._defPageRoute(routeState, route)
}
}
/**
* Define Page Route
* @private
* @created 2017-03-21T18:43:05-0300
* @param {string} state State
* @param {object} route Route
* @return {none} no-return
*/
_defPageRoute(state, route) {
this._logLine('[MarkoRouter] _defPageRoute.{state}: ' + state)
this._logLine('[MarkoRouter] _defPageRoute.{route.path}: ' + route.path)
// Set a Page Route and use a function as handler
page(route.path, (ctx) => {
this._logLine('[MarkoRouter] onMatch.{state}: ' + state)
this._logLine('[MarkoRouter] onMatch.{route.path}: ' + route.path)
this._logLine('[MarkoRouter] onMatch.{ctx}: ')
this._logLine(ctx)
// Set current state root {this._stateRoot}
const stateRoot = this._stateRoot
// Set current state {this._state}
const fromState = this._state
// Set current route {this._route}
const fromRoute = this._route
// Set next state {state}
const toState = state
// Set next route {route}
const toRoute = route
// Set ctx as {ctx}
this._ctx = ctx
// Set state as {toState}
this._state = toState
// Set state as {toRoute}
this._route = toRoute
// Emit event state.change
this._emitChangeState({
'ctx': ctx,
'stateRoot': stateRoot,
'from': {
'state': fromState,
'route': fromRoute
},
'to': {
'state': toState,
'route': toRoute
}
})
})
}
/**
* Emit State has been changed
* @private
* @created 2017-03-21T18:50:31-0300
* @param {object} args Arguments to pass during event
* @return {none} no-return
*/
_emitChangeState(args) {
this._logLine('[MarkoRouter] _emitChangeState.{args}: ')
this._logLine(args)
this.emit('state.change', args)
}
/**
* Emit Page has been Initialized
* @private
* @created 2017-03-21T18:50:31-0300
* @param {object} args Arguments to pass during event
* @return {none} no-return
*/
_emitPageInit(args) {
this._logLine('[MarkoRouter] _emitPageInit.{args}: ')
this._logLine(args)
this.emit('page.init', args)
}
/**
* Set current state root
* @created 2017-03-21T18:57:27-0300
* @param {string} newStateRoot State Root to be set
* @return {none} no-return
*/
set stateRoot(newStateRoot) {
this._logLine('[MarkoRouter] set stateRoot.{this._stateRoot}: ' + this._stateRoot)
this._logLine('[MarkoRouter] set stateRoot.{newStateRoot}: ' + newStateRoot)
this._stateRoot = newStateRoot
}
/**
* Get current state root
* @created 2017-03-21T18:58:32-0300
* @return {string} Current state root
*/
get stateRoot() {
return this._stateRoot
}
/**
* Set current state
* @created 2017-03-21T18:57:27-0300
* @param {string} newState State to be set
* @return {none} no-return
*/
set state(newState) {
this._logLine('[MarkoRouter] set state.{this._state}: ' + this._state)
this._logLine('[MarkoRouter] set state.{newState}: ' + newState)
this._state = newState
this._route = this._getStateRoute(newState)
}
/**
* Get current state
* @created 2017-03-21T18:58:32-0300
* @return {string} Current state
*/
get state() {
return this._state
}
/**
* Get current context
* @created 2017-03-21T18:59:57-0300
* @return {object} Current context
*/
get ctx() {
return this._ctx
}
/**
* Handle onMount from Marko Component
* @created 2017-03-21T19:00:34-0300
* @param {string} stateRoot Current Root State
* @param {string} state Current State
* @return {none} no-return
*/
handleOnMount(stateRoot, state) {
this._logLine('[MarkoRouter] handleOnMount.{stateRoot}: ' + stateRoot)
this._logLine('[MarkoRouter] handleOnMount.{state}: ' + state)
// Set current stateRoot
this._stateRoot = stateRoot
// Set current state
if(state) {
this.state = state
}
// Initialize Page
this._pageInit()
}
/**
* Go To State
* @created 2017-03-21T19:07:27-0300
* @param {string} state New state
* @param {object} params State parameters
* @param {string} stateRoot New state root
* @return {none} no-return
*/
goTo(state, params, stateRoot) {
stateRoot = stateRoot || this._stateRoot
this._logLine('[MarkoRouter] goTo.{state}: ' + state)
this._logLine('[MarkoRouter] goTo.{params}: ' + JSON.stringify(params))
this._logLine('[MarkoRouter] goTo.{stateRoot}: ' + stateRoot)
const url = this._getStatePathUrl(state, params, stateRoot)
if(stateRoot !== this._stateRoot) {
// Set Page Base to new State Root
this.goToExternalUrl(url)
return
}
// Redirect to Path
this.goToInternalUrl(url)
}
goToInternalUrl(url) {
page(url)
}
goToExternalUrl(url) {
location.href = url
}
/**
* Initialize Page
* @created 2017-03-21T19:11:02-0300
* @return {none} no-return
*/
_pageInit() {
this._logLine('[MarkoRouter] _pageInit.{this}: ')
this._logLine(this)
// Define Page Base
this._defPageBase()
// Define Page Default
this._defPageDefault()
// Define Page Routes
this._defPageRoutes()
// Start Page
page()
// Emit Page has been Initialized
this._emitPageInit({
'state': this._state,
'stateRoot': this._stateRoot
})
}
}
module.exports = MarkoRouter