UNPKG

15.7 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6
7var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
8
9var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
10
11exports.browser = browser;
12exports.getOffset = getOffset;
13exports.loopAllChildren = loopAllChildren;
14exports.isInclude = isInclude;
15exports.filterParentPosition = filterParentPosition;
16exports.handleCheckState = handleCheckState;
17exports.getCheck = getCheck;
18exports.getStrictlyValue = getStrictlyValue;
19exports.arraysEqual = arraysEqual;
20exports.closest = closest;
21exports.isTreeNode = isTreeNode;
22exports.toArray = toArray;
23exports.getNodeChildren = getNodeChildren;
24exports.warnOnlyTreeNode = warnOnlyTreeNode;
25exports.convertListToTree = convertListToTree;
26exports.debounce = debounce;
27exports.throttle = throttle;
28
29var _react = require('react');
30
31var _react2 = _interopRequireDefault(_react);
32
33function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
34
35function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } /* eslint no-loop-func: 0*/
36
37function browser(navigator) {
38 var tem = void 0;
39 var ua = navigator.userAgent;
40 var M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
41 if (/trident/i.test(M[1])) {
42 tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
43 return 'IE ' + (tem[1] || '');
44 }
45 if (M[1] === 'Chrome') {
46 tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
47 if (tem) return tem.slice(1).join(' ').replace('OPR', 'Opera');
48 }
49 M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
50 tem = ua.match(/version\/(\d+)/i);
51 if (tem) {
52 M.splice(1, 1, tem[1]);
53 }
54 return M.join(' ');
55}
56
57// export function getOffset(el) {
58// const obj = el.getBoundingClientRect();
59// return {
60// left: obj.left + document.body.scrollLeft,
61// top: obj.top + document.body.scrollTop,
62// width: obj.width,
63// height: obj.height
64// };
65// }
66
67// // iscroll offset
68// offset = function (el) {
69// var left = -el.offsetLeft,
70// top = -el.offsetTop;
71
72// // jshint -W084
73// while (el = el.offsetParent) {
74// left -= el.offsetLeft;
75// top -= el.offsetTop;
76// }
77// // jshint +W084
78
79// return {
80// left: left,
81// top: top
82// };
83// }
84
85/* eslint-disable */
86function getOffset(ele) {
87 var doc = void 0,
88 win = void 0,
89 docElem = void 0,
90 rect = void 0;
91
92 if (!ele.getClientRects().length) {
93 return { top: 0, left: 0 };
94 }
95
96 rect = ele.getBoundingClientRect();
97
98 if (rect.width || rect.height) {
99 doc = ele.ownerDocument;
100 win = doc.defaultView;
101 docElem = doc.documentElement;
102
103 return {
104 top: rect.top + win.pageYOffset - docElem.clientTop,
105 left: rect.left + win.pageXOffset - docElem.clientLeft
106 };
107 }
108
109 return rect;
110}
111/* eslint-enable */
112
113function getChildrenlength(children) {
114 var len = 1;
115 if (Array.isArray(children)) {
116 len = children.length;
117 }
118 return len;
119}
120
121function getSiblingPosition(index, len, siblingPosition) {
122 if (len === 1) {
123 siblingPosition.first = true;
124 siblingPosition.last = true;
125 } else {
126 siblingPosition.first = index === 0;
127 siblingPosition.last = index === len - 1;
128 }
129 return siblingPosition;
130}
131
132function loopAllChildren(childs, callback, parent) {
133 var loop = function loop(children, level, _parent) {
134 var len = getChildrenlength(children);
135 _react2["default"].Children.forEach(children, function (item, index) {
136 var pos = level + '-' + index;
137 if (item.props.children && item.type && item.type.isTreeNode) {
138 loop(item.props.children, pos, { node: item, pos: pos });
139 }
140 callback(item, index, pos, item.key || pos, getSiblingPosition(index, len, {}), _parent);
141 });
142 };
143 loop(childs, 0, parent);
144}
145
146function isInclude(smallArray, bigArray) {
147 return smallArray.every(function (ii, i) {
148 return ii === bigArray[i];
149 });
150}
151// console.log(isInclude(['0', '1'], ['0', '10', '1']));
152
153
154// arr.length === 628, use time: ~20ms
155function filterParentPosition(arr) {
156 var levelObj = {};
157 arr.forEach(function (item) {
158 var posLen = item.split('-').length;
159 if (!levelObj[posLen]) {
160 levelObj[posLen] = [];
161 }
162 levelObj[posLen].push(item);
163 });
164 var levelArr = Object.keys(levelObj).sort();
165
166 var _loop = function _loop(i) {
167 if (levelArr[i + 1]) {
168 levelObj[levelArr[i]].forEach(function (ii) {
169 var _loop2 = function _loop2(j) {
170 levelObj[levelArr[j]].forEach(function (_i, index) {
171 if (isInclude(ii.split('-'), _i.split('-'))) {
172 levelObj[levelArr[j]][index] = null;
173 }
174 });
175 levelObj[levelArr[j]] = levelObj[levelArr[j]].filter(function (p) {
176 return p;
177 });
178 };
179
180 for (var j = i + 1; j < levelArr.length; j++) {
181 _loop2(j);
182 }
183 });
184 }
185 };
186
187 for (var i = 0; i < levelArr.length; i++) {
188 _loop(i);
189 }
190 var nArr = [];
191 levelArr.forEach(function (i) {
192 nArr = nArr.concat(levelObj[i]);
193 });
194 return nArr;
195}
196// console.log(filterParentPosition(
197// ['0-2', '0-3-3', '0-10', '0-10-0', '0-0-1', '0-0', '0-1-1', '0-1']
198// ));
199
200
201function stripTail(str) {
202 var arr = str.match(/(.+)(-[^-]+)$/);
203 var st = '';
204 if (arr && arr.length === 3) {
205 st = arr[1];
206 }
207 return st;
208}
209function splitPosition(pos) {
210 return pos.split('-');
211}
212
213function handleCheckState(obj, checkedPositionArr, checkIt) {
214 // console.log(stripTail('0-101-000'));
215 var objKeys = Object.keys(obj);
216 // let s = Date.now();
217 objKeys.forEach(function (i, index) {
218 var iArr = splitPosition(i);
219 var saved = false;
220 checkedPositionArr.forEach(function (_pos) {
221 // 设置子节点,全选或全不选
222 var _posArr = splitPosition(_pos);
223 if (iArr.length > _posArr.length && isInclude(_posArr, iArr)) {
224 obj[i].halfChecked = false;
225 obj[i].checked = checkIt;
226 objKeys[index] = null;
227 }
228 if (iArr[0] === _posArr[0] && iArr[1] === _posArr[1]) {
229 // 如果
230 saved = true;
231 }
232 });
233 if (!saved) {
234 objKeys[index] = null;
235 }
236 });
237 // TODO: 循环 2470000 次耗时约 1400 ms。 性能瓶颈!
238 // console.log(Date.now()-s, checkedPositionArr.length * objKeys.length);
239 objKeys = objKeys.filter(function (i) {
240 return i;
241 }); // filter non null;
242
243 var _loop3 = function _loop3(_pIndex) {
244 // 循环设置父节点的 选中 或 半选状态
245 var loop = function loop(__pos) {
246 var _posLen = splitPosition(__pos).length;
247 if (_posLen <= 2) {
248 // e.g. '0-0', '0-1'
249 return;
250 }
251 var sibling = 0;
252 var siblingChecked = 0;
253 var parentPosition = stripTail(__pos);
254 objKeys.forEach(function (i /* , index*/) {
255 var iArr = splitPosition(i);
256 if (iArr.length === _posLen && isInclude(splitPosition(parentPosition), iArr)) {
257 sibling++;
258 if (obj[i].checked) {
259 siblingChecked++;
260 var _i = checkedPositionArr.indexOf(i);
261 if (_i > -1) {
262 checkedPositionArr.splice(_i, 1);
263 if (_i <= _pIndex) {
264 _pIndex--;
265 }
266 }
267 } else if (obj[i].halfChecked) {
268 siblingChecked += 0.5;
269 }
270 // objKeys[index] = null;
271 }
272 });
273 // objKeys = objKeys.filter(i => i); // filter non null;
274 var parent = obj[parentPosition];
275 // sibling 不会等于0
276 // 全不选 - 全选 - 半选
277 if (siblingChecked === 0) {
278 parent.checked = false;
279 parent.halfChecked = false;
280 } else if (siblingChecked === sibling) {
281 parent.checked = true;
282 parent.halfChecked = false;
283 } else {
284 parent.halfChecked = true;
285 parent.checked = false;
286 }
287 loop(parentPosition);
288 };
289 loop(checkedPositionArr[_pIndex], _pIndex);
290 pIndex = _pIndex;
291 };
292
293 for (var pIndex = 0; pIndex < checkedPositionArr.length; pIndex++) {
294 _loop3(pIndex);
295 }
296 // console.log(Date.now()-s, objKeys.length, checkIt);
297}
298
299function getCheck(treeNodesStates) {
300 var halfCheckedKeys = [];
301 var checkedKeys = [];
302 var checkedNodes = [];
303 var checkedNodesPositions = [];
304 Object.keys(treeNodesStates).forEach(function (item) {
305 var itemObj = treeNodesStates[item];
306 if (itemObj.checked) {
307 checkedKeys.push(itemObj.key);
308 checkedNodes.push(itemObj.node);
309 checkedNodesPositions.push({ node: itemObj.node, pos: item });
310 } else if (itemObj.halfChecked) {
311 halfCheckedKeys.push(itemObj.key);
312 }
313 });
314 return {
315 halfCheckedKeys: halfCheckedKeys, checkedKeys: checkedKeys, checkedNodes: checkedNodes, checkedNodesPositions: checkedNodesPositions, treeNodesStates: treeNodesStates
316 };
317}
318
319function getStrictlyValue(checkedKeys, halfChecked) {
320 if (halfChecked) {
321 return { checked: checkedKeys, halfChecked: halfChecked };
322 }
323 return checkedKeys;
324}
325
326function arraysEqual(a, b) {
327 if (a === b) return true;
328 if (a === null || typeof a === 'undefined' || b === null || typeof b === 'undefined') {
329 return false;
330 }
331 if (a.length !== b.length) return false;
332
333 // If you don't care about the order of the elements inside
334 // the array, you should sort both arrays here.
335
336 for (var i = 0; i < a.length; ++i) {
337 if (a[i] !== b[i]) return false;
338 }
339 return true;
340}
341
342function closest(el, selector) {
343 var matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
344
345 while (el) {
346 if (matchesSelector.call(el, selector)) {
347 return el;
348 } else {
349 el = el.parentElement;
350 }
351 }
352 return null;
353}
354
355function isTreeNode(node) {
356 return node && node.type && node.type.isTreeNode;
357}
358
359function toArray(children) {
360 var ret = [];
361 _react2["default"].Children.forEach(children, function (c) {
362 ret.push(c);
363 });
364 return ret;
365}
366
367function getNodeChildren(children) {
368 return toArray(children).filter(isTreeNode);
369}
370
371var onlyTreeNodeWarned = false;
372
373function warnOnlyTreeNode() {
374 if (onlyTreeNodeWarned) return;
375 onlyTreeNodeWarned = true;
376 console.warn('Tree only accept TreeNode as children.');
377}
378
379/**
380 * 将一维数组转换为树结构
381 * @param {*} treeData 扁平结构的 List 数组
382 * @param {*} attr 属性配置设置
383 * @param {*} flatTreeKeysMap 存储所有 key-value 的映射,方便获取各节点信息
384 */
385function convertListToTree(treeData, attr, flatTreeKeysMap) {
386 var tree = []; //存储所有一级节点
387 var resData = treeData,
388 //resData 存储截取的节点 + 父节点(除一级节点外)
389 resKeysMap = {},
390 //resData 的Map映射
391 treeKeysMap = {}; //tree 的Map映射
392 resData.map(function (element) {
393 var key = attr.id;
394 resKeysMap[element[key]] = element;
395 });
396 // 查找父节点,为了补充不完整的数据结构
397 var findParentNode = function findParentNode(node) {
398 var parentKey = node[attr.parendId];
399 if (parentKey !== attr.rootId) {
400 //如果不是根节点,则继续递归
401 var item = flatTreeKeysMap[parentKey];
402 // 用 resKeysMap 判断,避免重复计算某节点的父节点
403 if (resKeysMap.hasOwnProperty(item[attr.id])) return;
404 resData.unshift(item);
405 resKeysMap[item[attr.id]] = item;
406 findParentNode(item);
407 } else {
408 // 用 treeKeysMap 判断,避免重复累加
409 if (!treeKeysMap.hasOwnProperty(node[attr.id])) {
410 var key = node.key,
411 title = node.title,
412 children = node.children,
413 isLeaf = node.isLeaf,
414 otherProps = _objectWithoutProperties(node, ['key', 'title', 'children', 'isLeaf']);
415
416 var obj = {
417 key: key,
418 title: title,
419 isLeaf: isLeaf,
420 children: []
421 };
422 tree.push(_extends(obj, _extends({}, otherProps)));
423 treeKeysMap[key] = node;
424 }
425 }
426 };
427 // 遍历 resData ,找到所有的一级节点
428 for (var i = 0; i < resData.length; i++) {
429 var item = resData[i];
430 if (item[attr.parendId] === attr.rootId && !treeKeysMap.hasOwnProperty(item[attr.id])) {
431 //如果是根节点,就存放进 tree 对象中
432 var key = item.key,
433 title = item.title,
434 children = item.children,
435 otherProps = _objectWithoutProperties(item, ['key', 'title', 'children']);
436
437 var obj = {
438 key: item[attr.id],
439 title: item[attr.name],
440 isLeaf: item[attr.isLeaf],
441 children: []
442 };
443 tree.push(_extends(obj, _extends({}, otherProps)));
444 treeKeysMap[key] = item;
445 resData.splice(i, 1);
446 i--;
447 } else {
448 //递归查找根节点信息
449 findParentNode(item);
450 }
451 }
452 // console.log('resData',resKeysMap);
453 var run = function run(treeArrs) {
454 if (resData.length > 0) {
455 for (var _i2 = 0; _i2 < treeArrs.length; _i2++) {
456 for (var j = 0; j < resData.length; j++) {
457 var _item = resData[j];
458 if (treeArrs[_i2].key === _item[attr.parendId]) {
459 var _key = _item.key,
460 _title = _item.title,
461 _children = _item.children,
462 _otherProps = _objectWithoutProperties(_item, ['key', 'title', 'children']);
463
464 var _obj = {
465 key: _item[attr.id],
466 title: _item[attr.name],
467 isLeaf: _item[attr.isLeaf],
468 children: []
469 };
470 treeArrs[_i2].children.push(_extends(_obj, _extends({}, _otherProps)));
471 resData.splice(j, 1);
472 j--;
473 }
474 }
475 run(treeArrs[_i2].children);
476 }
477 }
478 };
479 run(tree);
480 return tree;
481}
482
483function isObject(value) {
484 var type = typeof value === 'undefined' ? 'undefined' : _typeof(value);
485 return value != null && (type == 'object' || type == 'function');
486}
487
488/**
489 * 函数防抖
490 * @param {*} func
491 * @param {*} wait
492 * @param {*} immediate
493 */
494function debounce(func, wait, immediate) {
495 var timeout = void 0;
496 return function debounceFunc() {
497 var context = this;
498 var args = arguments;
499 // https://fb.me/react-event-pooling
500 if (args[0] && args[0].persist) {
501 args[0].persist();
502 }
503 var later = function later() {
504 timeout = null;
505 if (!immediate) {
506 func.apply(context, args);
507 }
508 };
509 var callNow = immediate && !timeout;
510 clearTimeout(timeout);
511 timeout = setTimeout(later, wait);
512 if (callNow) {
513 func.apply(context, args);
514 }
515 };
516}
517
518/**
519 * 函数节流
520 * @param {*} func 延时调用函数
521 * @param {*} wait 延迟多长时间
522 * @param {*} options 至少多长时间触发一次
523 * @return Function 延迟执行的方法
524 */
525function throttle(func, wait, options) {
526 var leading = true;
527 var trailing = true;
528
529 if (typeof func !== 'function') {
530 throw new TypeError('Expected a function');
531 }
532 if (isObject(options)) {
533 leading = 'leading' in options ? !!options.leading : leading;
534 trailing = 'trailing' in options ? !!options.trailing : trailing;
535 }
536 return debounce(func, wait, {
537 leading: leading,
538 trailing: trailing,
539 'maxWait': wait
540 });
541}
\No newline at end of file