-
Notifications
You must be signed in to change notification settings - Fork 90
/
avalon2.js
1730 lines (1626 loc) · 62.5 KB
/
avalon2.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
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(DOC) {
var expose = Date.now()
var subscribers = "$" + expose
//http://stackoverflow.com/questions/3277182/how-to-get-the-global-object-in-javascript
var window = Function("return this")()
var otherRequire = window.require
var otherDefine = window.define
var stopRepeatAssign = false
var rword = /[^, ]+/g //切割字符串为一个个小块,以空格或豆号分开它们,结合replace实现字符串的forEach
var rcomplexType = /^(?:object|array)$/
var rsvg = /^\[object SVG\w*Element\]$/
var rwindow = /^\[object (Window|DOMWindow|global)\]$/
var oproto = Object.prototype
var ohasOwn = oproto.hasOwnProperty
var serialize = oproto.toString
var ap = Array.prototype
var aslice = ap.slice
var Registry = {} //将函数曝光到此对象上,方便访问器收集依赖
var head = DOC.head //HEAD元素
var root = DOC.documentElement
var hyperspace = DOC.createDocumentFragment()
var cinerator = DOC.createElement("div")
var class2type = {}
"Boolean Number String Function Array Date RegExp Object Error".replace(rword, function(name) {
class2type["[object " + name + "]"] = name.toLowerCase()
})
function noop() {
}
function log() {
if (avalon.config.debug) {
// http://stackoverflow.com/questions/8785624/how-to-safely-wrap-console-log
console.log.apply(console, arguments)
}
}
function oneObject(array, val) {
if (typeof array === "string") {
array = array.match(rword) || []
}
var result = {},
value = val !== void 0 ? val : 1
for (var i = 0, n = array.length; i < n; i++) {
result[array[i]] = value
}
return result
}
/*生成UUID http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript*/
function generateID() {
return "avalon" + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
}
/*********************************************************************
* avalon的静态方法定义区 *
**********************************************************************/
window.avalon = function(el) { //创建jQuery式的无new 实例化结构
return new avalon.init(el)
}
avalon.init = function(el) {
this[0] = this.element = el
}
avalon.fn = avalon.prototype = avalon.init.prototype
avalon.isFunction = isFunction
function isFunction(fn) {
return typeof fn === "function"
}
/*取得目标类型*/
avalon.type = function(obj) {
if (obj == null) {
return String(obj)
}
// 早期的webkit内核浏览器实现了已废弃的ecma262v4标准,可以将正则字面量当作函数使用,因此typeof在判定正则时会返回function
return typeof obj === "object" || typeof obj === "function" ?
class2type[serialize.call(obj)] || "object" :
typeof obj
}
avalon.isWindow = function(obj) {
return rwindow.test(serialize.call(obj))
}
/*判定是否是一个朴素的javascript对象(Object),不是DOM对象,不是BOM对象,不是自定义类的实例*/
avalon.isPlainObject = function(obj) {
return !!obj && typeof obj === "object" && Object.getPrototypeOf(obj) === oproto
}
avalon.mix = avalon.fn.mix = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false
// 如果第一个参数为布尔,判定是否深拷贝
if (typeof target === "boolean") {
deep = target
target = arguments[1] || {}
i++
}
//确保接受方为一个复杂的数据类型
if (typeof target !== "object" && avalon.type(target) !== "function") {
target = {}
}
//如果只有一个参数,那么新成员添加于mix所在的对象上
if (i === length) {
target = this
i--
}
for (; i < length; i++) {
//只处理非空参数
if ((options = arguments[i]) != null) {
for (name in options) {
src = target[name]
copy = options[name]
// 防止环引用
if (target === copy) {
continue
}
if (deep && copy && (avalon.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false
clone = src && Array.isArray(src) ? src : []
} else {
clone = src && avalon.isPlainObject(src) ? src : {}
}
target[name] = avalon.mix(deep, clone, copy)
} else if (copy !== void 0) {
target[name] = copy
}
}
}
}
return target
}
avalon.mix({
rword: rword,
subscribers: subscribers,
version: 1.36,
ui: {},
log: log,
noop: noop,
error: function(str, e) { //如果不用Error对象封装一下,str在控制台下可能会乱码
throw new (e || Error)(str)
},
oneObject: oneObject,
/* avalon.range(10)
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
avalon.range(1, 11)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
avalon.range(0, 30, 5)
=> [0, 5, 10, 15, 20, 25]
avalon.range(0, -10, -1)
=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
avalon.range(0)
=> []*/
range: function(start, end, step) { // 用于生成整数数组
step || (step = 1)
if (end == null) {
end = start || 0
start = 0
}
var index = -1,
length = Math.max(0, Math.ceil((end - start) / step)),
result = Array(length)
while (++index < length) {
result[index] = start
start += step
}
return result
},
slice: function(nodes, start, end) {
return aslice.call(nodes, start, end)
},
eventHooks: {},
bind: function(el, type, fn, phase) {
var hooks = avalon.eventHooks
var hook = hooks[type]
if (typeof hook === "object") {
type = hook.type
if (hook.deel) {
fn = hook.deel(el, fn)
}
}
el.addEventListener(type, fn, !!phase)
return fn
},
unbind: function(el, type, fn, phase) {
var hooks = avalon.eventHooks
var hook = hooks[type]
if (typeof hook === "object") {
type = hook.type
}
el.removeEventListener(type, fn || noop, !!phase)
},
css: function(node, name, value) {
if (node instanceof avalon) {
node = node[0]
}
var prop = /[_-]/.test(name) ? camelize(name) : name
name = avalon.cssName(prop) || prop
if (value === void 0 || typeof value === "boolean") { //获取样式
var fn = cssHooks[prop + ":get"] || cssHooks["@:get"]
if (name === "background") {
name = "backgroundColor"
}
var val = fn(node, name)
return value === true ? parseFloat(val) || 0 : val
} else if (value === "") { //请除样式
node.style[name] = ""
} else { //设置样式
if (value == null || value !== value) {
return
}
if (isFinite(value) && !avalon.cssNumber[prop]) {
value += "px"
}
fn = cssHooks[prop + ":set"] || cssHooks["@:set"]
fn(node, name, value)
}
},
each: function(obj, fn) {
if (obj) { //排除null, undefined
var i = 0
if (isArrayLike(obj)) {
for (var n = obj.length; i < n; i++) {
fn(i, obj[i])
}
} else {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
fn(i, obj[i])
}
}
}
}
},
getWidgetData: function(elem, prefix) {
var raw = avalon(elem).data()
var result = {}
for (var i in raw) {
if (i.indexOf(prefix) === 0) {
result[i.replace(prefix, "").replace(/\w/, function(a) {
return a.toLowerCase()
})] = raw[i]
}
}
return result
},
parseJSON: JSON.parse,
Array: {
/*只有当前数组不存在此元素时只添加它*/
ensure: function(target, item) {
if (target.indexOf(item) === -1) {
return target.push(item)
}
},
/*移除数组中指定位置的元素,返回布尔表示成功与否*/
removeAt: function(target, index) {
return !!target.splice(index, 1).length
},
/*移除数组中第一个匹配传参的那个元素,返回布尔表示成功与否*/
remove: function(target, item) {
var index = target.indexOf(item)
if (~index)
return avalon.Array.removeAt(target, index)
return false
}
}
})
/*判定是否类数组,如节点集合,纯数组,arguments与拥有非负整数的length属性的纯JS对象*/
function isArrayLike(obj) {
if (obj && typeof obj === "object") {
var n = obj.length,
str = serialize.call(obj)
if (/(Array|List|Collection|Map|Arguments)\]$/.test(str)) {
return true
} else if (str === "[object Object]" && (+n === n && !(n % 1) && n >= 0)) {
return true //由于ecma262v5能修改对象属性的enumerable,因此不能用propertyIsEnumerable来判定了
}
}
return false
}
/*视浏览器情况采用最快的异步回调*/
avalon.nextTick = function(callback) {
new Promise(function(resolve) {
resolve()
}).then(callback)
}
if (!root.contains) { //safari5+是把contains方法放在Element.prototype上而不是Node.prototype
Node.prototype.contains = function(arg) {
return !!(this.compareDocumentPosition(arg) & 16)
}
}
/*********************************************************************
* modelFactory *
**********************************************************************/
avalon.vmodels = {}
avalon.define = function(obj) {
var id = obj.$id
if (this.vmodels[id]) {
log("warning: " + id + " 已经存在于avalon.vmodels中")
}
return this.vmodels[id] = modelFactory(obj)
}
function isIndex(s) {//判定是非负整数,可以作为索引的
return +s === s >>> 0;
}
function observeCallback(changes) {
changes.forEach(function(change) {
if (change.type === "update") {
var object = change.object
var name = change.name
var events = object.$events
var array = events[name] || []
var newValue = object[name]
var newValue = "newValue" in change ? change.newValue : object[name]
var oldValue = change.oldValue
var target = "target" in change ? change.target : object
if (array.length) {
// var newValue = "value" in change ? change.value : object[name]
array.forEach(function(fn) {
fn.call(target, newValue, oldValue, name)
})
}
if (Array.isArray(object) && isIndex(name)) {
var array = events["[*]"]
if (array.length) {
var oldValue = change.oldValue
array.forEach(function(fn) {
fn.call(target, newValue, oldValue, name)
})
}
}
if (object.$parent) {
var notifier = Object.getNotifier(object.$parent)
if (Array.isArray(object) && isIndex(name)) {
notifier.notify({
object: object.$parent,
type: "update",
name: object.$surname + "[" + name + "]",
oldValue: oldValue,
newValue: newValue,
target: target
});
notifier.notify({
object: object.$parent,
type: "update",
name: object.$surname + "[*]",
oldValue: oldValue,
newValue: newValue,
target: target
});
} else {
// console.log(newValue)
notifier.notify({
object: object.$parent,
type: "update",
name: object.$surname + "." + name,
oldValue: oldValue,
newValue: newValue,
target: target
});
}
}
}
})
}
function isFunction(fn) {
return typeof fn === "function"
}
function isObject(obj) {
return obj && typeof obj === "object"
}
var $$skipArray = String("$id,$surname,$watch,$unwatch,$parent,$fire,$events,$model,$skipArray").match(rword)
function modelFactory($scope) {
if (Array.isArray($scope)) {
// var arr = $scope.concat()
// $scope.length = 0
var collection = Collection($scope)
// collection.pushArray(arr)
return collection
}
$scope.$events = []
for (var i in EventManager) {
$scope[i] = EventManager[i]
}
for (var i in $scope) {
if ($$skipArray.indexOf(i) === -1 && isObject($scope[i])) {
var child = modelFactory($scope[i])
child.$parent = $scope
child.$surname = i
$scope[i] = child
}
}
Object.observe($scope, observeCallback)
return $scope
}
function Collection($scope) {
$scope.$events = {}
for (var i in EventManager) {
$scope[i] = EventManager[i]
}
Object.observe($scope, observeCallback)
return $scope
}
var findNode = function(str) {
return DOC.querySelector(str)
}
var EventManager = {
$watch: function(type, callback) {
if (typeof callback === "function") {
console.log(type)
var callbacks = this.$events[type]
if (callbacks) {
callbacks.push(callback)
} else {
this.$events[type] = [callback]
}
} else { //重新开始监听此VM的第一重简单属性的变动
this.$events = this.$watch.backup
}
return this
},
$unwatch: function(type, callback) {
var n = arguments.length
if (n === 0) { //让此VM的所有$watch回调无效化
this.$watch.backup = this.$events
this.$events = {}
} else if (n === 1) {
this.$events[type] = []
} else {
var callbacks = this.$events[type] || []
var i = callbacks.length
while (~--i < 0) {
if (callbacks[i] === callback) {
return callbacks.splice(i, 1)
}
}
}
return this
},
$fire: function(type) {
var special
if (/^(\w+)!(\S+)$/.test(type)) {
special = RegExp.$1
type = RegExp.$2
}
var events = this.$events
var args = aslice.call(arguments, 1)
var detail = [type].concat(args)
if (special === "all") {
for (var i in avalon.vmodels) {
var v = avalon.vmodels[i]
if (v !== this) {
v.$fire.apply(v, detail)
}
}
} else if (special === "up" || special === "down") {
var element = events.expr && findNode(events.expr)
if (!element)
return
for (var i in avalon.vmodels) {
var v = avalon.vmodels[i]
if (v !== this) {
if (v.$events.expr) {
var node = findNode(v.$events.expr)
if (!node) {
continue
}
var ok = special === "down" ? element.contains(node) : //向下捕获
node.contains(element) //向上冒泡
if (ok) {
node._avalon = v //符合条件的加一个标识
}
}
}
}
var nodes = DOC.getElementsByTagName("*") //实现节点排序
var alls = []
Array.prototype.forEach.call(nodes, function(el) {
if (el._avalon) {
alls.push(el._avalon)
el._avalon = ""
el.removeAttribute("_avalon")
}
})
if (special === "up") {
alls.reverse()
}
for (var i = 0, el; el = alls[i++]; ) {
if (el.$fire.apply(el, detail) === false) {
break
}
}
} else {
var callbacks = events[type] || []
var all = events.$all || []
for (var i = 0, callback; callback = callbacks[i++]; ) {
if (isFunction(callback))
callback.apply(this, args)
}
for (var i = 0, callback; callback = all[i++]; ) {
if (isFunction(callback))
callback.apply(this, arguments)
}
}
}
}
/*********************************************************************
* 配置模块 *
**********************************************************************/
function kernel(settings) {
for (var p in settings) {
if (!ohasOwn.call(settings, p))
continue
var val = settings[p]
if (typeof kernel.plugins[p] === "function") {
kernel.plugins[p](val)
} else if (typeof kernel[p] === "object") {
avalon.mix(kernel[p], val)
} else {
kernel[p] = val
}
}
return this
}
var openTag, closeTag, rexpr, rexprg, rbind, rregexp = /[-.*+?^${}()|[\]\/\\]/g
/*将字符串安全格式化为正则表达式的源码 http://stevenlevithan.com/regex/xregexp/*/
function escapeRegExp(target) {
return (target + "").replace(rregexp, "\\$&")
}
var innerRequire = noop
var plugins = {
loader: function(builtin) {
window.define = builtin ? innerRequire.define : otherDefine
window.require = builtin ? innerRequire : otherRequire
},
interpolate: function(array) {
openTag = array[0]
closeTag = array[1]
if (openTag === closeTag) {
avalon.error("openTag!==closeTag", SyntaxError)
} else if (array + "" === "<!--,-->") {
kernel.commentInterpolate = true
} else {
var test = openTag + "test" + closeTag
cinerator.innerHTML = test
if (cinerator.innerHTML !== test && cinerator.innerHTML.indexOf("<") >= 0) {
avalon.error("此定界符不合法", SyntaxError)
}
cinerator.innerHTML = ""
}
var o = escapeRegExp(openTag),
c = escapeRegExp(closeTag)
rexpr = new RegExp(o + "(.*?)" + c)
rexprg = new RegExp(o + "(.*?)" + c, "g")
rbind = new RegExp(o + ".*?" + c + "|\\sms-")
}
}
kernel.debug = true
kernel.plugins = plugins
kernel.plugins['interpolate'](["{{", "}}"])
kernel.paths = {}
kernel.shim = {}
kernel.maxRepeatSize = 100
avalon.config = kernel
/*********************************************************************
* DOM API的高级封装 *
**********************************************************************/
/*转换为连字符线风格*/
function hyphen(target) {
return target.replace(/([a-z\d])([A-Z]+)/g, "$1-$2").toLowerCase()
}
/*转换为驼峰风格*/
function camelize(target) {
if (target.indexOf("-") < 0 && target.indexOf("_") < 0) {
return target //提前判断,提高getStyle等的效率
}
return target.replace(/[-_][^-_]/g, function(match) {
return match.charAt(1).toUpperCase()
})
}
"add,remove".replace(rword, function(method) {
avalon.fn[method + "Class"] = function(cls) {
var el = this[0]
//https://developer.mozilla.org/zh-CN/docs/Mozilla/Firefox/Releases/26
if (cls && typeof cls === "string" && el && el.nodeType === 1) {
cls.replace(/\S+/g, function(c) {
el.classList[method](c)
})
}
return this
}
})
avalon.fn.mix({
hasClass: function(cls) {
var el = this[0] || {} //IE10+, chrome8+, firefox3.6+, safari5.1+,opera11.5+支持classList,chrome24+,firefox26+支持classList2.0
return el.nodeType === 1 && el.classList.contains(cls)
},
toggleClass: function(value, stateVal) {
var node = this[0]
if (node && node.nodeType === 1) {
var state = stateVal
var i = 0
var classNames = value.split(/\s+/)
var isBool = typeof stateVal === "boolean"
var classList = node.classList, className
while ((className = classNames[i++])) {
state = isBool ? state : !classList.contains(className)
classList[state ? "add" : "remove"](className)
}
}
return this
},
attr: function(name, value) {
if (arguments.length === 2) {
this[0].setAttribute(name, value)
return this
} else {
return this[0].getAttribute(name)
}
},
data: function(name, val) {
var dataset = this[0].dataset
switch (arguments.length) {
case 2:
dataset[name] = val
return this
case 1:
val = dataset[name]
return parseData(val)
case 0:
var ret = {}
for (var name in dataset) {
ret[name] = parseData(dataset[name])
}
return ret
}
},
removeData: function(name) {
name = "data-" + hyphen(name)
this[0].removeAttribute(name)
return this
},
css: function(name, value) {
if (avalon.isPlainObject(name)) {
for (var i in name) {
avalon.css(this, i, name[i])
}
} else {
var ret = avalon.css(this, name, value)
}
return ret !== void 0 ? ret : this
},
position: function() {
var offsetParent, offset,
elem = this[0],
parentOffset = {
top: 0,
left: 0
};
if (!elem) {
return
}
if (this.css("position") === "fixed") {
offset = elem.getBoundingClientRect()
} else {
offsetParent = this.offsetParent() //得到真正的offsetParent
offset = this.offset() // 得到正确的offsetParent
if (offsetParent[0].tagName !== "HTML") {
parentOffset = offsetParent.offset()
}
parentOffset.top += avalon.css(offsetParent[0], "borderTopWidth", true)
parentOffset.left += avalon.css(offsetParent[0], "borderLeftWidth", true)
}
return {
top: offset.top - parentOffset.top - avalon.css(elem, "marginTop", true),
left: offset.left - parentOffset.left - avalon.css(elem, "marginLeft", true)
}
},
offsetParent: function() {
var offsetParent = this[0].offsetParent || root
while (offsetParent && (offsetParent.tagName !== "HTML") && avalon.css(offsetParent, "position") === "static") {
offsetParent = offsetParent.offsetParent
}
return avalon(offsetParent || root)
},
bind: function(type, fn, phase) {
if (this[0]) { //此方法不会链
return avalon.bind(this[0], type, fn, phase)
}
},
unbind: function(type, fn, phase) {
if (this[0]) {
avalon.unbind(this[0], type, fn, phase)
}
return this
},
val: function(value) {
var node = this[0]
if (node && node.nodeType === 1) {
var get = arguments.length === 0
var access = get ? ":get" : ":set"
var fn = valHooks[getValType(node) + access]
if (fn) {
var val = fn(node, value)
} else if (get) {
return (node.value || "").replace(/\r/g, "")
} else {
node.value = value
}
}
return get ? val : this
}
})
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/
function parseData(data) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null : +data + "" === data ? +data : rbrace.test(data) ? JSON.parse(data) : data
} catch (e) {
}
return data
}
avalon.each({
scrollLeft: "pageXOffset",
scrollTop: "pageYOffset"
}, function(method, prop) {
avalon.fn[method] = function(val) {
var node = this[0] || {}, win = getWindow(node),
top = method === "scrollTop"
if (!arguments.length) {
return win ? win[prop] : node[method]
} else {
if (win) {
win.scrollTo(!top ? val : avalon(win).scrollLeft(), top ? val : avalon(win).scrollTop())
} else {
node[method] = val
}
}
}
})
function getWindow(node) {
return node.window && node.document ? node : node.nodeType === 9 ? node.defaultView : false
}
//=============================css相关==================================
var cssHooks = avalon.cssHooks = {}
var prefixes = ["", "-webkit-", "-o-", "-moz-", "-ms-"]
var cssMap = {
"float": "cssFloat"
}
avalon.cssNumber = oneObject("columnCount,order,fillOpacity,fontWeight,lineHeight,opacity,orphans,widows,zIndex,zoom")
avalon.cssName = function(name, host, camelCase) {
if (cssMap[name]) {
return cssMap[name]
}
host = host || root.style
for (var i = 0, n = prefixes.length; i < n; i++) {
camelCase = camelize(prefixes[i] + name)
if (camelCase in host) {
return (cssMap[name] = camelCase)
}
}
return null
}
cssHooks["@:set"] = function(node, name, value) {
node.style[name] = value
}
cssHooks["@:get"] = function(node, name) {
if (!node || !node.style) {
throw new Error("getComputedStyle要求传入一个节点 " + node)
}
var ret, computed = getComputedStyle(node, null)
if (computed) {
ret = computed[ name ]
if (ret === "") {
ret = node.style[name] //其他浏览器需要我们手动取内联样式
}
}
return ret
}
cssHooks["opacity:get"] = function(node) {
var ret = cssHooks["@:get"](node, "opacity")
return ret === "" ? "1" : ret
}
"top,left".replace(rword, function(name) {
cssHooks[name + ":get"] = function(node) {
var computed = cssHooks["@:get"](node, name)
return /px$/.test(computed) ? computed :
avalon(node).position()[name] + "px"
}
})
var cssShow = {
position: "absolute",
visibility: "hidden",
display: "block"
}
var rdisplayswap = /^(none|table(?!-c[ea]).+)/
function showHidden(node, array) {
//http://www.cnblogs.com/rubylouvre/archive/2012/10/27/2742529.html
if (node.offsetWidth === 0) {
var styles = getComputedStyle(node, null)
if (rdisplayswap.test(styles["display"])) {
var obj = {
node: node
}
for (var name in cssShow) {
obj[name] = styles[name]
node.style[name] = cssShow[name]
}
array.push(obj)
}
var parent = node.parentNode
if (parent && parent.nodeType == 1) {
showHidden(parent, array)
}
}
}
"Width,Height".replace(rword, function(name) {//fix 481
var method = name.toLowerCase(),
clientProp = "client" + name,
scrollProp = "scroll" + name,
offsetProp = "offset" + name
cssHooks[method + ":get"] = function(node, which, override) {
var boxSizing = -4
if (typeof override === "number") {
boxSizing = override
}
which = name === "Width" ? ["Left", "Right"] : ["Top", "Bottom"]
var ret = node[offsetProp] // border-box 0
if (boxSizing === 2) { // margin-box 2
return ret + avalon.css(node, "margin" + which[0], true) + avalon.css(node, "margin" + which[1], true)
}
if (boxSizing < 0) { // padding-box -2
ret = ret - avalon.css(node, "border" + which[0] + "Width", true) - avalon.css(node, "border" + which[1] + "Width", true)
}
if (boxSizing === -4) { // content-box -4
ret = ret - avalon.css(node, "padding" + which[0], true) - avalon.css(node, "padding" + which[1], true)
}
return ret
}
cssHooks[method + "&get"] = function(node) {
var hidden = [];
showHidden(node, hidden);
var val = cssHooks[method + ":get"](node)
for (var i = 0, obj; obj = hidden[i++]; ) {
node = obj.node
for (var n in obj) {
if (typeof obj[n] === "string") {
node.style[n] = obj[n]
}
}
}
return val;
}
avalon.fn[method] = function(value) { //会忽视其display
var node = this[0]
if (arguments.length === 0) {
if (node.setTimeout) { //取得窗口尺寸,IE9后可以用node.innerWidth /innerHeight代替
return node["inner" + name]
}
if (node.nodeType === 9) { //取得页面尺寸
var doc = node.documentElement
//FF chrome html.scrollHeight< body.scrollHeight
//IE 标准模式 : html.scrollHeight> body.scrollHeight
//IE 怪异模式 : html.scrollHeight 最大等于可视窗口多一点?
return Math.max(node.body[scrollProp], doc[scrollProp], node.body[offsetProp], doc[offsetProp], doc[clientProp])
}
return cssHooks[method + "&get"](node)
} else {
return this.css(method, value)
}
}
avalon.fn["inner" + name] = function() {
return cssHooks[method + ":get"](this[0], void 0, -2)
}
avalon.fn["outer" + name] = function(includeMargin) {
return cssHooks[method + ":get"](this[0], void 0, includeMargin === true ? 2 : 0)
}
})
avalon.fn.offset = function() { //取得距离页面左右角的坐标
var node = this[0], box = {
left: 0,
top: 0
}
if (!node || !node.tagName || !node.ownerDocument) {
return box
}
var doc = node.ownerDocument,
root = doc.documentElement,
win = doc.defaultView
if (!root.contains(node)) {
return box
}
if (node.getBoundingClientRect !== void 0) {
box = node.getBoundingClientRect()
}
return {
top: box.top + win.pageYOffset - root.clientTop,
left: box.left + win.pageXOffset - root.clientLeft
}
}
//=============================val相关=======================
function getValType(el) {
var ret = el.tagName.toLowerCase()
return ret === "input" && /checkbox|radio/.test(el.type) ? "checked" : ret
}
var valHooks = {
"select:get": function(node, value) {
var one = node.multiple
var values = one ? null : []
for (var i = 0, option; option = node.options[i++]; ) {
if (option.selected && !option.disabled) {
value = option.value
if (one) {
return value
}
//收集所有selected值组成数组返回
values.push(value)
}
}
return values
},
"select:set": function(node, values, optionSet) {
values = [].concat(values) //强制转换为数组
for (var i = 0, el; el = node.options[i++]; ) {
if ((el.selected = values.indexOf(el.value) >= 0)) {
optionSet = true
}
}
if (!optionSet) {
node.selectedIndex = -1
}
}
}
/************************************************************************
* HTML处理(parseHTML, innerHTML, clearHTML) *
****************************************************************************/
!function(t) {
var rtagName = /<([\w:]+)/
var rxhtml = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig
var tagHooks = {
g: [1, '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">', '</svg>'],
//IE6-8在用innerHTML生成节点时,不能直接创建no-scope元素与HTML5的新标签
_default: [0, "", ""] //div可以不用闭合
}
String("circle,defs,ellipse,image,line,path,polygon,polyline,rect,symbol,text,use").replace(rword, function(tag) {
tagHooks[tag] = tagHooks.g //处理SVG
})
avalon.parseHTML = function(html) {
html = html.replace(rxhtml, "<$1></$2>").trim()
var tag = (rtagName.exec(html) || ["", ""])[1].toLowerCase()
var wrap = tagHooks[tag] || tagHooks._default
t.innerHTML = wrap[1] + html + wrap[2]
var wrapper = t.content
if (wrap[0]) {
var fragment = wrapper.cloneNode(false)
wrapper = wrapper.lastChild
while (tag = wrapper.firstChild) { // 将wrapper上的节点转移到文档碎片上!
fragment.appendChild(tag)