forked from wechat-miniprogram/minigame-canvas-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
7519 lines (6293 loc) · 264 KB
/
index.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
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EE", function() { return EE; });
/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_env_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _components_elements_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _common_pool_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5);
/* harmony import */ var tiny_emitter__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/* harmony import */ var tiny_emitter__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(tiny_emitter__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var css_layout__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6);
/* harmony import */ var css_layout__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(css_layout__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _common_util_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(7);
/* harmony import */ var _libs_fast_xml_parser_parser_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(8);
/* harmony import */ var _libs_fast_xml_parser_parser_js__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_libs_fast_xml_parser_parser_js__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _common_bitMapFont__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(14);
/* harmony import */ var _tweenjs_tween_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(16);
/* harmony import */ var _common_debugInfo_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(18);
/* harmony import */ var _common_ticker__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(19);
/* harmony import */ var _common_vd__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(20);
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
// 全局事件管道
var EE = new tiny_emitter__WEBPACK_IMPORTED_MODULE_3___default.a();
var imgPool = new _common_pool_js__WEBPACK_IMPORTED_MODULE_2__["default"]('imgPool');
var debugInfo = new _common_debugInfo_js__WEBPACK_IMPORTED_MODULE_9__["default"]();
var Layout = /*#__PURE__*/function (_Element) {
_inherits(Layout, _Element);
var _super = _createSuper(Layout);
function Layout() {
var _this;
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
style = _ref.style,
name = _ref.name;
_classCallCheck(this, Layout);
_this = _super.call(this, {
style: style,
id: 0,
name: name
});
_this.hasEventHandler = false;
_this.elementTree = null;
_this.renderContext = null;
_this.renderport = {};
_this.viewport = {};
_this.viewportScale = 1;
_this.touchStart = _this.eventHandler('touchstart').bind(_assertThisInitialized(_this));
_this.touchMove = _this.eventHandler('touchmove').bind(_assertThisInitialized(_this));
_this.touchEnd = _this.eventHandler('touchend').bind(_assertThisInitialized(_this));
_this.touchCancel = _this.eventHandler('touchcancel').bind(_assertThisInitialized(_this));
_this.version = '1.0.0';
_this.eleCount = 0;
_this.touchMsg = {};
_this.hasViewPortSet = false;
_this.realLayoutBox = {
realX: 0,
realY: 0
};
_this.state = _common_util_js__WEBPACK_IMPORTED_MODULE_5__["STATE"].UNINIT;
_this.bitMapFonts = [];
/**
* 对于不会影响布局的改动,比如图片只是改个地址、加个背景色之类的改动,会触发 Layout 的 repaint 操作
* 触发的方式是给 Layout 抛个 `repaint` 的事件,为了性能,每次接收到 repaint 请求不会执行真正的渲染
* 而是执行一个置脏操作,ticker 每一次执行 update 会检查这个标记位,进而执行真正的重绘操作
*/
_this.isNeedRepaint = false;
_this.on('repaint', function () {
_this.isNeedRepaint = true;
});
_this.ticker = new _common_ticker__WEBPACK_IMPORTED_MODULE_10__["default"]();
/**
* 将 Tween 挂载到 Layout,对于 Tween 的使用完全遵循 Tween.js 的文档
* https://github.com/tweenjs/tween.js/
* 只不过当 Tween 改动了节点会触发 repaint、reflow 的属性时,Layout 会执行相应的操作
* 业务侧不用感知到 repaint 和 reflow
*/
_this.TWEEN = _tweenjs_tween_js__WEBPACK_IMPORTED_MODULE_8__["default"];
_this.tickerFunc = function () {
_tweenjs_tween_js__WEBPACK_IMPORTED_MODULE_8__["default"].update();
if (_this.isDirty) {
_this.reflow();
} else if (_this.isNeedRepaint) {
_this.repaint();
}
};
return _this;
} // 与老版本兼容
_createClass(Layout, [{
key: "debugInfo",
get: function get() {
var info = debugInfo.log();
info += "elementCount: ".concat(this.eleCount, "\n");
return info;
}
/**
* 更新被绘制canvas的窗口信息,本渲染引擎并不关心是否会和其他游戏引擎共同使用
* 而本身又需要支持事件处理,因此,如果被渲染内容是绘制到离屏canvas,需要将最终绘制在屏幕上
* 的绝对尺寸和位置信息更新到本渲染引擎。
* 其中,width为物理像素宽度,height为物理像素高度,x为距离屏幕左上角的物理像素x坐标,y为距离屏幕左上角的物理像素
* y坐标
*/
}, {
key: "updateViewPort",
value: function updateViewPort(box) {
this.viewport.width = box.width || 0;
this.viewport.height = box.height || 0;
this.viewport.x = box.x || 0;
this.viewport.y = box.y || 0;
this.realLayoutBox = {
realX: this.viewport.x,
realY: this.viewport.y
};
this.hasViewPortSet = true;
}
}, {
key: "init",
value: function init(template, style, attrValueProcessor) {
var parseConfig = {
attributeNamePrefix: '',
attrNodeName: 'attr',
// default is 'false'
textNodeName: '#text',
ignoreAttributes: false,
ignoreNameSpace: true,
allowBooleanAttributes: true,
parseNodeValue: false,
parseAttributeValue: false,
trimValues: true,
parseTrueNumberOnly: false
};
if (attrValueProcessor && typeof attrValueProcessor === 'function') {
parseConfig.attrValueProcessor = attrValueProcessor;
}
debugInfo.start('xmlParse'); // 将xml字符串解析成xml节点树
var jsonObj = _libs_fast_xml_parser_parser_js__WEBPACK_IMPORTED_MODULE_6___default.a.parse(template, parseConfig, true);
debugInfo.end('xmlParse');
var xmlTree = jsonObj.children[0]; // XML树生成渲染树
debugInfo.start('xmlTreeToLayoutTree');
var layoutTree = _common_vd__WEBPACK_IMPORTED_MODULE_11__["create"].call(this, xmlTree, style);
debugInfo.end('xmlTreeToLayoutTree');
this.add(layoutTree);
this.state = _common_util_js__WEBPACK_IMPORTED_MODULE_5__["STATE"].INITED;
this.ticker.add(this.tickerFunc);
this.ticker.start();
}
}, {
key: "reflow",
value: function reflow() {
var isFirst = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (!isFirst) {
debugInfo.reset();
}
debugInfo.start('reflow');
/**
* 计算布局树
* 经过 Layout 计算,节点树带上了 layout、lastLayout、shouldUpdate 布局信息
* Layout本身并不作为布局计算,只是作为节点树的容器
*/
debugInfo.start('computeLayout');
css_layout__WEBPACK_IMPORTED_MODULE_4___default()(this.children[0]);
debugInfo.end('computeLayout');
var rootEle = this.children[0];
if (rootEle.style.width === undefined || rootEle.style.height === undefined) {
console.error('Please set width and height property for root element');
} else {
this.renderport.width = rootEle.style.width;
this.renderport.height = rootEle.style.height;
} // 将布局树的布局信息加工赋值到渲染树
debugInfo.start('layoutChildren');
_common_vd__WEBPACK_IMPORTED_MODULE_11__["layoutChildren"].call(this, this);
debugInfo.end('layoutChildren');
this.viewportScale = this.viewport.width / this.renderport.width;
Object(_common_util_js__WEBPACK_IMPORTED_MODULE_5__["clearCanvas"])(this.renderContext); // 遍历节点树,依次调用节点的渲染接口实现渲染
debugInfo.start('renderChildren');
Object(_common_vd__WEBPACK_IMPORTED_MODULE_11__["renderChildren"])(this.children, this.renderContext, false);
debugInfo.end('renderChildren');
debugInfo.start('repaint');
this.repaint();
debugInfo.end('repaint');
this.isDirty = false; // iterateTree(this.children[0], (ele) => {
// console.log(ele.id, ele.className);
// });
debugInfo.end('reflow');
}
/**
* init阶段核心仅仅是根据xml和css创建了节点树
* 要实现真正的渲染,需要调用 layout 函数,之所以将 layout 单独抽象为一个函数,是因为 layout 应当是可以重复调用的
* 比如改变了一个元素的尺寸,实际上节点树是没变的,仅仅是需要重新计算布局,然后渲染
* 一个完整的 layout 分成下面的几步:
* 1. 执行画布清理,因为布局变化页面需要重绘,这里没有做很高级的剔除等操作,一律清除重画,实际上性能已经很好
* 2. 节点树都含有 style 属性,css-layout 能够根据这些信息计算出最终布局,详情可见 https://www.npmjs.com/package/css-layout
* 3. 经过 Layout 计算,节点树带上了 layout、lastLayout、shouldUpdate 布局信息,但这些信息并不是能够直接用的
* 比如 layout.top 是指在一个父容器内的 top,最终要实现渲染,实际上要递归加上复容器的 top
* 这样每次 repaint 的时候只需要直接使用计算好的值即可,不需要每次都递归计算
* 这一步称为 layoutChildren,目的在于将 css-layout 进一步处理为可以渲染直接用的布局信息
* 4. renderChildren:执行渲染
* 5. bindEvents:执行事件绑定
*/
}, {
key: "layout",
value: function layout(context) {
this.renderContext = context;
if (!this.hasViewPortSet) {
console.error('Please invoke method `updateViewPort` before method `layout`');
}
this.reflow(true);
this.bindEvents();
debugInfo.start('observeStyleAndEvent');
Object(_common_vd__WEBPACK_IMPORTED_MODULE_11__["iterateTree"])(this.children[0], function (element) {
return element.observeStyleAndEvent();
});
debugInfo.end('observeStyleAndEvent');
this.state = _common_util_js__WEBPACK_IMPORTED_MODULE_5__["STATE"].RENDERED;
}
}, {
key: "repaint",
value: function repaint() {
Object(_common_util_js__WEBPACK_IMPORTED_MODULE_5__["clearCanvas"])(this.renderContext);
this.isNeedRepaint = false;
Object(_common_vd__WEBPACK_IMPORTED_MODULE_11__["repaintChildren"])(this.children);
}
}, {
key: "eventHandler",
value: function eventHandler(eventName) {
return function touchEventHandler(e) {
var _this2 = this;
var touch = e.touches && e.touches[0] || e.changedTouches && e.changedTouches[0] || e;
if (!touch || !touch.pageX || !touch.pageY) {
return;
}
if (!touch.timeStamp) {
touch.timeStamp = e.timeStamp;
}
var list = [];
if (touch) {
var x = touch.pageX;
var y = touch.pageY;
Object(_common_vd__WEBPACK_IMPORTED_MODULE_11__["iterateTree"])(this.children[0], function (ele) {
var _ele$layoutBox = ele.layoutBox,
absoluteX = _ele$layoutBox.absoluteX,
absoluteY = _ele$layoutBox.absoluteY,
width = _ele$layoutBox.width,
height = _ele$layoutBox.height;
var realX = absoluteX * _this2.viewportScale + _this2.realLayoutBox.realX;
var realY = absoluteY * _this2.viewportScale + _this2.realLayoutBox.realY;
var realWidth = width * _this2.viewportScale;
var realHeight = height * _this2.viewportScale;
if (realX <= x && x <= realX + realWidth && realY <= y && y <= realY + realHeight) {
list.push(ele);
}
});
}
if (!list.length) {
list.push(this);
}
var item = list[list.length - 1];
item && item.emit(eventName, e);
if (eventName === 'touchstart' || eventName === 'touchend') {
this.touchMsg[eventName] = touch;
}
if (eventName === 'touchend' && Object(_common_util_js__WEBPACK_IMPORTED_MODULE_5__["isClick"])(this.touchMsg)) {
item && item.emit('click', e);
}
};
}
}, {
key: "bindEvents",
value: function bindEvents() {
if (this.hasEventHandler) {
return;
}
this.hasEventHandler = true;
if (typeof __env !== 'undefined') {
__env.onTouchStart(this.touchStart);
__env.onTouchMove(this.touchMove);
__env.onTouchEnd(this.touchEnd);
__env.onTouchCancel(this.touchCancel);
} else {
document.onmousedown = this.touchStart;
document.onmousemove = this.touchMove;
document.onmouseup = this.touchEnd;
document.onmouseleave = this.touchEnd;
}
}
}, {
key: "unBindEvents",
value: function unBindEvents() {
if (typeof __env !== 'undefined') {
__env.offTouchStart(this.touchStart);
__env.offTouchMove(this.touchMove);
__env.offTouchEnd(this.touchEnd);
__env.offTouchCancel(this.touchCancel);
} else {
document.onmousedown = null;
document.onmousemove = null;
document.onmouseup = null;
document.onmouseleave = null;
}
this.hasEventHandler = false;
}
}, {
key: "emit",
value: function emit(event, data) {
EE.emit(event, data);
}
}, {
key: "on",
value: function on(event, callback) {
EE.on(event, callback);
}
}, {
key: "once",
value: function once(event, callback) {
EE.once(event, callback);
}
}, {
key: "off",
value: function off(event, callback) {
EE.off(event, callback);
}
}, {
key: "destroyAll",
value: function destroyAll(tree) {
var _this3 = this;
var children = tree.children;
children.forEach(function (child) {
child.destroy();
_this3.destroyAll(child);
child.destroySelf && child.destroySelf();
});
}
}, {
key: "clear",
value: function clear() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var _options$removeTicker = options.removeTicker,
removeTicker = _options$removeTicker === void 0 ? true : _options$removeTicker;
debugInfo.reset();
_tweenjs_tween_js__WEBPACK_IMPORTED_MODULE_8__["default"].removeAll();
this.destroyAll(this);
this.elementTree = null;
this.children = [];
this.state = _common_util_js__WEBPACK_IMPORTED_MODULE_5__["STATE"].CLEAR;
this.isDirty = false;
Object(_common_util_js__WEBPACK_IMPORTED_MODULE_5__["clearCanvas"])(this.renderContext);
this.eleCount = 0;
this.unBindEvents();
if (removeTicker) {
this.ticker.remove();
this.ticker.stop();
}
}
}, {
key: "clearPool",
value: function clearPool() {
imgPool.clear();
}
}, {
key: "clearAll",
value: function clearAll() {
this.clear();
this.clearPool();
}
}, {
key: "loadImgs",
value: function loadImgs(arr) {
arr.forEach(function (src) {
var img = Object(_common_util_js__WEBPACK_IMPORTED_MODULE_5__["createImage"])();
imgPool.set(src, img);
img.onload = function () {
img.loadDone = true;
};
img.onloadcbks = [];
img.src = src;
});
}
}, {
key: "registBitMapFont",
value: function registBitMapFont(name, src, config) {
var font = new _common_bitMapFont__WEBPACK_IMPORTED_MODULE_7__["default"](name, src, config);
this.bitMapFonts.push(font);
}
}, {
key: "cloneNode",
value: function cloneNode(element) {
var deep = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
return _common_vd__WEBPACK_IMPORTED_MODULE_11__["clone"].call(this, element, deep);
}
}]);
return Layout;
}(_components_elements_js__WEBPACK_IMPORTED_MODULE_1__["default"]);
/* harmony default export */ __webpack_exports__["default"] = (new Layout({
style: {
width: 0,
height: 0
},
name: 'layout'
}));
/***/ }),
/* 1 */
/***/ (function(module, exports) {
if (typeof GameGlobal !== 'undefined') {
GameGlobal.__env = GameGlobal.wx || GameGlobal.tt || GameGlobal.swan;
}
/***/ }),
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getElementsById", function() { return _getElementsById; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getElementsByClassName", function() { return _getElementsByClassName; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Element; });
/* harmony import */ var _style_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3);
/* harmony import */ var _common_rect__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(30);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/* eslint-disable no-param-reassign */
function _getElementsById(tree) {
var list = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var id = arguments.length > 2 ? arguments[2] : undefined;
Object.keys(tree.children).forEach(function (key) {
var child = tree.children[key];
if (child.idName === id) {
list.push(child);
}
if (Object.keys(child.children).length) {
_getElementsById(child, list, id);
}
});
return list;
}
function _getElementsByClassName(tree) {
var list = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var className = arguments.length > 2 ? arguments[2] : undefined;
Object.keys(tree.children).forEach(function (key) {
var child = tree.children[key];
if ((child.classNameList || child.className.split(/\s+/)).indexOf(className) > -1) {
list.push(child);
}
if (Object.keys(child.children).length) {
_getElementsByClassName(child, list, className);
}
});
return list;
}
var Emitter = __webpack_require__(4); // 全局事件管道
var EE = new Emitter();
var uuid = 0;
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
function getRgba(hex, opacity) {
var rgbObj = hexToRgb(hex);
if (opacity === undefined) {
opacity = 1;
}
return "rgba(".concat(rgbObj.r, ", ").concat(rgbObj.g, ", ").concat(rgbObj.b, ", ").concat(opacity, ")");
}
var toEventName = function toEventName(event, id) {
var elementEvent = ['click', 'touchstart', 'touchmove', 'touchend', 'touchcancel'];
if (elementEvent.indexOf(event) !== -1) {
return "element-".concat(id, "-").concat(event);
}
return "element-".concat(id, "-").concat(event);
};
var Element = /*#__PURE__*/function () {
function Element(_ref) {
var _ref$style = _ref.style,
style = _ref$style === void 0 ? {} : _ref$style,
_ref$props = _ref.props,
props = _ref$props === void 0 ? {} : _ref$props,
_ref$idName = _ref.idName,
idName = _ref$idName === void 0 ? '' : _ref$idName,
_ref$className = _ref.className,
className = _ref$className === void 0 ? '' : _ref$className,
_ref$id = _ref.id,
id = _ref$id === void 0 ? uuid += 1 : _ref$id,
_ref$dataset = _ref.dataset,
dataset = _ref$dataset === void 0 ? {} : _ref$dataset;
_classCallCheck(this, Element);
this.children = [];
this.parent = null;
this.parentId = 0;
this.id = id;
this.props = props;
this.idName = idName;
this.className = className; // this.style = style;
this.EE = EE;
this.root = null;
this.isDestroyed = false;
this.layoutBox = {};
this.dataset = dataset;
if (style.opacity !== undefined && style.color && style.color.indexOf('#') > -1) {
style.color = getRgba(style.color, style.opacity);
}
if (style.opacity !== undefined && style.backgroundColor && style.backgroundColor.indexOf('#') > -1) {
style.backgroundColor = getRgba(style.backgroundColor, style.opacity);
}
this.originStyle = style;
this.style = style;
this.rect = null;
this.classNameList = null;
}
/**
* 监听属性的变化判断是否需要执行 reflow、repaint 操作
* 经过测试,Object.defineProperty 是一个比较慢的方法, 特别是属性比较多的时候
* 因此会先判断是否支持 Proxy,iMac (Retina 5K, 27-inch, 2017)测试结果
* 总共 312 个节点,observeStyleAndEvent总耗时为:
* Proxy: 3ms
* Object.defineProperty: 20ms
*/
_createClass(Element, [{
key: "observeStyleAndEvent",
value: function observeStyleAndEvent() {
var _this = this;
if (typeof Proxy === 'function') {
var ele = this;
this.style = new Proxy(this.originStyle, {
get: function get(target, prop, receiver) {
return Reflect.get(target, prop, receiver);
},
set: function set(target, prop, val, receiver) {
if (_style_js__WEBPACK_IMPORTED_MODULE_0__["reflowAffectedStyles"].indexOf(prop)) {
ele.isDirty = true;
var parent = ele.parent;
while (parent) {
parent.isDirty = true;
parent = parent.parent;
}
} else if (_style_js__WEBPACK_IMPORTED_MODULE_0__["repaintAffectedStyles"].indexOf(prop)) {
ele.root.emit('repaint');
}
return Reflect.set(target, prop, val, receiver);
}
});
} else {
var innerStyle = Object.assign({}, this.style);
_style_js__WEBPACK_IMPORTED_MODULE_0__["allStyles"].forEach(function (key) {
Object.defineProperty(_this.style, key, {
configurable: true,
enumerable: true,
get: function get() {
return innerStyle[key];
},
set: function set(value) {
innerStyle[key] = value;
if (_style_js__WEBPACK_IMPORTED_MODULE_0__["reflowAffectedStyles"].indexOf(key)) {
_this.isDirty = true;
var parent = _this.parent;
while (parent) {
parent.isDirty = true;
parent = parent.parent;
}
} else if (_style_js__WEBPACK_IMPORTED_MODULE_0__["repaintAffectedStyles"].indexOf(key)) {
_this.root.emit('repaint');
}
}
});
});
} // 事件冒泡逻辑
['touchstart', 'touchmove', 'touchcancel', 'touchend', 'click'].forEach(function (eventName) {
_this.on(eventName, function (e, touchMsg) {
_this.parent && _this.parent.emit(eventName, e, touchMsg);
});
});
this.classNameList = this.className.split(/\s+/);
} // 子类填充实现
}, {
key: "repaint",
value: function repaint() {} // 子类填充实现
}, {
key: "render",
value: function render() {}
/**
* 参照 Web 规范:https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
*/
}, {
key: "getBoundingClientRect",
value: function getBoundingClientRect() {
if (!this.rect) {
this.rect = new _common_rect__WEBPACK_IMPORTED_MODULE_1__["default"](this.layoutBox.absoluteX, this.layoutBox.absoluteY, this.layoutBox.width, this.layoutBox.height);
}
this.rect.set(this.layoutBox.absoluteX, this.layoutBox.absoluteY, this.layoutBox.width, this.layoutBox.height);
return this.rect;
}
}, {
key: "getElementsById",
value: function getElementsById(id) {
return _getElementsById(this, [], id);
}
}, {
key: "getElementsByClassName",
value: function getElementsByClassName(className) {
return _getElementsByClassName(this, [], className);
}
}, {
key: "insert",
value: function insert(ctx, needRender) {
this.ctx = ctx;
if (needRender) {
this.render();
}
} // 子类填充实现
}, {
key: "destroy",
value: function destroy() {
var _this2 = this;
['touchstart', 'touchmove', 'touchcancel', 'touchend', 'click', 'repaint'].forEach(function (eventName) {
_this2.off(eventName);
});
this.isDestroyed = true;
this.EE = null;
this.parent = null;
this.ctx = null; // element 在画布中的位置和尺寸信息
this.layoutBox = null;
this.props = null;
this.style = null;
this.className = '';
this.classNameList = null;
}
}, {
key: "add",
value: function add(element) {
element.parent = this;
element.parentId = this.id;
this.children.push(element);
}
}, {
key: "appendChild",
value: function appendChild(element) {
this.add(element);
this.isDirty = true;
var parent = this.parent;
while (parent) {
parent.isDirty = true;
parent = parent.parent;
}
}
}, {
key: "emit",
value: function emit(event) {
for (var _len = arguments.length, theArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
theArgs[_key - 1] = arguments[_key];
}
EE.emit.apply(EE, [toEventName(event, this.id)].concat(theArgs));
}
}, {
key: "on",
value: function on(event, callback) {
EE.on(toEventName(event, this.id), callback);
}
}, {
key: "once",
value: function once(event, callback) {
EE.once(toEventName(event, this.id), callback);
}
}, {
key: "off",
value: function off(event, callback) {
EE.off(toEventName(event, this.id), callback);
}
}, {
key: "renderBorder",
value: function renderBorder(ctx) {
var style = this.style || {};
var radius = style.borderRadius || 0;
var _style$borderWidth = style.borderWidth,
borderWidth = _style$borderWidth === void 0 ? 0 : _style$borderWidth;
var borderTopLeftRadius = style.borderTopLeftRadius || radius;
var borderTopRightRadius = style.borderTopRightRadius || radius;
var borderBottomLeftRadius = style.borderBottomLeftRadius || radius;
var borderBottomRightRadius = style.borderBottomRightRadius || radius;
var box = this.layoutBox;
var borderColor = style.borderColor;
var x = box.absoluteX;
var y = box.absoluteY;
var width = box.width,
height = box.height;
var hasRadius = radius || borderTopLeftRadius || borderTopRightRadius || borderBottomLeftRadius || borderBottomRightRadius; // borderWidth 和 radius 都没有,不需要执行后续逻辑,提升性能
if (!borderWidth && !hasRadius) {
return {
needClip: false,
needStroke: false
};
} // 左上角的点
ctx.beginPath();
ctx.lineWidth = borderWidth;
ctx.strokeStyle = borderColor;
ctx.moveTo(x + borderTopLeftRadius, y);
ctx.lineTo(x + width - borderTopRightRadius, y); // 右上角的圆角
ctx.arcTo(x + width, y, x + width, y + borderTopRightRadius, borderTopRightRadius); // 右下角的点
ctx.lineTo(x + width, y + height - borderBottomRightRadius); // 右下角的圆角
ctx.arcTo(x + width, y + height, x + width - borderBottomRightRadius, y + height, borderBottomRightRadius); // 左下角的点
ctx.lineTo(x + borderBottomLeftRadius, y + height); // 左下角的圆角
ctx.arcTo(x, y + height, x, y + height - borderBottomLeftRadius, borderBottomLeftRadius); // 左上角的点
ctx.lineTo(x, y + borderTopLeftRadius); // 左上角的圆角
ctx.arcTo(x, y, x + borderTopLeftRadius, y, borderTopLeftRadius);
return {
needClip: !!hasRadius,
needStroke: !!borderWidth
};
}
}]);
return Element;
}();
/***/ }),
/* 3 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "repaintAffectedStyles", function() { return repaintAffectedStyles; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reflowAffectedStyles", function() { return reflowAffectedStyles; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "allStyles", function() { return allStyles; });
var reflowAffectedStyles = ['width', 'height', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight', 'left', 'right', 'top', 'bottom', 'margin', 'marginLeft', 'marginRight', 'marginTop', 'marginBottom', 'padding', 'paddingLeft', 'paddingRight', 'paddingTop', 'paddingBottom', 'borderWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth', 'borderBottomWidth', 'flexDirection', 'justifyContent', 'alignItems', 'alignSelf', 'flex', 'flexWrap', 'position'];
var repaintAffectedStyles = ['fontSize', 'lineHeight', 'textAlign', 'verticalAlign', 'color', 'backgroundColor', 'textOverflow', 'letterSpacing', 'backgroundColor', 'borderRadius', 'borderColor'];
var allStyles = reflowAffectedStyles.concat(repaintAffectedStyles);
/***/ }),
/* 4 */
/***/ (function(module, exports) {
function E () {
// Keep this empty so it's easier to inherit from
// (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3)
}
E.prototype = {
on: function (name, callback, ctx) {
var e = this.e || (this.e = {});
(e[name] || (e[name] = [])).push({
fn: callback,
ctx: ctx
});
return this;
},
once: function (name, callback, ctx) {
var self = this;
function listener () {
self.off(name, listener);
callback.apply(ctx, arguments);