-
Notifications
You must be signed in to change notification settings - Fork 8
/
jquery.lazyjaxdavis.coffee
569 lines (456 loc) · 14.3 KB
/
jquery.lazyjaxdavis.coffee
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
(($, window, document) -> # encapsulate whole start
ns = {}
$document = $(document)
# ============================================================
# tiny utils
# setTimeout wrapper
wait = ns.wait = (time) ->
$.Deferred (defer) ->
setTimeout ->
defer.resolve()
, time
# detect features
$.support.pushstate = $.isFunction window.history.pushState
# ============================================================
# string manipulators
# "#foobar" -> true
# "foobar" -> false
ns.isToId = (path) ->
if (path.charAt 0) is '#'
return true
else
return false
# "hogehoge#foobar" -> hogehoge
ns.trimAnchor = (str) ->
str.replace /#.*/, ''
# "page.html?foo=bar" -> "page.html"
ns.trimGetVals = (path) ->
path.replace /\?.*/, ''
# "/somewhere/foo.html#bar" will be parsed to...
# { path: "/somewhere/foo.html", hash: "#bar" }
ns.tryParseAnotherPageAnchor = (path) ->
if ns.isToId(path)
return false
if (path.indexOf '#') is -1
return false
res = path.match /^([^#]+)#(.+)/
ret = { path: res[1] }
if res[2] then ret.hash = "##{res[2]}"
ret
# filters html string
#
# "<title>foobar</title>", /<title[^>]*>([^<]*)<\/title>/
# -> "foobar"
#
# '<img src="foobar.gif"> <img src="moomoo.png">', /src="([^"]+)"/gi, true
# -> [ "foobar.gif", "moomoo.png" ]
ns.filterStr = (str, expr, captureAll) ->
if captureAll
res = []
str.replace expr, (matched, captured) ->
res.push captured
return res
else
res = str.match expr
if res and res[1]
return $.trim res[1]
else
return null
# ============================================================
# logger
# prepare this if there's Davis. else do nothing about this
ns.logger = if window.Davis then (new Davis.logger).logger else null
# shortcuts
ns.info = info = (msg) ->
if not ns.logger then return
ns.logger.info msg
ns.error = error = (msg) ->
if not ns.logger then return
ns.logger.error msg
# ============================================================
# ajax callers
ns.fetchPage = (->
current = null
(url, options) ->
ret = $.Deferred (defer) ->
current.abort() if current?.abort?
defaults = { url: url }
options = $.extend defaults, options
current = ($.ajax options)
current.then (res) ->
current = null
defer.resolve res
, (xhr, msg) ->
aborted = (msg is 'abort')
defer.reject aborted
.promise()
ret.abort = -> current?.abort?()
ret
)()
# ============================================================
# event module
class ns.Event
constructor: ->
@_callbacks = {}
bind: (ev, callback) ->
evs = ev.split(' ')
for name in evs
@_callbacks[name] or= []
@_callbacks[name].push(callback)
@
one: (ev, callback) ->
@bind ev, ->
@unbind(ev, arguments.callee)
callback.apply(@, arguments)
trigger: (args...) ->
ev = args.shift()
list = @_callbacks?[ev]
return unless list
for callback in list
if callback.apply(@, args) is false
break
@
unbind: (ev, callback) ->
unless ev
@_callbacks = {}
return @
list = @_callbacks?[ev]
return this unless list
unless callback
delete @_callbacks[ev]
return this
for cb, i in list when cb is callback
list = list.slice()
list.splice(i, 1)
@_callbacks[ev] = list
break
@
# ============================================================
# main
class ns.HistoryLogger
constructor: ->
@_items = []
# push first page
@_items.push (ns.trimAnchor location.pathname)
push: (obj) ->
@_items.push obj
@
last: ->
l = @_items.length
return if l then @_items[l-1] else null
isToSamePageRequst: (path) ->
path = (ns.trimAnchor path)
last = (ns.trimAnchor @last())
if not last then return false
if path is last
return true
else
return false
size: ->
@_items.length
class ns.Page extends ns.Event
eventNames = [
'fetchstart'
'fetchsuccess'
'fetchabort'
'fetchfail'
'pageready'
'anchorhandler'
]
options:
ajxoptions:
dataType: 'text'
cache: true
expr: null
updatetitle: true
title: null
router: null
config: null
_text: null
constructor: (@request, config, @routed, @router, options, @hash) ->
super
@config = $.extend {}, @config, config
@options = $.extend true, {}, @options, options
if ($.type @config.path) is 'string'
@path = @config.path
else
@path = @request.path
$.each eventNames, (i, eventName) =>
$.each @config, (key, val) =>
if eventName isnt key then return true
@bind eventName, val
anchorhandler = @config?.anchorhandler or @options?.anchorhandler
if anchorhandler then @_anchorhandler = anchorhandler
@bind 'pageready', =>
if not @hash then return
@_anchorhandler.call @, @hash
_anchorhandler: (hash) ->
if not hash then return @
top = ($document.find hash).offset().top
window.scrollTo 0, top
@
fetch: ->
currentFetch = null
path = @request.path
# prepare ajax options
o = @options?.ajaxoptions or {}
if @config?.method
o.type = @config.method
if @request?.params
o.data = $.extend true, {}, o.data, @request.params
@_fetchDefer = $.Deferred (defer) =>
currentFetch = (ns.fetchPage path, o)
currentFetch.then (text) =>
@_text = text
@updatetitle()
defer.resolve()
, (aborted) =>
defer.reject
aborted: aborted
.always =>
@_fetchDefer = null
@_fetchDefer.abort = -> currentFetch.abort()
@_fetchDefer
abort: ->
@_fetchDefer?.abort()
@
rip: (exprKey, captureAll) ->
if not @_text then return null
if not exprKey then return @_text
expr = @options?.expr?[exprKey]
if not expr then return null
res = ns.filterStr @_text, expr, captureAll
if not res
error "ripper could not find the text for key: #{exprKey}"
res
ripAll: (exprKey) ->
@rip exprKey, true
updatetitle: ->
if not @options.updatetitle then return @
title = null
if not title and @_text
title = @rip('title')
if not title then return @
document.title = title
@
class ns.Router extends ns.Event
options:
ajaxoptions:
dataType: 'text'
cache: true
type: 'GET'
expr:
title: /<title[^>]*>([^<]*)<\/title>/
content: /<!-- LazyJaxDavis start -->([\s\S]*)<!-- LazyJaxDavis end -->/
davis:
linkSelector: 'a:not([href^=#]):not(.apply-nolazy)'
formSelector: 'form:not(.apply-nolazy)'
throwErrors: false
handleRouteNotFound: true
minwaittime: 0
updatetitle: true
firereadyonstart: true
ignoregetvals: false
constructor: (initializer) ->
super
@history = new ns.HistoryLogger
initializer.call @, @
if @options.davis then @_setupDavis()
@firePageready not @options.firereadyonstart
@fireTransPageready()
_createPage: (request, config, routed, hash) ->
# prepare option for Page
o =
expr: @options.expr
updatetitle: @options.updatetitle
# handle anchorhandler
if @options.anchorhandler
o.anchorhandler = @options.anchorhandler
# handle ajaxoptions
# use config or @options
if config?.ajaxoptions
o.ajaxoptions = config.ajaxoptions
else if @options.ajaxoptions
o.ajaxoptions = @options.ajaxoptions
# detect hash
if not hash and request?.path
res = ns.tryParseAnotherPageAnchor request.path
hash = res.hash or null
new ns.Page request, config, routed, @, o, hash
_setupDavis: ->
if not $.support.pushstate then return # you can't use it
self = @ # Davis needs "this" scope
# complete action
completePage = (page) ->
page.bind 'pageready', ->
self._findWhosePathMatches 'page', page.path # just find for raise error
self.trigger 'everypageready'
self.fireTransPageready()
self.history.push page.path
self.fetch page
# start Davis initialization
@davis = new Davis ->
davis = @
# handle @pages
if self.pages
$.each self.pages, (i, pageConfig) ->
# make davis treat pages which was
# attached pageexpr as, routeNoutFound.
if $.type(pageConfig.path) is 'regexp' then return
method = (pageConfig.method or 'get').toLowerCase()
davis[method] pageConfig.path, (request) ->
if self.history.isToSamePageRequst request.path then return
page = self._createPage request, pageConfig, true
completePage page
true
# handle routNotFound
if self.options.davis.handleRouteNotFound
davis.bind 'routeNotFound', (request) ->
# if it was just an anchor to the same page, ignore it
if ns.isToId request.path
self.trigger 'toid', request.path
return
# check whether the request was another page with anchor.
# If was anchored, there may be config in @pages
res = ns.tryParseAnotherPageAnchor request.path
hash = res.hash or null
path = res.path or request.path
# log
if self.history.isToSamePageRequst path then return
# find matched page config
config = (self._findWhosePathMatches 'page', path) or null
routed = if config then true else false
# then complete it
page = self._createPage request, config, routed, hash
completePage page
# configure davis
davis.configure (config) =>
$.each self.options.davis, (key, val) ->
config[key] = val
true
# if extra davisRoutings were there, do it
self.davisInitializer?.call davis
@_tweakDavis()
@
_tweakDavis: ->
# tweak davis not to log erro if routeNotFound.
# because we treat it as sure thing.
warn = @davis.logger.warn
info = @davis.logger.info
@davis.logger.warn = (args...) =>
if (args[0].indexOf 'routeNotFound') isnt -1
args[0] = args[0].replace /routeNotFound/, 'unRouted'
info.apply @davis.logger, args
else
warn.apply @davis.logger, args
@
_findWhosePathMatches: (target, requestedPath, handleMulti) ->
# determine which configs to handle
if target is 'page'
if @pages and @pages.length
configs = @pages
else
return null
else if target is 'transRoutes'
if @transRoutes and @transRoutes.length
configs = @transRoutes
handleMulti = true
else
return null
matched = []
trimedPath = ns.trimGetVals requestedPath
# find from configs
$.each configs, (i, config) =>
# if ignoregetvals, trim path to eval
if @options.ignoregetvals or config.ignoregetvals
path = trimedPath
else
path = requestedPath
# handle regexp
if $.type(config.path) is 'regexp'
if config.path.test path
matched.push config
if handleMulti then return true
else
return true
# eval path
if config.path is path
matched.push config
if handleMulti then return true
true
# raise error if multi configs are detected
if not handleMulti and (matched.length > 1)
error "2 or more expr was matched about: #{requestedPath}"
$.each matched, (i, config) ->
error "dumps detected page configs - path:#{config.path}"
return false
if handleMulti
return matched
else
return matched[0] or null
fetch: (page) ->
# invoke all fetch events here.
# these are not done in Page class because I want these events
# to be fired in desired order
$.Deferred (defer) =>
page.trigger 'fetchstart', page
@trigger 'everyfetchstart', page
($.when page.fetch(), (wait @options.minwaittime)).then =>
page.trigger 'fetchsuccess', page
@trigger 'everyfetchsuccess', page
defer.resolve()
, (error) =>
if error.aborted
page.trigger 'fetchabort', page
@trigger 'everyfetchabort', page
else
page.trigger 'fetchfil', page
@trigger 'everyfetchfail', page
.promise()
stop: ->
@davis?.stop()
@
navigate: (path, method) ->
if @davis
request = new Davis.Request
method: method or 'get'
fullPath: path
title: ''
Davis.location.assign request
else
location.href = path
@
# fire all pageready events from @pages
firePageready: (skipEvery) ->
if @pages?.length
page = @_findWhosePathMatches 'page', location.pathname
if page then page.pageready?()
if skipEvery then return @
@trigger 'everypageready'
@
# fire all pageready events from @transRoutes
fireTransPageready: ->
if @transRoutes?.length
routings = @_findWhosePathMatches 'transRoutes', location.pathname
if not routings.length then return @
$.each routings, (i, routing) ->
routing.pageready?()
@
# initialization helpers
route: (pages) ->
@pages = pages
@
routeTransparents: (transRoutes) ->
@transRoutes = transRoutes
@
routeDavis: (initializer) ->
@davisInitializer = initializer
@
option: (options) ->
if not options then return @options
@options = $.extend true, {}, @options, options
# ============================================================
# globalify
$.LazyJaxDavisNs = ns
$.LazyJaxDavis = ns.Router
) jQuery, @, @document # encapsulate whole end