-
Notifications
You must be signed in to change notification settings - Fork 69
/
ml.js
4321 lines (3743 loc) · 137 KB
/
ml.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(win, lib) {
var doc = win.document;
var docEl = doc.documentElement;
var metaEl = doc.querySelector('meta[name="viewport"]');
var flexibleEl = doc.querySelector('meta[name="flexible"]');
var dpr = 0;
var scale = 0;
var tid;
var flexible = lib.flexible || (lib.flexible = {});
if (metaEl) {
console.warn('将根据已有的meta标签来设置缩放比例');
var match = metaEl.getAttribute('content').match(/initial\-scale=([\d\.]+)/);
if (match) {
scale = parseFloat(match[1]);
dpr = parseInt(1 / scale);
}
} else if (flexibleEl) {
var content = flexibleEl.getAttribute('content');
if (content) {
var initialDpr = content.match(/initial\-dpr=([\d\.]+)/);
var maximumDpr = content.match(/maximum\-dpr=([\d\.]+)/);
if (initialDpr) {
dpr = parseFloat(initialDpr[1]);
scale = parseFloat((1 / dpr).toFixed(2));
}
if (maximumDpr) {
dpr = parseFloat(maximumDpr[1]);
scale = parseFloat((1 / dpr).toFixed(2));
}
}
}
if (!dpr && !scale) {
var isAndroid = win.navigator.appVersion.match(/android/gi);
var isIPhone = win.navigator.appVersion.match(/iphone/gi);
var devicePixelRatio = win.devicePixelRatio;
if (isIPhone) {
// iOS下,对于2和3的屏,用2倍的方案,其余的用1倍方案
if (devicePixelRatio >= 3 && (!dpr || dpr >= 3)) {
dpr = 3;
} else if (devicePixelRatio >= 2 && (!dpr || dpr >= 2)){
dpr = 2;
} else {
dpr = 1;
}
} else {
// 其他设备下,仍旧使用1倍的方案
dpr = 1;
}
scale = 1 / dpr;
}
docEl.setAttribute('data-dpr', dpr);
if (!metaEl) {
metaEl = doc.createElement('meta');
metaEl.setAttribute('name', 'viewport');
metaEl.setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no');
if (docEl.firstElementChild) {
docEl.firstElementChild.appendChild(metaEl);
} else {
var wrap = doc.createElement('div');
wrap.appendChild(metaEl);
doc.write(wrap.innerHTML);
}
}
function refreshRem(){
var width = docEl.getBoundingClientRect().width;
if (width / dpr > 540) {
width = 540 * dpr;
}
var rem = width / 10;
docEl.style.fontSize = rem + 'px';
flexible.rem = win.rem = rem;
}
win.addEventListener('resize', function() {
clearTimeout(tid);
tid = setTimeout(refreshRem, 300);
}, false);
win.addEventListener('pageshow', function(e) {
if (e.persisted) {
clearTimeout(tid);
tid = setTimeout(refreshRem, 300);
}
}, false);
if (doc.readyState === 'complete') {
doc.body.style.fontSize = 12 * dpr + 'px';
} else {
doc.addEventListener('DOMContentLoaded', function(e) {
doc.body.style.fontSize = 12 * dpr + 'px';
}, false);
}
refreshRem();
flexible.dpr = win.dpr = dpr;
flexible.refreshRem = refreshRem;
flexible.rem2px = function(d) {
var val = parseFloat(d) * this.rem;
if (typeof d === 'string' && d.match(/rem$/)) {
val += 'px';
}
return val;
}
flexible.px2rem = function(d) {
var val = parseFloat(d) / this.rem;
if (typeof d === 'string' && d.match(/px$/)) {
val += 'rem';
}
return val;
}
})(window, window['lib'] || (window['lib'] = {}));
// Copyright (C) 2013:
// Alex Russell <[email protected]>
// Yehuda Katz
//
// Use of this source code is governed by
// http://www.apache.org/licenses/LICENSE-2.0
;(function(browserGlobal, lib) {
//
// Async Utilities
//
// Borrowed from RSVP.js
var async;
var MutationObserver = browserGlobal.MutationObserver ||
browserGlobal.WebKitMutationObserver;
var Promise;
if (MutationObserver) {
var queue = [];
var observer = new MutationObserver(function() {
var toProcess = queue.slice();
queue = [];
toProcess.forEach(function(tuple) {
tuple[0].call(tuple[1]);
});
});
var element = document.createElement('div');
observer.observe(element, {
attributes: true
});
// Chrome Memory Leak: https://bugs.webkit.org/show_bug.cgi?id=93661
window.addEventListener('unload', function() {
observer.disconnect();
observer = null;
});
async = function(callback, binding) {
queue.push([callback, binding]);
element.setAttribute('drainQueue', 'drainQueue');
};
} else {
async = function(callback, binding) {
setTimeout(function() {
callback.call(binding);
}, 1);
};
}
//
// Object Model Utilities
//
// defineProperties utilities
var _readOnlyProperty = function(v) {
return {
enumerable: true,
configurable: false,
get: v
};
};
var _method = function(v, e, c, w) {
return {
enumerable: !! (e || 0),
configurable: !! (c || 1),
writable: !! (w || 1),
value: v || function() {}
};
};
var _pseudoPrivate = function(v) {
return _method(v, 0, 1, 0);
};
var _public = function(v) {
return _method(v, 1);
};
//
// Promises Utilities
//
var isThenable = function(any) {
if (any === undefined)
return false;
try {
var f = any.then;
if (typeof f == "function") {
return true;
}
} catch (e) { /*squelch*/ }
return false;
};
var AlreadyResolved = function(name) {
Error.call(this, name);
};
AlreadyResolved.prototype = Object.create(Error.prototype);
var Backlog = function() {
var bl = [];
bl.pump = function(value) {
async(function() {
var l = bl.length;
var x = 0;
while (x < l) {
x++;
bl.shift()(value);
}
});
};
return bl;
};
//
// Resolver Constuctor
//
var Resolver = function(future,
fulfillCallbacks,
rejectCallbacks,
setValue,
setError,
setState) {
var isResolved = false;
var resolver = this;
var fulfill = function(value) {
// console.log("queueing fulfill with:", value);
async(function() {
setState("fulfilled");
setValue(value);
// console.log("fulfilling with:", value);
fulfillCallbacks.pump(value);
});
};
var reject = function(reason) {
// console.log("queuing reject with:", reason);
async(function() {
setState("rejected");
setError(reason);
// console.log("rejecting with:", reason);
rejectCallbacks.pump(reason);
});
};
var resolve = function(value) {
if (isThenable(value)) {
value.then(resolve, reject);
return;
}
fulfill(value);
};
var ifNotResolved = function(func, name) {
return function(value) {
if (!isResolved) {
isResolved = true;
func(value);
} else {
if (typeof console != "undefined") {
console.error("Cannot resolve a Promise multiple times.");
}
}
};
};
// Indirectly resolves the Promise, chaining any passed Promise's resolution
this.resolve = ifNotResolved(resolve, "resolve");
// Directly fulfills the future, no matter what value's type is
this.fulfill = ifNotResolved(fulfill, "fulfill");
// Rejects the future
this.reject = ifNotResolved(reject, "reject");
this.cancel = function() {
resolver.reject(new Error("Cancel"));
};
this.timeout = function() {
resolver.reject(new Error("Timeout"));
};
setState("pending");
};
//
// Promise Constuctor
//
var Promise = function(init) {
var fulfillCallbacks = new Backlog();
var rejectCallbacks = new Backlog();
var value;
var error;
var state = "pending";
Object.defineProperties(this, {
_addAcceptCallback: _pseudoPrivate(
function(cb) {
// console.log("adding fulfill callback:", cb);
fulfillCallbacks.push(cb);
if (state == "fulfilled") {
fulfillCallbacks.pump(value);
}
}
),
_addRejectCallback: _pseudoPrivate(
function(cb) {
// console.log("adding reject callback:", cb);
rejectCallbacks.push(cb);
if (state == "rejected") {
rejectCallbacks.pump(error);
}
}
)
});
var r = new Resolver(this,
fulfillCallbacks, rejectCallbacks,
function(v) {
value = v;
},
function(e) {
error = e;
},
function(s) {
state = s;
})
try {
if (init) {
init(r);
}
} catch (e) {
r.reject(e);
console.log(e);
}
};
//
// Consructor
//
var isCallback = function(any) {
return (typeof any == "function");
};
// Used in .then()
var wrap = function(callback, resolver, disposition) {
if (!isCallback(callback)) {
// If we don't get a callback, we want to forward whatever resolution we get
return resolver[disposition].bind(resolver);
}
return function() {
try {
var r = callback.apply(null, arguments);
resolver.resolve(r);
} catch (e) {
// Exceptions reject the resolver
resolver.reject(e);
console.log(e);
}
};
};
var addCallbacks = function(onfulfill, onreject, scope) {
if (isCallback(onfulfill)) {
scope._addAcceptCallback(onfulfill);
}
if (isCallback(onreject)) {
scope._addRejectCallback(onreject);
}
return scope;
};
//
// Prototype properties
//
Promise.prototype = Object.create(null, {
"then": _public(function(onfulfill, onreject) {
// The logic here is:
// We return a new Promise whose resolution merges with the return from
// onfulfill() or onerror(). If onfulfill() returns a Promise, we forward
// the resolution of that future to the resolution of the returned
// Promise.
var f = this;
return new Promise(function(r) {
addCallbacks(wrap(onfulfill, r, "resolve"),
wrap(onreject, r, "reject"), f);
});
}),
"catch": _public(function(onreject) {
var f = this;
return new Promise(function(r) {
addCallbacks(null, wrap(onreject, r, "reject"), f);
});
})
});
//
// Statics
//
Promise.isThenable = isThenable;
var toPromiseList = function(list) {
return Array.prototype.slice.call(list).map(Promise.resolve);
};
Promise.any = function( /*...futuresOrValues*/ ) {
var futures = toPromiseList(arguments);
return new Promise(function(r) {
if (!futures.length) {
r.reject("No futures passed to Promise.any()");
} else {
var resolved = false;
var firstSuccess = function(value) {
if (resolved) {
return;
}
resolved = true;
r.resolve(value);
};
var firstFailure = function(reason) {
if (resolved) {
return;
}
resolved = true;
r.reject(reason);
};
futures.forEach(function(f, idx) {
f.then(firstSuccess, firstFailure);
});
}
});
};
Promise.every = function( /*...futuresOrValues*/ ) {
var futures = toPromiseList(arguments);
return new Promise(function(r) {
if (!futures.length) {
r.reject("No futures passed to Promise.every()");
} else {
var values = new Array(futures.length);
var count = 0;
var accumulate = function(idx, v) {
count++;
values[idx] = v;
if (count == futures.length) {
r.resolve(values);
}
};
futures.forEach(function(f, idx) {
f.then(accumulate.bind(null, idx), r.reject);
});
}
});
};
Promise.some = function() {
var futures = toPromiseList(arguments);
return new Promise(function(r) {
if (!futures.length) {
r.reject("No futures passed to Promise.some()");
} else {
var count = 0;
var accumulateFailures = function(e) {
count++;
if (count == futures.length) {
r.reject();
}
};
futures.forEach(function(f, idx) {
f.then(r.resolve, accumulateFailures);
});
}
});
};
Promise.fulfill = function(value) {
return new Promise(function(r) {
r.fulfill(value);
});
};
Promise.resolve = function(value) {
return new Promise(function(r) {
r.resolve(value);
});
};
Promise.reject = function(reason) {
return new Promise(function(r) {
r.reject(reason);
});
};
Promise.deferred = function() {
var resolver;
var promise = new Promise(function(r) {
resolver = r;
});
var deferred = {};
['resolve', 'reject', 'fulfill', 'timeout', 'cancel'].forEach(function(key){
deferred[key] = function() {
resolver[key].apply(key, arguments);
}
});
deferred.promise = function(obj) {
if (obj) {
['then', 'catch'].forEach(function(key) {
obj[key] = function() {
return promise[key].apply(promise, arguments);
}
})
return obj;
} else {
return promise;
}
}
return deferred;
}
// 兼容Zepto和jQuery的Deferred
if (window['$'] && !window['$'].Deferred) {
window['$'].Deferred = function() {
var deferred = Promise.deferred();
deferred.resolveWith = function(context, data) {
this.resolve.apply(context, data);
}
deferred.rejectWith = function(context, data) {
this.reject.apply(context, data);
}
return deferred;
}
}
lib.promise = Promise;
})(window, window['lib'] || (window['lib'] = {}));
;(function(win, lib, undef){
var document = win.document;
var location = win.location;
var history = win.history;
var ua = win.navigator.userAgent;
var Firefox = !!ua.match(/Firefox/i);
var IEMobile = !!ua.match(/IEMobile/i);
!history.state && history.replaceState && history.replaceState(true, null); // 先重置一次state,可以通过history.state来判断手机是否正常支持
function Params(args) {
args = args || '';
var that = this;
var params = {};
if (args && typeof args === 'string') {
var s1 = args.split('&');
for (var i = 0; i < s1.length; i++) {
var s2 = s1[i].split('=');
params[decodeURIComponent(s2[0])] = decodeURIComponent(s2[1]);
}
} else if (typeof args === 'object') {
for (var key in args) {
params[key] = args[key];
}
}
for (var key in params) {
(function(prop){
Object.defineProperty(that, prop, {
get: function() {
return params[prop];
},
set: function(v) {
params[prop] = v;
},
enumerable: true
});
})(key);
}
this.toString = function() {
return Object.keys(params).sort().map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
}
}
var requestAnimationFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
function(cb) {
setTimeout(cb, 1 /60);
};
function Navigation(){
var that = this;
var executerQueue = [];
var useHistoryState = !!history.state;
var historyStorage = {
//stack: []
};
var action = 'initial';
function dispatchAnchorEvent(href) {
var a = document.createElement('a');
a.href = href;
a.style.cssText = 'display:none;';
document.body.appendChild(a);
var e;
if (win['MouseEvent']) {
e = new MouseEvent('click', {
view: window,
bubbles: false,
cancelable: false
});
} else {
e = document.createEvent('HTMLEvents');
e.initEvent('click', false, false);
}
if (e) {
a.dispatchEvent(e);
} else {
location.href = href;
}
}
function dispatchWindowEvent(name, extra) {
var ev = document.createEvent('HTMLEvents');
ev.initEvent(name, false, false);
if (extra) {
for (var key in extra) {
ev[key] = extra[key];
}
}
window.dispatchEvent(ev);
}
function PushExecuter(state, step){
this.exec = function(){
//historyStorage.stack.push(state);
dispatchWindowEvent('navigation:push');
}
}
function PopExecuter(state, step){
this.exec = function(){
// for (var i = 0; i > step; i--) {
// historyStorage.stack.pop();
// }
dispatchWindowEvent('navigation:pop');
}
}
function ReplaceExecuter(state){
this.exec = function(){
// historyStorage.stack.pop();
// historyStorage.stack.push(state);
dispatchWindowEvent('navigation:replace');
}
}
executerQueue.exec = function() {
if (executerQueue.length) {
executerQueue.shift().exec();
}
}
function isSameState(state1, state2) {
return state1.name === state2.name && state1.args.toString() === state2.args.toString();
}
this.push = function(path, args){
var state = {
name: path,
args: new Params(args),
id: historyStorage.state.id + 1
};
if (isSameState(state, historyStorage.state)) return;
action = 'push';
var search = state.args.toString();
if (useHistoryState) {
var hash = '#' + state.name + (search?'?' + search:'');
history.pushState({
name: state.name,
args: search,
id: state.id
}, null, hash);
dispatchWindowEvent('pushstate');
} else {
var hash = '#' + state.name + '[' + state.id + ']' + (search?'?' + search:'');
dispatchAnchorEvent(hash);
}
}
this.pop = function(){
if (historyStorage.state.id > 1) {
action = 'pop';
history.back();
}
}
this.replace = function(path, args) {
var state = {
name: path,
args: new Params(args),
id: historyStorage.state.id
};
if (isSameState(state, historyStorage.state)) return;
action = 'replace';
var search = state.args.toString();
if (useHistoryState) {
var hash = '#' + state.name + (search?'?' + search:'');
history.replaceState({
name: state.name,
args: search,
id: state.id
}, null, hash);
dispatchWindowEvent('replacestate');
} else {
var hash = '#' + state.name + '[' + state.id + ']' + (search?'?' + search:'');
dispatchAnchorEvent(hash);
}
}
var isStart = false;
this.start = function(options) {
if (isStart) return;
isStart = true;
var defaultPath = options.defaultPath || '';
var defaultArgs = options.defaultArgs || '';
useHistoryState &= !!options.useHistoryState;
Object.defineProperty(this, 'useHistoryState', {
get: function() {
return useHistoryState;
}
});
Object.defineProperty(this, 'action', {
get: function() {
return action;
}
});
Object.defineProperty(this, 'state', {
get: function() {
return {
id: historyStorage.state.id,
name: historyStorage.state.name,
args: historyStorage.state.args
};
}
});
function getState() {
var state;
if (useHistoryState && history.state != null && history.state !== true) {
state = {
id: history.state.id,
name: history.state.name,
args: new Params(history.state.args)
}
} else {
var hash = location.hash;
var hashMatched = hash.match(/#([^\[\]\?]+)(?:\[(\d+)\])?(?:\?(.*))?/) || ['', defaultPath, 1, defaultArgs];
state = {
name: hashMatched[1],
id: parseInt(hashMatched[2] || 1),
args: new Params(hashMatched[3] || '')
}
}
return state;
}
function stateChange(e) {
var state = getState();
var oldstate = historyStorage.state;
historyStorage.state = state;
if(state.id < oldstate.id) {
action = 'pop';
executerQueue.push(new PopExecuter(state, state.id - oldstate.id));
} else if (state.id === oldstate.id) {
if (that.action === 'replace') {
executerQueue.push(new ReplaceExecuter(state));
} else {
// 手动改hash的问题
console.error('请勿用location.hash或location.href来改变hash值');
}
} else {
action = 'push';
executerQueue.push(new PushExecuter(state, state.id - oldstate.id));
}
executerQueue.exec();
}
var state = getState();
if (useHistoryState) {
win.addEventListener('pushstate', stateChange, false);
win.addEventListener('popstate', stateChange, false);
win.addEventListener('replacestate', stateChange, false);
} else {
win.addEventListener('hashchange', stateChange, false);
}
historyStorage.state = state;
executerQueue.push(new PushExecuter(state));
executerQueue.exec();
}
}
lib.navigation = Navigation;
})(window, window['lib'] || (window['lib'] = {}));
;(function(win, lib, undef) {
'use strict';
var doc = win.document,
docEl = doc.documentElement,
slice = Array.prototype.slice,
gestures = {}, lastTap = null
;
/**
* 找到两个结点共同的最小根结点
* 如果跟结点不存在,则返回null
*
* @param {Element} el1 第一个结点
* @param {Element} el2 第二个结点
* @return {Element} 根结点
*/
function getCommonAncestor(el1, el2) {
var el = el1;
while (el) {
if (el.contains(el2) || el == el2) {
return el;
}
el = el.parentNode;
}
return null;
}
/**
* 触发一个事件
*
* @param {Element} element 目标结点
* @param {string} type 事件类型
* @param {object} extra 对事件对象的扩展
*/
function fireEvent(element, type, extra) {
var event = doc.createEvent('HTMLEvents');
event.initEvent(type, true, true);
if(typeof extra === 'object') {
for(var p in extra) {
event[p] = extra[p];
}
}
element.dispatchEvent(event);
}
/**
* 计算变换效果
* 假设坐标系上有4个点ABCD
* > 旋转:从AB旋转到CD的角度
* > 缩放:从AB长度变换到CD长度的比例
* > 位移:从A点位移到C点的横纵位移
*
* @param {number} x1 上述第1个点的横坐标
* @param {number} y1 上述第1个点的纵坐标
* @param {number} x2 上述第2个点的横坐标
* @param {number} y2 上述第2个点的纵坐标
* @param {number} x3 上述第3个点的横坐标
* @param {number} y3 上述第3个点的纵坐标
* @param {number} x4 上述第4个点的横坐标
* @param {number} y4 上述第4个点的纵坐标
* @return {object} 变换效果,形如{rotate, scale, translate[2], matrix[3][3]}
*/
function calc(x1, y1, x2, y2, x3, y3, x4, y4) {
var rotate = Math.atan2(y4 - y3, x4 - x3) - Math.atan2(y2 - y1, x2 - x1),
scale = Math.sqrt((Math.pow(y4 - y3, 2) + Math.pow(x4 - x3, 2)) / (Math.pow(y2 - y1, 2) + Math.pow(x2 - x1, 2))),
translate = [x3 - scale * x1 * Math.cos(rotate) + scale * y1 * Math.sin(rotate), y3 - scale * y1 * Math.cos(rotate) - scale * x1 * Math.sin(rotate)]
;
return {
rotate: rotate,
scale: scale,
translate: translate,
matrix: [
[scale * Math.cos(rotate), -scale * Math.sin(rotate), translate[0]],
[scale * Math.sin(rotate), scale * Math.cos(rotate), translate[1]],
[0, 0, 1]
]
};
}
/**
* 捕获touchstart事件,将每一个新增的触点添加到gestrues
* 如果之前尚无被记录的触点,则绑定touchmove, touchend, touchcancel事件
*
* 新增触点默认处于tapping状态
* 500毫秒之后如果还处于tapping状态,则触发press手势
* 如果触点数为2,则触发dualtouchstart手势,该手势的目标结点为两个触点共同的最小根结点
*
* @event
* @param {event} event
*/
function touchstartHandler(event) {
if (Object.keys(gestures).length === 0) {
docEl.addEventListener('touchmove', touchmoveHandler, false);
docEl.addEventListener('touchend', touchendHandler, false);
docEl.addEventListener('touchcancel', touchcancelHandler, false);
}
// 记录每一个触点
// TODO: 变量声明方式,建议在函数最前面声明
for(var i = 0 ; i < event.changedTouches.length ; i++ ) {
var touch = event.changedTouches[i],
touchRecord = {};
for (var p in touch) {
touchRecord[p] = touch[p];
}
var gesture = {
startTouch: touchRecord,
startTime: Date.now(),
status: 'tapping',
element: event.srcElement || event.target,
// TODO: Don't make functions within a loop
pressingHandler: setTimeout(function(element) {
return function () {
if (gesture.status === 'tapping') {
gesture.status = 'pressing';
fireEvent(element, 'press', {
touchEvent:event
});
}
clearTimeout(gesture.pressingHandler);
gesture.pressingHandler = null;
};
}(event.srcElement || event.target), 500)
};
gestures[touch.identifier] = gesture;
}
// TODO: 变量声明方式,建议在函数最前面声明
if (Object.keys(gestures).length == 2) {
var elements = [];
for(var p in gestures) {
elements.push(gestures[p].element);
}
fireEvent(getCommonAncestor(elements[0], elements[1]), 'dualtouchstart', {
touches: slice.call(event.touches),
touchEvent: event
});
}
}
/**
* 捕获touchmove事件,处理pan和dual的相关手势