-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathko-router.js
253 lines (238 loc) · 9.11 KB
/
ko-router.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
( function ( root, factory ) {
if ( typeof define === 'function' && define.amd ) {
define( [ 'ko' ], factory );
} else {
root.router = factory( root.ko );
};
}( this, function ( ko ) {
"use strict";
var router = {
on404: function ( rt, e ) {
throw new Error( [
'Path' + router.resolvePath.apply( router, rt ) + ' not found.',
'You can handle the error by overriding this function.'
].join( '\n' ) );
},
route: ko.observableArray(),
root: Page( {
title: window.document.title
} ),
resolvePath: function resolvePath() {
var args = Array.from( arguments );
var url = args.map( function ( r, i, s ) {
if ( r.slice( -1 ) !== '/' && i !== s.length - 1 ) r += '/';
return r;
} ).reduce( function ( url, path ) {
return new window.URL( path, url.href );
}, new window.URL( window.location.origin ) );
return url.pathname + url.search + url.hash;
},
navigate: function navigate( href ) {
href = router.resolvePath( href );
return guards( path( href ) ).then( function () {
window.history.pushState( {}, '', href );
router.route( path() );
} );
},
start: function start( opts ) {
return ( window.onpopstate = handlePop )();
},
loader: {
start: function () {},
done: function () {}
}
};
router.Page = Page;
ko.bindingHandlers[ 'page' ] = {
init: function ( element, valueAccessor, allBindingsAccessor, viewModel, bindingContext ) {
var value = valueAccessor();
if ( !value.route ) throw new Error( 'route required' );
var parent = bindingContext._page || router.root;
var page = parent.to[ value.route ] = parent.to[ value.route ] || Page( {
route: value.route
} );
Object.assign( page, {
element: element,
src: value.src,
title: value.title || parent.title,
template: value.template,
guard: value.guard,
onclose: value.onclose,
context: bindingContext
} );
page.close();
return {
controlsDescendantBindings: true
};
}
};
ko.bindingHandlers[ 'nav' ] = {
update: function ( element, valueAccessor, allBindingsAccessor, viewModel, bindingContext ) {
var value = valueAccessor();
var page = bindingContext._page || {};
var route = page.path ? page.path() : '/';
if ( element.tagName === 'A' ) element.href = router.resolvePath( route, value );
element.onclick = function ( ev ) {
var href = this.href || router.resolvePath( route, value );
if ( ev.button !== 0 || ( ev.ctrlKey && ev.button === 0 ) ) {
if ( this.tagName !== 'A' ) window.open( href, '_blank' ).focus();
return true;
};
router.navigate( href );
return false;
};
}
};
function Page( data ) {
if ( !( this instanceof Page ) ) return new Page( data );
data = data || {};
this.element = data.element;
this.route = data.route;
this.title = data.title;
this.template = data.template;
this.guard = data.guard;
this.onclose = data.onclose;
this.current = '';
this.src = data.src;
this.context = data.context;
this.to = {};
};
Page.prototype.check = function check( route ) {
return wrap( this.guard, this, [ route ] ).then( function () {
return this;
}.bind( this ) );
};
Page.prototype.ensureTemplate = function ensureTemplate() {
var tmplname = this.template.name || this.template;
var tmpl = window.document.querySelector( 'script#' + tmplname );
if ( !tmpl && !this.src ) return Promise.reject( new Error( 'No template or source supplied' ) );
if ( !tmpl && this.src ) return window.fetch( encodeURI( this.src ) ).then( function ( response ) {
if ( response.status !== 200 ) {
var e = new Error( response.statusText );
e.response = response;
throw e;
};
return response.text();
} ).then( function ( text ) {
var tmpl = document.createElement( 'div' );
tmpl.innerHTML = text;
tmpl = tmpl.firstChild;
if ( !tmpl || tmpl.tagName !== 'SCRIPT' || tmpl.id !== tmplname ) throw new Error( 'Wrong source' );
window.document.body.appendChild( tmpl );
} );
};
Page.prototype.open = function open( current ) {
this.current = current;
if ( !this.template || !this.element ) return this;
ko.applyBindingsToNode( this.element, {
template: this.template
}, this.context.extend( {
_page: this
} ) );
this.element.style.display = '';
return this;
};
Page.prototype.close = function close() {
this.current = '';
var children = Array.from( this.element.children );
var ready = Promise.resolve();
if ( children.length ) ready = wrap( this.onclose, this );
return ready.then( function () {
children.map( function ( c ) {
c.remove();
} );
this.element.style.display = 'none';
return this;
}.bind( this ) );
};
Page.prototype.closeChildren = function closeChildren() {
return Promise.all( Object.keys( this.to ).map( function ( t ) {
return this.to[ t ].close();
}.bind( this ) ) );
};
Page.prototype.closeSiblings = function closeSiblings() {
var parent = this.parent();
if ( !parent ) return;
return Promise.all( Object.keys( parent.to ).map( function ( t ) {
if ( parent.to[ t ] !== this ) return parent.to[ t ].close();
}.bind( this ) ) );
};
Page.prototype.next = function next( route ) {
if ( !route && this.to[ '/' ] ) return this.to[ '/' ];
if ( route && this.to[ route ] ) return this.to[ route ];
if ( route && this.to[ '*' ] ) return this.to[ '*' ];
};
Page.prototype.path = function path() {
var path = [];
var parent = this;
do {
path.unshift( parent.current );
parent = parent.parent();
} while ( parent )
return path.join( '/' );
};
Page.prototype.parent = function parent() {
if ( this === router.root ) return;
try {
return this.context._page || router.root;
} catch ( e ) {
return router.root;
};
};
function guards( rt ) {
router.loader.start();
console.log( 'GUARD', rt );
return router.root.check( rt ).then( workGuard.bind( this, {
rt: Array.from( rt ),
page: router.root
} ) ).then( function ( page ) {
window.document.title = page.title || router.root.title;
router.loader.done();
return page;
} ).catch( function ( e ) {
if ( e instanceof Promise ) return e;
if ( e instanceof Error && e.message === 'Page not found' )
return router.on404( rt, e );
throw e;
router.loader.done();
} );
};
function workGuard( cur ) {
var r = cur.rt.shift();
var next = cur.page.next( r );
if ( !next ) return cur.page.closeChildren().then( function () {
if ( r ) return Promise.reject( new Error( 'Page not found' ) );
return Promise.resolve( cur.page );
}.bind( this ) );
return Promise.all( [ next.check( r ), next.ensureTemplate() ] ).then( function ( res ) {
cur.page = res[ 0 ];
if ( cur.page.current === r ) return;
return cur.page.closeSiblings().then( function () {
cur.page.open( r );
} );
} ).then( workGuard.bind( this, cur ) );
};
function handlePop() {
return guards( path() ).then( function () {
router.route( path() );
} );
};
function path( pathname ) {
return ( pathname || window.location.pathname ).slice( 1 ).split( '/' ).filter( function ( r ) {
return !!r;
} );
};
function wrap( target, reciever, args ) {
if ( target instanceof Error ) return Promise.reject( target );
if ( !( target instanceof Function ) ) return Promise.resolve( target );
if ( !Array.isArray( args ) ) args = [ args ];
try {
var r = ( reciever || args ) ? target.apply( reciever, args ) : target.call();
if ( !( r instanceof Promise ) ) return Promise.resolve( r );
return r;
} catch ( e ) {
return Promise.reject( e );
};
};
return router;
} ) );