From 4e2a41bfb7a0e0bc7d4395f96cbe1862b6df61b8 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Thu, 5 Jan 2023 00:30:17 +0800 Subject: [PATCH] =?UTF-8?q?=E6=97=A0JIRA=E4=BB=BB=E5=8A=A1=20chore:=20?= =?UTF-8?q?=E8=A1=A5=E5=85=85eslint=E8=A7=84=E5=88=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .eslintrc | 8 +- src/core/2.base.js | 544 +++++++++++++++++++++++-------------------- src/core/3.ob.js | 11 +- src/core/4.widget.js | 135 ++++++----- src/core/5.inject.js | 201 ++++++++-------- src/core/index.js | 6 +- 6 files changed, 495 insertions(+), 410 deletions(-) diff --git a/.eslintrc b/.eslintrc index eee30f2c7..234d9007a 100644 --- a/.eslintrc +++ b/.eslintrc @@ -27,11 +27,15 @@ "plugins": ["@typescript-eslint/eslint-plugin"], "overrides": [{ "files": ["src/*.js","src/**/*.js", "demo/*.js", "demo/**/*.js", "i18n/**/*.js", "i18n/*.js", "test/**/*.js", "test/*.js", "examples/*.js", "examples/**/*.js"], - "extends": "plugin:@fui/es6", + "extends": "plugin:@fui/esnext", "rules": { "no-param-reassign": "off", "quotes": [2, "double"], - "comma-dangle": ["error", { "arrays": "never", "objects": "always-multiline"}] // 多行对象字面量中要求拖尾逗号 + "comma-dangle": ["error", { "arrays": "never", "objects": "always-multiline"}], // 多行对象字面量中要求拖尾逗号 + "no-var": 2, + "prefer-const": 2, + "indent": ["error", 4], + "no-use-before-define": 0 } }, { "files": ["webpack/*.js", "./*.js", "lib/**/*.js", "lib/*.js", "./bin/*.js", "./bin/**/*.js"], diff --git a/src/core/2.base.js b/src/core/2.base.js index 01814415b..4fe7583de 100644 --- a/src/core/2.base.js +++ b/src/core/2.base.js @@ -3,28 +3,29 @@ * Create By GUY 2014\11\17 * */ -var traverse = function (func, context) { +function traverse (func, context) { return function (value, key, obj) { return func.call(context, key, value, obj); }; -}; -var _apply = function (name) { +} +function _apply(name) { return function () { - return BI._[name].apply(BI._, arguments); + return BI._[name](...arguments); }; -}; -var _applyFunc = function (name) { +} +function _applyFunc(name) { return function () { - var args = Array.prototype.slice.call(arguments, 0); + const args = Array.prototype.slice.call(arguments, 0); args[1] = BI._.isFunction(args[1]) ? traverse(args[1], args[2]) : args[1]; - return BI._[name].apply(BI._, args); + + return BI._[name](...args); }; -}; +} export function assert(v, is) { if (isFunction(is)) { if (!is(v)) { - throw new Error(v + " error"); + throw new Error(`${v} error`); } else { return true; } @@ -33,8 +34,9 @@ export function assert(v, is) { is = [is]; } if (!deepContains(is, v)) { - throw new Error(v + " error"); + throw new Error(`${v} error`); } + return true; } @@ -43,12 +45,13 @@ export function warn(message) { } export function UUID() { - var f = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; - var str = ""; - for (var i = 0; i < 16; i++) { - var r = _global.parseInt(f.length * Math.random(), 10); + const f = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; + let str = ""; + for (let i = 0; i < 16; i++) { + const r = _global.parseInt(f.length * Math.random(), 10); str += f[r]; } + return str; } @@ -66,58 +69,60 @@ export function createWidgets(items, options, context) { } else { options || (options = {}); } - return map(flatten(items), function (i, item) { - return BI.createWidget(item, deepClone(options), context); - }); + + return map(flatten(items), (i, item) => BI.createWidget(item, deepClone(options), context)); } export function createItems(data, innerAttr, outerAttr) { innerAttr = isArray(innerAttr) ? innerAttr : makeArray(flatten(data).length, innerAttr || {}); outerAttr = isArray(outerAttr) ? outerAttr : makeArray(flatten(data).length, outerAttr || {}); - return map(data, function (i, item) { + + return map(data, (i, item) => { if (isArray(item)) { return createItems(item, innerAttr, outerAttr); } if (item instanceof BI.Widget) { return extend({}, innerAttr.shift(), outerAttr.shift(), { type: null, - el: item + el: item, }); } if (innerAttr[0] instanceof BI.Widget) { outerAttr.shift(); + return extend({}, item, { - el: innerAttr.shift() + el: innerAttr.shift(), }); } if (item.el instanceof BI.Widget) { innerAttr.shift(); + return extend({}, outerAttr.shift(), { type: null }, item); } if (item.el) { return extend({}, outerAttr.shift(), item, { - el: extend({}, innerAttr.shift(), item.el) + el: extend({}, innerAttr.shift(), item.el), }); } + return extend({}, outerAttr.shift(), { - el: extend({}, innerAttr.shift(), item) + el: extend({}, innerAttr.shift(), item), }); }); } // 用容器包装items export function packageItems(items, layouts) { - for (var i = layouts.length - 1; i >= 0; i--) { - items = map(items, function (k, it) { - return extend({}, layouts[i], { - items: [ - extend({}, layouts[i].el, { - el: it - }) - ] - }); - }); - } + for (let i = layouts.length - 1; i >= 0; i--) { + items = map(items, (k, it) => extend({}, layouts[i], { + items: [ + extend({}, layouts[i].el, { + el: it, + }) + ], + })); + } + return items; } @@ -125,8 +130,9 @@ export function formatEL(obj) { if (obj && !obj.type && obj.el) { return obj; } + return { - el: obj + el: obj, }; } @@ -140,13 +146,13 @@ export function trans2Element(widgets) { } // 集合相关方法 -BI._.each(["where", "findWhere", "invoke", "pluck", "shuffle", "sample", "toArray", "size"], function (name) { +BI._.each(["where", "findWhere", "invoke", "pluck", "shuffle", "sample", "toArray", "size"], name => { BI[name] = _apply(name); }); BI._.each([ "get", "set", "each", "map", "reduce", "reduceRight", "find", "filter", "reject", "every", "all", "some", "any", "max", "min", "sortBy", "groupBy", "indexBy", "countBy", "partition", "clamp" -], function (name) { +], name => { if (name === "any") { BI[name] = _applyFunc("some"); } else { @@ -185,12 +191,13 @@ export const clamp = BI.clamp; // 数数 export function count(from, to, predicate) { - var t; + let t; if (predicate) { for (t = from; t < to; t++) { predicate(t); } } + return to - from; } @@ -201,45 +208,51 @@ export function inverse(from, to, predicate) { export function firstKey(obj) { let res = undefined; - any(obj, function (key, value) { + any(obj, (key, value) => { res = key; + return true; }); + return res; } export function lastKey(obj) { let res = undefined; - each(obj, function (key, value) { + each(obj, (key, value) => { res = key; + return true; }); + return res; } export function firstObject(obj) { let res = undefined; - any(obj, function (key, value) { + any(obj, (key, value) => { res = value; + return true; }); + return res; } export function lastObject(obj) { let res = undefined; - each(obj, function (key, value) { + each(obj, (key, value) => { res = value; + return true; }); + return res; } export function concat(obj1, obj2) { if (isKey(obj1)) { - return map([].slice.apply(arguments), function (idx, v) { - return v; - }).join(""); + return map([].slice.apply(arguments), (idx, v) => v).join(""); } if (isArray(obj1)) { return BI._.concat.apply([], arguments); @@ -254,6 +267,7 @@ export function backEach(obj, predicate, context) { for (let index = obj.length - 1; index >= 0; index--) { predicate(index, obj[index], obj); } + return false; } @@ -264,6 +278,7 @@ export function backAny(obj, predicate, context) { return true; } } + return false; } @@ -274,12 +289,14 @@ export function backEvery(obj, predicate, context) { return false; } } + return true; } export function backFindKey(obj, predicate, context) { predicate = iteratee(predicate, context); - let objKeys = keys(obj), key; + const objKeys = keys(obj); + let key; for (let i = objKeys.length - 1; i >= 0; i--) { key = objKeys[i]; if (predicate(obj[key], key, obj)) { @@ -311,7 +328,7 @@ export function remove(obj, target, context) { } } } else { - each(obj, function (i, v) { + each(obj, (i, v) => { if ((targetIsFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!targetIsFunction && contains(target, obj[i]))) { delete obj[i]; } @@ -321,7 +338,8 @@ export function remove(obj, target, context) { export function removeAt(obj, index) { index = isArray(index) ? index : [index]; - let objIsArray = isArray(obj), i; + const objIsArray = isArray(obj); + let i; for (i = 0; i < index.length; i++) { if (objIsArray) { obj[index[i]] = "$deleteIndex"; @@ -343,13 +361,15 @@ export function array2String(array) { } export function abc2Int(string) { - let idx = 0, start = "A", str = string.toUpperCase(); + let idx = 0; + const start = "A", str = string.toUpperCase(); for (let i = 0, len = str.length; i < len; ++i) { idx = str.charAt(i).charCodeAt(0) - start.charCodeAt(0) + 26 * idx + 1; if (idx > (2147483646 - str.charAt(i).charCodeAt(0) + start.charCodeAt(0)) / 26) { return 0; } } + return idx; } @@ -367,6 +387,7 @@ export function int2Abc(num) { str = DIGITS[t - 1] + str; idx = (idx - t) / 26; } + return str; } @@ -374,10 +395,10 @@ export function int2Abc(num) { BI._.each([ "first", "initial", "last", "rest", "compact", "flatten", "without", "union", "intersection", "difference", "zip", "unzip", "object", "indexOf", "lastIndexOf", "sortedIndex", "range", "take", "takeRight", "uniqBy" -], function (name) { +], name => { BI[name] = _apply(name); }); -BI._.each(["findIndex", "findLastIndex"], function (name) { +BI._.each(["findIndex", "findLastIndex"], name => { BI[name] = _applyFunc(name); }); export const first = BI.first; @@ -405,7 +426,7 @@ export const findLastIndex = BI.findLastIndex; // 构建一个长度为length的数组 export function makeArray(length, value) { - let res = []; + const res = []; for (let i = 0; i < length; i++) { if (isNull(value)) { res.push(i); @@ -413,11 +434,12 @@ export function makeArray(length, value) { res.push(deepClone(value)); } } + return res; } export function makeObject(array, value) { - let map = {}; + const map = {}; for (let i = 0; i < array.length; i++) { if (isNull(value)) { map[array[i]] = array[i]; @@ -427,11 +449,12 @@ export function makeObject(array, value) { map[array[i]] = deepClone(value); } } + return map; } export function makeArrayByArray(array, value) { - let res = []; + const res = []; if (!array) { return res; } @@ -442,11 +465,12 @@ export function makeArrayByArray(array, value) { res.push(deepClone(value)); } } + return res; } export function uniq(array, isSorted, iteratee, context) { - if (array == null) { + if (array === null) { return []; } if (!isBoolean(isSorted)) { @@ -455,7 +479,8 @@ export function uniq(array, isSorted, iteratee, context) { isSorted = false; } iteratee && (iteratee = traverse(iteratee, context)); - return uniq.call(BI._, array, isSorted, iteratee, context); + + return BI._uniq.call(BI._, array, isSorted, iteratee, context); } // 对象相关方法 @@ -464,7 +489,7 @@ BI._.each([ "defaults", "clone", "property", "propertyOf", "matcher", "isEqual", "isMatch", "isEmpty", "isElement", "isNumber", "isString", "isArray", "isObject", "isPlainObject", "isArguments", "isFunction", "isFinite", "isBoolean", "isDate", "isRegExp", "isError", "isNaN", "isUndefined", "zipObject", "cloneDeep" -], function (name) { +], name => { BI[name] = _apply(name); }); export const keys = BI.keys; @@ -502,7 +527,7 @@ export const isUndefined = BI.isUndefined; export const zipObject = BI.zipObject; export const cloneDeep = BI.cloneDeep; -BI._.each(["mapObject", "findKey", "pick", "omit", "tap"], function (name) { +BI._.each(["mapObject", "findKey", "pick", "omit", "tap"], name => { BI[name] = _applyFunc(name); }); export const mapObject = BI.mapObject; @@ -512,17 +537,18 @@ export const omit = BI.omit; export const tap = BI.tap; export function inherit(sp, overrides) { - let sb = function () { + function sb () { return sp.apply(this, arguments); - }; - let F = function () { - }, spp = sp.prototype; + } + function F () {} + const spp = sp.prototype; F.prototype = spp; sb.prototype = new F(); sb.superclass = spp; extend(sb.prototype, overrides, { - superclass: sp + superclass: sp, }); + return sb; } @@ -542,11 +568,11 @@ export function has(obj, keys) { if (keys.length === 0) { return false; } - return every(keys, function (i, key) { - return BI._.has(obj, key); - }); + + return every(keys, (i, key) => BI._.has(obj, key)); } - return BI._.has.apply(BI._, arguments); + + return BI._.has(...arguments); } export function freeze(value) { @@ -555,6 +581,7 @@ export function freeze(value) { if (Object.freeze && isObject(value)) { return Object.freeze(value); } + return value; } @@ -565,8 +592,9 @@ export function isKey(key) { // 忽略大小写的等于 export function isCapitalEqual(a, b) { - a = isNull(a) ? a : ("" + a).toLowerCase(); - b = isNull(b) ? b : ("" + b).toLowerCase(); + a = isNull(a) ? a : (`${a}`).toLowerCase(); + b = isNull(b) ? b : (`${b}`).toLowerCase(); + return isEqual(a, b); } @@ -603,7 +631,7 @@ export function isNotEmptyObject(obj) { } export function isWindow(obj) { - return obj != null && obj == obj.window; + return obj !== null && obj === obj.window; } export function isPromise(obj) { @@ -614,8 +642,8 @@ export const deepClone = BI._.cloneDeep; export const deepExtend = BI._.deepExtend; export function isDeepMatch(object, attrs) { - let attrsKeys = keys(attrs), length = attrsKeys.length; - if (object == null) { + const attrsKeys = keys(attrs), length = attrsKeys.length; + if (object === null) { return !length; } const obj = Object(object); @@ -625,11 +653,13 @@ export function isDeepMatch(object, attrs) { return false; } } + return true; } export function contains(obj, target, fromIndex) { if (!BI._.isArrayLike(obj)) obj = values(obj); + return indexOf(obj, target, typeof fromIndex === "number" && fromIndex) >= 0; } @@ -637,6 +667,7 @@ export function deepContains(obj, copy) { if (isObject(copy)) { return any(obj, (i, v) => isEqual(v, copy)); } + return contains(obj, copy); } @@ -646,6 +677,7 @@ export function deepIndexOf(obj, target) { return i; } } + return -1; } @@ -667,35 +699,39 @@ export function deepRemove(obj, target) { } }); } + return done; } export function deepWithout(obj, target) { if (isArray(obj)) { - let result = []; + const result = []; for (let i = 0; i < obj.length; i++) { if (!isEqual(target, obj[i])) { result.push(obj[i]); } } + return result; } - let result = {}; + const result = {}; each(obj, (i, v) => { if (!isEqual(target, obj[i])) { result[i] = v; } }); + return result; } export function deepUnique(array) { - let result = []; + const result = []; each(array, (i, item) => { if (!deepContains(result, item)) { result.push(item); } }); + return result; } @@ -703,9 +739,9 @@ export function deepUnique(array) { export function deepDiff(object, other) { object || (object = {}); other || (other = {}); - let result = []; - let used = []; - for (let b in object) { + const result = []; + const used = []; + for (const b in object) { if (has(object, b)) { if (!isEqual(object[b], other[b])) { result.push(b); @@ -713,19 +749,18 @@ export function deepDiff(object, other) { used.push(b); } } - for (let b in other) { + for (const b in other) { if (has(other, b) && !contains(used, b)) { result.push(b); } } + return result; } // 通用方法 -BI._.each(["uniqueId", "result", "chain", "iteratee", "unescape", "before", "after", "chunk"], function (name) { - BI[name] = function () { - return BI._[name].apply(BI._, arguments); - }; +BI._.each(["uniqueId", "result", "chain", "iteratee", "unescape", "before", "after", "chunk"], name => { + BI[name] = (...args) => BI._[name](...args); }); export const uniqueId = BI.uniqueId; export const result = BI.result; @@ -737,10 +772,8 @@ export const after = BI.after; export const chunk = BI.chunk; // 事件相关方法 -BI._.each(["bind", "once", "partial", "debounce", "throttle", "delay", "defer", "wrap"], function (name) { - BI[name] = function () { - return BI._[name].apply(BI._, arguments); - }; +BI._.each(["bind", "once", "partial", "debounce", "throttle", "delay", "defer", "wrap"], name => { + BI[name] = (...args) => BI._[name](...args); }); export const bind = BI.bind; export const once = BI.once; @@ -752,13 +785,13 @@ export const defer = BI.defer; export const wrap = BI.wrap; export const nextTick = (function () { - let callbacks = []; + const callbacks = []; let pending = false; let timerFunc = void 0; function nextTickHandler() { pending = false; - let copies = callbacks.slice(0); + const copies = callbacks.slice(0); callbacks.length = 0; for (let i = 0; i < copies.length; i++) { copies[i](); @@ -766,16 +799,16 @@ export const nextTick = (function () { } if (typeof Promise !== "undefined") { - let p = Promise.resolve(); + const p = Promise.resolve(); timerFunc = function timerFunc() { p.then(nextTickHandler); }; } else if (typeof MutationObserver !== "undefined") { let counter = 1; - let observer = new MutationObserver(nextTickHandler); - let textNode = document.createTextNode(String(counter)); + const observer = new MutationObserver(nextTickHandler); + const textNode = document.createTextNode(String(counter)); observer.observe(textNode, { - characterData: true + characterData: true, }); timerFunc = function timerFunc() { counter = (counter + 1) % 2; @@ -794,16 +827,16 @@ export const nextTick = (function () { return function queueNextTick(cb) { let _resolve = void 0; - let args = [].slice.call(arguments, 1); - callbacks.push(function () { + const args = [].slice.call(arguments, 1); + callbacks.push(() => { if (cb) { try { - cb.apply(null, args); + cb(...args); } catch (e) { console.error(e); } } else if (_resolve) { - _resolve.apply(null, args); + _resolve(...args); } }); if (!pending) { @@ -811,16 +844,16 @@ export const nextTick = (function () { timerFunc(); } // $flow-disable-line - if (!cb && typeof Promise !== 'undefined') { - return new Promise(function (resolve, reject) { + if (!cb && typeof Promise !== "undefined") { + return new Promise(((resolve, reject) => { _resolve = resolve; - }); + })); } }; -})(); +}()); // 数字相关方法 -BI._.each(["random"], function (name) { +BI._.each(["random"], name => { BI[name] = _apply(name); }); export const random = BI.random; @@ -833,13 +866,13 @@ export function parseInt(number) { try { return _global.parseInt(number, radix); } catch (e) { - throw new Error(number + "parse int error"); - return NaN; + throw new Error(`${number}parse int error`); } } export function parseSafeInt(value) { - let MAX_SAFE_INTEGER = 9007199254740991; + const MAX_SAFE_INTEGER = 9007199254740991; + return value ? clamp(parseInt(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) : (value === 0 ? value : 0); @@ -849,8 +882,7 @@ export function parseFloat(number) { try { return _global.parseFloat(number); } catch (e) { - throw new Error(number + "parse float error"); - return NaN; + throw new Error(`${number}parse float error`); } } @@ -863,11 +895,11 @@ export function isPositiveInteger(number) { } export function isNegativeInteger(number) { - return /^\-[1-9][0-9]*$/.test(number); + return /^-[1-9][0-9]*$/.test(number); } export function isInteger(number) { - return /^\-?\d+$/.test(number); + return /^-?\d+$/.test(number); } export function isNumeric(number) { @@ -882,6 +914,7 @@ export function isOdd(number) { if (!isInteger(number)) { return false; } + return (number & 1) === 1; } @@ -889,6 +922,7 @@ export function isEven(number) { if (!isInteger(number)) { return false; } + return (number & 1) === 0; } @@ -901,24 +935,26 @@ export function sum(array, iteratee, context) { sum += Number(item); } }); + return sum; } export function average(array, iteratee, context) { const sumResult = sum(array, iteratee, context); + return sumResult / array.length; } -export function trim() { - return BI._.trim.apply(BI._, arguments); +export function trim(...args) { + return BI._.trim(...args); } export function toUpperCase(string) { - return (string + "").toLocaleUpperCase(); + return (`${string}`).toLocaleUpperCase(); } export function toLowerCase(string) { - return (string + "").toLocaleLowerCase(); + return (`${string}`).toLocaleLowerCase(); } export function isEndWithBlank(string) { @@ -926,12 +962,13 @@ export function isEndWithBlank(string) { } export function isLiteral(exp) { - return /^\s?(true|false|-?[\d\.]+|'[^']*'|"[^"]*")\s?$/.test(exp); + return /^\s?(true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/.test(exp); } export function stripQuotes(str) { const a = str.charCodeAt(0); const b = str.charCodeAt(str.length - 1); + return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str; @@ -964,9 +1001,9 @@ export function isEmptyString(str) { */ export function encrypt(type, text, key) { switch (type) { - case BI.CRYPT_TYPE.AES: - default: - return BI.aesEncrypt(text, key); + case BI.CRYPT_TYPE.AES: + default: + return BI.aesEncrypt(text, key); } } @@ -979,9 +1016,9 @@ export function encrypt(type, text, key) { */ export function decrypt(type, text, key) { switch (type) { - case BI.CRYPT_TYPE.AES: - default: - return BI.aesDecrypt(text, key); + case BI.CRYPT_TYPE.AES: + default: + return BI.aesDecrypt(text, key); } } @@ -1015,6 +1052,7 @@ export function leftPad(val, size, ch) { while (result.length < size) { result = ch + result; } + return result.toString(); } @@ -1030,7 +1068,8 @@ export function leftPad(val, size, ch) { * @return {String} 做了替换后的字符串 */ export function format(format) { - var args = Array.prototype.slice.call(arguments, 1); + const args = Array.prototype.slice.call(arguments, 1); + return format.replace(/\{(\d+)\}/g, (m, i) => args[i]); } @@ -1065,25 +1104,26 @@ export function checkDateVoid(YY, MM, DD, minDate, maxDate) { } else if (YY > maxDate[0]) { back = ["y", 1]; } else if (YY >= minDate[0] && YY <= maxDate[0]) { - if (YY == minDate[0]) { + if (YY === minDate[0]) { if (MM < minDate[1]) { back = ["m"]; - } else if (MM == minDate[1]) { + } else if (MM === minDate[1]) { if (DD < minDate[2]) { back = ["d"]; } } } - if (YY == maxDate[0]) { + if (YY === maxDate[0]) { if (MM > maxDate[1]) { back = ["m", 1]; - } else if (MM == maxDate[1]) { + } else if (MM === maxDate[1]) { if (DD > maxDate[2]) { back = ["d", 1]; } } } } + return back; } @@ -1096,8 +1136,9 @@ export function checkDateLegal(str) { if (ar.length <= 2) { return MM >= 1 && MM <= 12; } - let MD = BI.Date._MD.slice(0); + const MD = BI.Date._MD.slice(0); MD[1] = isLeapYear(YY) ? 29 : 28; + return MM >= 1 && MM <= 12 && DD <= MD[MM - 1]; } @@ -1114,74 +1155,75 @@ export function parseDateTime(str, fmt) { let m; let d; // wei : 对于fmt为‘YYYYMM’或者‘YYYYMMdd’的格式,str的值为类似'201111'的形式,因为年月之间没有分隔符,所以正则表达式分割无效,导致bug7376。 - let a = str.split(/\W+/); - if (fmt.toLowerCase() == "%y%x" || fmt.toLowerCase() == "%y%x%d") { - let yearlength = 4; - let otherlength = 2; + const a = str.split(/\W+/); + if (fmt.toLowerCase() === "%y%x" || fmt.toLowerCase() === "%y%x%d") { + const yearlength = 4; + const otherlength = 2; a[0] = str.substring(0, yearlength); a[1] = str.substring(yearlength, yearlength + otherlength); a[2] = str.substring(yearlength + otherlength, yearlength + otherlength * 2); } - let b = fmt.match(/%./g); + const b = fmt.match(/%./g); let i = 0, j = 0; let hr = 0; let min = 0; let sec = 0; for (i = 0; i < a.length; ++i) { switch (b[i]) { - case "%d": - case "%e": - d = _global.parseInt(a[i], 10); - break; - - case "%X": - m = _global.parseInt(a[i], 10) - 1; - break; - case "%x": - m = _global.parseInt(a[i], 10) - 1; - break; - - case "%Y": - case "%y": - y = _global.parseInt(a[i], 10); - (y < 100) && (y += (y > 29) ? 1900 : 2000); - break; - - case "%b": - case "%B": - for (j = 0; j < 12; ++j) { - if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { - m = j; - break; - } - } - break; - - case "%H": - case "%I": - case "%k": - case "%l": - hr = _global.parseInt(a[i], 10); - break; - - case "%P": - case "%p": - if (/pm/i.test(a[i]) && hr < 12) { - hr += 12; - } else if (/am/i.test(a[i]) && hr >= 12) { - hr -= 12; + case "%d": + case "%e": + d = _global.parseInt(a[i], 10); + break; + + case "%X": + m = _global.parseInt(a[i], 10) - 1; + break; + case "%x": + m = _global.parseInt(a[i], 10) - 1; + break; + + case "%Y": + case "%y": + y = _global.parseInt(a[i], 10); + (y < 100) && (y += (y > 29) ? 1900 : 2000); + break; + + case "%b": + case "%B": + for (j = 0; j < 12; ++j) { + if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() === a[i].toLowerCase()) { + m = j; + break; } - break; - case "%Q": - case "%q": - m = (_global.parseInt(a[i], 10) - 1) * 3; - break; - case "%M": - min = _global.parseInt(a[i], 10); - break; - case "%S": - sec = _global.parseInt(a[i], 10); - break; + } + break; + + case "%H": + case "%I": + case "%k": + case "%l": + hr = _global.parseInt(a[i], 10); + break; + + case "%P": + case "%p": + if (/pm/i.test(a[i]) && hr < 12) { + hr += 12; + } else if (/am/i.test(a[i]) && hr >= 12) { + hr -= 12; + } + break; + case "%Q": + case "%q": + m = (_global.parseInt(a[i], 10) - 1) * 3; + break; + case "%M": + min = _global.parseInt(a[i], 10); + break; + case "%S": + sec = _global.parseInt(a[i], 10); + break; + default: } } // if (!a[i]) { @@ -1205,45 +1247,46 @@ export function parseDateTime(str, fmt) { if (isNaN(sec)) { sec = today.getSeconds(); } - if (y != 0) { + if (y !== 0) { return BI.getDate(y, m, d, hr, min, sec); } y = 0; m = -1; d = 0; for (i = 0; i < a.length; ++i) { - if (a[i].search(/[a-zA-Z]+/) != -1) { + if (a[i].search(/[a-zA-Z]+/) !== -1) { let t = -1; for (j = 0; j < 12; ++j) { - if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { + if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() === a[i].toLowerCase()) { t = j; break; } } - if (t != -1) { - if (m != -1) { + if (t !== -1) { + if (m !== -1) { d = m + 1; } m = t; } - } else if (_global.parseInt(a[i], 10) <= 12 && m == -1) { + } else if (_global.parseInt(a[i], 10) <= 12 && m === -1) { m = a[i] - 1; - } else if (_global.parseInt(a[i], 10) > 31 && y == 0) { + } else if (_global.parseInt(a[i], 10) > 31 && y === 0) { y = _global.parseInt(a[i], 10); (y < 100) && (y += (y > 29) ? 1900 : 2000); - } else if (d == 0) { + } else if (d === 0) { d = a[i]; } } - if (y == 0) { + if (y === 0) { y = today.getFullYear(); } if (m === -1) { m = today.getMonth(); } - if (m != -1 && d != 0) { + if (m !== -1 && d !== 0) { return BI.getDate(y, m, d, hr, min, sec); } + return today; } @@ -1251,49 +1294,51 @@ export function getDate(...args) { const length = args.length; let dt; switch (length) { - // new Date() - case 0: - dt = new Date(); - break; + // new Date() + case 0: + dt = new Date(); + break; // new Date(long) - case 1: - dt = new Date(args[0]); - break; + case 1: + dt = new Date(args[0]); + break; // new Date(year, month) - case 2: - dt = new Date(args[0], args[1]); - break; + case 2: + dt = new Date(args[0], args[1]); + break; // new Date(year, month, day) - case 3: - dt = new Date(args[0], args[1], args[2]); - break; + case 3: + dt = new Date(args[0], args[1], args[2]); + break; // new Date(year, month, day, hour) - case 4: - dt = new Date(args[0], args[1], args[2], args[3]); - break; + case 4: + dt = new Date(args[0], args[1], args[2], args[3]); + break; // new Date(year, month, day, hour, minute) - case 5: - dt = new Date(args[0], args[1], args[2], args[3], args[4]); - break; + case 5: + dt = new Date(args[0], args[1], args[2], args[3], args[4]); + break; // new Date(year, month, day, hour, minute, second) - case 6: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); - break; + case 6: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); + break; // new Date(year, month, day, hour, minute, second, millisecond) - case 7: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - break; - default: - dt = new Date(); - break; + case 7: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + break; + default: + dt = new Date(); + break; } if (isNotNull(BI.timeZone) && (arguments.length === 0 || (arguments.length === 1 && isNumber(arguments[0])))) { const localTime = dt.getTime(); // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 const localOffset = dt.getTimezoneOffset() * 60000; // 获得当地时间偏移的毫秒数 const utc = localTime + localOffset; // utc即GMT时间标准时区 + return new Date(utc + BI.timeZone);// + Pool.timeZone.offset); } + return dt; } @@ -1302,46 +1347,47 @@ export function getTime() { const args = arguments; let dt; switch (length) { - // new Date() - case 0: - dt = new Date(); - break; + // new Date() + case 0: + dt = new Date(); + break; // new Date(long) - case 1: - dt = new Date(args[0]); - break; + case 1: + dt = new Date(args[0]); + break; // new Date(year, month) - case 2: - dt = new Date(args[0], args[1]); - break; + case 2: + dt = new Date(args[0], args[1]); + break; // new Date(year, month, day) - case 3: - dt = new Date(args[0], args[1], args[2]); - break; + case 3: + dt = new Date(args[0], args[1], args[2]); + break; // new Date(year, month, day, hour) - case 4: - dt = new Date(args[0], args[1], args[2], args[3]); - break; + case 4: + dt = new Date(args[0], args[1], args[2], args[3]); + break; // new Date(year, month, day, hour, minute) - case 5: - dt = new Date(args[0], args[1], args[2], args[3], args[4]); - break; + case 5: + dt = new Date(args[0], args[1], args[2], args[3], args[4]); + break; // new Date(year, month, day, hour, minute, second) - case 6: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); - break; + case 6: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); + break; // new Date(year, month, day, hour, minute, second, millisecond) - case 7: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - break; - default: - dt = new Date(); - break; + case 7: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + break; + default: + dt = new Date(); + break; } if (isNotNull(BI.timeZone)) { // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 return dt.getTime() - BI.timeZone - new Date().getTimezoneOffset() * 60000; } + return dt.getTime(); } diff --git a/src/core/3.ob.js b/src/core/3.ob.js index fcd9db92a..8357389fd 100644 --- a/src/core/3.ob.js +++ b/src/core/3.ob.js @@ -1,7 +1,8 @@ import { isFunction, isArray, isObject, isArguments, reduce, bind } from "./2.base"; function obExtend() { - let target = arguments[0] || {}, length = arguments.length, i = 1, name, copy; + const target = arguments[0] || {}, length = arguments.length; + let i = 1, name, copy; for (; i < length; i++) { // Only deal with non-null/undefined values const options = arguments[i]; @@ -53,9 +54,7 @@ export class OB { props = this.props(config); } const defaultProps = obExtend(this._defaultConfig(config), props); - const modifiedDefaultProps = (config && config.type && OB.configFunctions[config.type + ".props"]) ? reduce(OB.configFunctions[config.type + ".props"], function (value, conf, index) { - return obExtend(conf, value.fn(defaultProps, config, value.opt)); - }, {}) : null; + const modifiedDefaultProps = (config && config.type && OB.configFunctions[`${config.type}.props`]) ? reduce(OB.configFunctions[`${config.type}.props`], (value, conf, index) => obExtend(conf, value.fn(defaultProps, config, value.opt)), {}) : null; this.options = obExtend(defaultProps, modifiedDefaultProps, config); } @@ -73,7 +72,7 @@ export class OB { return; } if (isArray(lis)) { - BI._.each(lis, (l) => { + BI._.each(lis, l => { this.on(eventName, l); }); @@ -162,7 +161,7 @@ export class OB { const fns = this._getEvents()[eventName]; if (isArray(fns)) { const newFns = []; - BI._.each(fns, function (ifn) { + BI._.each(fns, ifn => { if (ifn !== fn) { newFns.push(ifn); } diff --git a/src/core/4.widget.js b/src/core/4.widget.js index e67bdb4dc..11faacc6e 100644 --- a/src/core/4.widget.js +++ b/src/core/4.widget.js @@ -30,7 +30,7 @@ function callLifeHook(self, life) { if (hook) { hooks = hooks.concat(isArray(hook) ? hook : [hook]); } - each(hooks, function (i, hook) { + each(hooks, (i, hook) => { hook.call(self); }); } @@ -53,7 +53,7 @@ export class Widget extends OB { baseCls: "", extraCls: "", cls: "", - css: null + css: null, // vdom: false }); @@ -132,6 +132,7 @@ export class Widget extends OB { // 加个保险 if (initCallbackCalled === true) { _global.console && console.error("组件: 请检查beforeInit内部的写法,callback只能执行一次"); + return; } initCallbackCalled = true; @@ -140,18 +141,19 @@ export class Widget extends OB { // 加个保险 if (renderCallbackCalled === true) { _global.console && console.error("组件: 请检查beforeRender内部的写法,callback只能执行一次"); + return; } renderCallbackCalled = true; this._render(); this.__afterRender(); - } + }; if (this.options.beforeRender || this.beforeRender) { this.__async = true; const beforeRenderResult = (this.options.beforeRender || this.beforeRender).call(this, render); if (beforeRenderResult instanceof Promise) { - beforeRenderResult.then(render).catch(function (e) { + beforeRenderResult.then(render).catch(e => { _global.console && console.error(e); render(); }); @@ -160,13 +162,13 @@ export class Widget extends OB { this._render(); this.__afterRender(); } - } + }; if (this.options.beforeInit || this.beforeInit) { this.__asking = true; const beforeInitResult = (this.options.beforeInit || this.beforeInit).call(this, init); if (beforeInitResult instanceof Promise) { - beforeInitResult.then(init).catch(function (e) { + beforeInitResult.then(init).catch(e => { _global.console && console.error(e); init(); }); @@ -206,11 +208,11 @@ export class Widget extends OB { this._initElementWidth(); this._initElementHeight(); if (o._baseCls || o.baseCls || o.extraCls) { - this.element.addClass((o._baseCls || "") + " " + (o.baseCls || "") + " " + (o.extraCls || "")); + this.element.addClass(`${o._baseCls || ""} ${o.baseCls || ""} ${o.extraCls || ""}`); } if (o.cls) { if (isFunction(o.cls)) { - const cls = this.__watch(o.cls, (context, newValue) => { + let cls = this.__watch(o.cls, (context, newValue) => { this.element.removeClass(cls).addClass(cls = newValue); }); this.element.addClass(cls); @@ -229,7 +231,7 @@ export class Widget extends OB { } if (o.css) { if (isFunction(o.css)) { - const css = this.__watch(o.css, (context, newValue) => { + let css = this.__watch(o.css, (context, newValue) => { for (const k in css) { if (isNull(newValue[k])) { newValue[k] = ""; @@ -247,14 +249,13 @@ export class Widget extends OB { __watch(getter, handler, options) { if (_global.Fix) { this._watchers = this._watchers || []; - const watcher = new Fix.Watcher(null, () => { - return getter.call(this, this); - }, (handler && ((v) => { + const watcher = new Fix.Watcher(null, () => getter.call(this, this), (handler && (v => { handler.call(this, this, v); })) || BI.emptyFn, extend({ deep: true }, options)); this._watchers.push(() => { watcher.teardown(); }); + return watcher.value; } else { return getter(); @@ -374,7 +375,7 @@ export class Widget extends OB { each(els, (i, el) => { if (el) { _lazyCreateWidget(el, { - element: this + element: this, }); } }); @@ -422,6 +423,7 @@ export class Widget extends OB { this.__afterMount(lifeHook, predicate); // }, 0); } + return true; } @@ -444,10 +446,12 @@ export class Widget extends OB { _update(nextProps, shouldUpdate) { callLifeHook(this, "beforeUpdate"); + let res; if (shouldUpdate) { - const res = this.update && this.update(nextProps, shouldUpdate); + res = this.update && this.update(nextProps, shouldUpdate); } callLifeHook(this, "updated"); + return res; } @@ -476,7 +480,7 @@ export class Widget extends OB { this.options._disabled = true; } // 递归将所有子组件使能 - each(this._children, function (i, child) { + each(this._children, (i, child) => { !child._manualSetEnable && child._setEnable && child._setEnable(enable); }); } @@ -488,7 +492,7 @@ export class Widget extends OB { this.options._invalid = true; } // 递归将所有子组件使有效 - each(this._children, function (i, child) { + each(this._children, (i, child) => { !child._manualSetValid && child._setValid && child._setValid(valid); }); } @@ -525,36 +529,36 @@ export class Widget extends OB { this.__setElementVisible(true); this._mount(); if (o.animation && !lastVisible) { - this.element.removeClass(o.animation + "-leave").removeClass(o.animation + "-leave-active").addClass(o.animation + "-enter"); + this.element.removeClass(`${o.animation}-leave`).removeClass(`${o.animation}-leave-active`).addClass(`${o.animation}-enter`); if (this._requestAnimationFrame) { cancelAnimationFrame(this._requestAnimationFrame); } this._requestAnimationFrame = () => { - this.element.addClass(o.animation + "-enter-active"); + this.element.addClass(`${o.animation}-enter-active`); }; requestAnimationFrame(this._requestAnimationFrame); if (this._animationDuring) { clearTimeout(this._animationDuring); } this._animationDuring = setTimeout(() => { - this.element.removeClass(o.animation + "-enter").removeClass(o.animation + "-enter-active"); + this.element.removeClass(`${o.animation}-enter`).removeClass(`${o.animation}-enter-active`); }, o.animationDuring); } } else if (visible === false) { if (o.animation && lastVisible) { - this.element.removeClass(o.animation + "-enter").removeClass(o.animation + "-enter-active").addClass(o.animation + "-leave"); + this.element.removeClass(`${o.animation}-enter`).removeClass(`${o.animation}-enter-active`).addClass(`${o.animation}-leave`); if (this._requestAnimationFrame) { cancelAnimationFrame(this._requestAnimationFrame); } this._requestAnimationFrame = () => { - this.element.addClass(o.animation + "-leave-active"); + this.element.addClass(`${o.animation}-leave-active`); }; requestAnimationFrame(this._requestAnimationFrame); if (this._animationDuring) { clearTimeout(this._animationDuring); } this._animationDuring = setTimeout(() => { - this.element.removeClass(o.animation + "-leave").removeClass(o.animation + "-leave-active"); + this.element.removeClass(`${o.animation}-leave`).removeClass(`${o.animation}-leave-active`); this.__setElementVisible(false); }, o.animationDuring); } else { @@ -582,8 +586,8 @@ export class Widget extends OB { doBehavior() { const args = arguments; // 递归将所有子组件使有效 - each(this._children, function (i, child) { - child.doBehavior && child.doBehavior.apply(child, args); + each(this._children, (i, child) => { + child.doBehavior && child.doBehavior(...args); }); } @@ -602,7 +606,7 @@ export class Widget extends OB { name = widget.getName(); } if (isKey(name)) { - name = name + ""; + name = `${name}`; } name = name || widget.getName() || uniqueId("widget"); if (this._children[name]) { @@ -613,6 +617,7 @@ export class Widget extends OB { // TODO: self待删 remove(self._children, this); }); + return (this._children[name] = widget); } @@ -620,20 +625,21 @@ export class Widget extends OB { if (!isKey(name) || name === this.getName()) { return this; } - name = name + ""; - let widget = void 0, other = {}; - any(this._children, function (i, wi) { + name = `${name}`; + let widget = void 0; + const other = {}; + any(this._children, (i, wi) => { if (i === name) { widget = wi; + return true; } other[i] = wi; }); if (!widget) { - any(other, function (i, wi) { - return (widget = wi.getWidgetByName(i)); - }); + any(other, (i, wi) => (widget = wi.getWidgetByName(i))); } + return widget; } @@ -646,7 +652,7 @@ export class Widget extends OB { } hasWidget(name) { - return this._children[name] != null; + return isNotNull(this._children[name]); } getName() { @@ -664,11 +670,13 @@ export class Widget extends OB { attr(key, value) { if (isPlainObject(key)) { each(key, (k, v) => this.attr(k, v)); + return; } if (isNotNull(value)) { - return this.options[key] = value; + this.options[key] = value; } + return this.options[key]; } @@ -729,7 +737,7 @@ export class Widget extends OB { } __d() { - each(this._children, function (i, widget) { + each(this._children, (i, widget) => { widget && widget._unMount && widget._unMount(); }); this._children = {}; @@ -747,7 +755,6 @@ export class Widget extends OB { this.destroyed = null; this._isDestroyed = true; // this._purgeRef(); // 清除ref的时机还是要仔细考虑一下 - } _unMount() { @@ -767,7 +774,7 @@ export class Widget extends OB { _empty () { this._assetMounted(); - each(this._children, function (i, widget) { + each(this._children, (i, widget) => { widget && widget._unMount && widget._unMount(); }); this._children = {}; @@ -801,9 +808,9 @@ export class Widget extends OB { // this.purgeListeners(); // 去掉组件绑定的watcher - each(this._watchers, function (i, unwatches) { + each(this._watchers, (i, unwatches) => { unwatches = isArray(unwatches) ? unwatches : [unwatches]; - each(unwatches, function (j, unwatch) { + each(unwatches, (j, unwatch) => { unwatch(); }); }); @@ -839,7 +846,7 @@ export class Widget extends OB { this._purgeRef(); this.purgeListeners(); } -}; +} let context = null, current = null; const contextStack = [], currentStack = []; @@ -882,35 +889,42 @@ export function useStore(_store) { } if (current) { const currentStore = current._store; - let delegate = {}, origin; + const delegate = {}; + let origin; if (_global.Proxy) { const proxy = new Proxy(delegate, { - get: function (target, key) { + get (target, key) { return Reflect.get(origin, key); }, - set: function (target, key, value) { + set (target, key, value) { return Reflect.set(origin, key, value); - } + }, }); current._store = function () { origin = (_store || currentStore).apply(this, arguments); delegate.$delegate = origin; + return origin; }; - return current.$storeDelegate = proxy; + current.$storeDelegate = proxy; + + return current.$storeDelegate; } current._store = function () { const st = (_store || currentStore).apply(this, arguments); extend(delegate, st); + return st; }; - return current.$storeDelegate = delegate; + current.$storeDelegate = delegate; + + return current.$storeDelegate; } } export function useContext(inject) { // 通过组件找最近的store - const vm = Widget.findStore(Widget.current || Widget.context); + let vm = Widget.findStore(Widget.current || Widget.context); if (vm) { if (inject) { if (vm.$$computed && inject in vm.$$computed) { @@ -928,9 +942,11 @@ export function useContext(inject) { } vm = vm._parent; } + return null; } } + return vm; } @@ -949,18 +965,19 @@ export function watch(vm, watch, handler) { if (isArray(handler)) { for (let i = 0; i < handler.length; i++) { watchers.push(Fix.watch(vm.model, key, innerHandler, { - store: vm + store: vm, })); } } else { watchers.push(Fix.watch(vm.model, key, innerHandler, { - store: vm + store: vm, })); } } // vm中一定有_widget Widget.current._watchers || (Widget.current._watchers = []); Widget.current._watchers = Widget.current._watchers.concat(watchers); + return; } handler = watch; @@ -974,6 +991,7 @@ export function onBeforeMount(beforeMount) { if (current) { if (current.__isMounting) { beforeMount(); + return; } if (!current.beforeMount) { @@ -989,6 +1007,7 @@ export function onMounted(mounted) { if (current) { if (current._isMounted && !this.__async) { mounted(); + return; } if (!current.mounted) { @@ -998,7 +1017,7 @@ export function onMounted(mounted) { } current.mounted.push(mounted); } -}; +} export function onBeforeUnmount(beforeDestroy) { if (current) { @@ -1026,7 +1045,7 @@ Widget.registerRenderEngine = function (engine) { Widget._renderEngine = engine; }; Widget.registerRenderEngine({ - createElement: function (widget) { + createElement (widget) { if (isWidget(widget)) { const o = widget.options; if (o.element) { @@ -1035,13 +1054,15 @@ Widget.registerRenderEngine({ if (o.tagName) { return BI.$(document.createElement(o.tagName)); } + return BI.$(document.createDocumentFragment()); } + return BI.$(widget); }, - createFragment: function () { + createFragment () { return document.createDocumentFragment(); - } + }, }); export function mount(widget, container, predicate, hydrate) { @@ -1049,8 +1070,8 @@ export function mount(widget, container, predicate, hydrate) { // 将widget的element元素都挂载好,并建立相互关系 widget.element.data("__widgets", [widget]); const res = widget._mount(true, false, false, function (w) { - each(w._children, function (i, child) { - const ws = child.element.data("__widgets"); + each(w._children, (i, child) => { + let ws = child.element.data("__widgets"); if (!ws) { ws = []; } @@ -1063,19 +1084,21 @@ export function mount(widget, container, predicate, hydrate) { const c = Widget._renderEngine.createElement; BI.DOM.patchProps(widget.element, c(c(container).children()[0])); - const triggerLifeHook = function (w) { + const triggerLifeHook = w => { w.beforeMount && w.beforeMount(); w.mounted && w.mounted(); - each(w._children, function (i, child) { + each(w._children, (i, child) => { triggerLifeHook(child); }); }; // 最后触发组件树生命周期函数 triggerLifeHook(widget); + return res; } if (container) { Widget._renderEngine.createElement(container).append(widget.element); } + return widget._mount(true, false, false, predicate); } diff --git a/src/core/5.inject.js b/src/core/5.inject.js index 77faa02f3..8a54bbeb7 100644 --- a/src/core/5.inject.js +++ b/src/core/5.inject.js @@ -1,19 +1,19 @@ import { isFunction, isNull, isNotNull, isArray, each, isWidget, extend, init, isEmpty, remove } from "./2.base"; import { OB } from "./3.ob"; -import { Widget } from "./4.widget" +import { Widget } from "./4.widget"; -let moduleInjection = {}, moduleInjectionMap = { +const moduleInjection = {}, moduleInjectionMap = { components: {}, constants: {}, stores: {}, services: {}, models: {}, - providers: {} + providers: {}, }; export function module(xtype, cls) { - if (moduleInjection[xtype] != null) { - _global.console && console.error("module: [" + xtype + "] 已经注册过了"); + if (isNotNull(moduleInjection[xtype])) { + _global.console && console.error(`module: [${xtype}] 已经注册过了`); } else { if (isFunction(cls)) { cls = cls(); @@ -29,7 +29,7 @@ export function module(xtype, cls) { } moduleInjectionMap[k][key].push({ version: cls[k][key], - moduleId: xtype + moduleId: xtype, }); } } @@ -40,10 +40,10 @@ export function module(xtype, cls) { return () => Modules.getModule(xtype); } -let constantInjection = {}; +const constantInjection = {}; export function constant(xtype, cls) { - if (constantInjection[xtype] != null) { - _global.console && console.error("constant: [" + xtype + "]已经注册过了"); + if (isNotNull(constantInjection[xtype])) { + _global.console && console.error(`constant: [${xtype}]已经注册过了`); } else { constantInjection[xtype] = cls; } @@ -51,60 +51,60 @@ export function constant(xtype, cls) { return () => Constants.getConstant(xtype); } -let modelInjection = {}; +const modelInjection = {}; export function model(xtype, cls) { - if (modelInjection[xtype] != null) { - _global.console && console.error("model: [" + xtype + "] 已经注册过了"); + if (isNotNull(modelInjection[xtype])) { + _global.console && console.error(`model: [${xtype}] 已经注册过了`); } else { modelInjection[xtype] = cls; } - return (config) => Models.getModel(xtype, config); + return config => Models.getModel(xtype, config); } -let storeInjection = {}; +const storeInjection = {}; export function store(xtype, cls) { - if (storeInjection[xtype] != null) { - _global.console && console.error("store: [" + xtype + "] 已经注册过了"); + if (isNotNull(storeInjection[xtype])) { + _global.console && console.error(`store: [${xtype}] 已经注册过了`); } else { storeInjection[xtype] = cls; } - return (config) => Stores.getStore(xtype, config); + return config => Stores.getStore(xtype, config); } -let serviceInjection = {}; +const serviceInjection = {}; export function service(xtype, cls) { - if (serviceInjection[xtype] != null) { - _global.console && console.error("service: [" + xtype + "] 已经注册过了"); + if ((serviceInjection[xtype])) { + _global.console && console.error(`service: [${xtype}] 已经注册过了`); } serviceInjection[xtype] = cls; - return (config) => Services.getService(xtype, config); + return config => Services.getService(xtype, config); } -let providerInjection = {}; +const providerInjection = {}; export function provider(xtype, cls) { - if (providerInjection[xtype] != null) { - _global.console && console.error("provider: [" + xtype + "] 已经注册过了"); + if ((providerInjection[xtype])) { + _global.console && console.error(`provider: [${xtype}] 已经注册过了`); } else { providerInjection[xtype] = cls; } - return (config) => Providers.getProvider(xtype, config); + return config => Providers.getProvider(xtype, config); } -let configFunctions = OB.configFunctions = {}; -const runConfigFunction = function (type, configFn) { +const configFunctions = OB.configFunctions = {}; +const runConfigFunction = (type, configFn) => { if (!type || !configFunctions[type]) { return false; } let queue = []; if (configFn) { - queue = configFunctions[type].filter((conf) => conf.fn === configFn); - configFunctions[type] = configFunctions[type].filter((conf) => conf.fn !== configFn); + queue = configFunctions[type].filter(conf => conf.fn === configFn); + configFunctions[type] = configFunctions[type].filter(conf => conf.fn !== configFn); } else { queue = configFunctions[type]; delete configFunctions[type]; @@ -140,7 +140,7 @@ const runConfigFunction = function (type, configFn) { } } if (findVersion === true) { - _global.console && console.error("moduleId: [" + module.moduleId + "] 接口: [" + type + "] 接口版本: [" + version + "] 已过期,版本要求为:", dependencies[module.moduleId], "=>", moduleInjection[module.moduleId]); + _global.console && console.error(`moduleId: [${module.moduleId}] 接口: [${type}] 接口版本: [${version}] 已过期,版本要求为:`, dependencies[module.moduleId], "=>", moduleInjection[module.moduleId]); continue; } } @@ -179,6 +179,7 @@ export function config(type, configFn, opt) { if (providerInstance[type]) { delete providerInstance[type]; } + return configFn(providers[type]); } @@ -187,7 +188,7 @@ export function config(type, configFn, opt) { } configFunctions[type].push({ fn: configFn, - opt: opt + opt, }); if (opt.immediately) { @@ -199,28 +200,30 @@ export function getReference(type, fn) { return BI.Plugin.registerObject(type, fn); } -let actions = {}; -let globalAction = []; +const actions = {}; +const globalAction = []; export function action(type, actionFn) { if (isFunction(type)) { globalAction.push(type); + return () => { - remove(globalAction, (idx) => globalAction.indexOf(actionFn) === idx); + remove(globalAction, idx => globalAction.indexOf(actionFn) === idx); }; } if (!actions[type]) { actions[type] = []; } actions[type].push(actionFn); + return () => { - remove(actions[type], (idx) => actions[type].indexOf(actionFn) === idx); + remove(actions[type], idx => actions[type].indexOf(actionFn) === idx); if (actions[type].length === 0) { delete actions[type]; } }; } -let points = {}; +const points = {}; export function point(type, action, pointFn, after) { if (!points[type]) { points[type] = {}; @@ -235,35 +238,37 @@ export function point(type, action, pointFn, after) { } export const Modules = { - getModule: function (type) { + getModule (type) { if (!moduleInjection[type]) { - _global.console && console.error("module: [" + type + "] 未定义"); + _global.console && console.error(`module: [${type}] 未定义`); } + return moduleInjection[type]; }, - getAllModules: function () { + getAllModules () { return moduleInjection; - } -} + }, +}; export const Constants = { - getConstant: function (type) { + getConstant (type) { if (isNull(constantInjection[type])) { - _global.console && console.error("constant: [" + type + "] 未定义"); + _global.console && console.error(`constant: [${type}] 未定义`); } runConfigFunction(type); + return isFunction(constantInjection[type]) ? constantInjection[type]() : constantInjection[type]; - } -} + }, +}; -const callPoint = function (inst, types) { +function callPoint(inst, types) { types = isArray(types) ? types : [types]; each(types, (idx, type) => { if (points[type]) { for (const action in points[type]) { - let bfns = points[type][action].before; + const bfns = points[type][action].before; if (bfns) { - BI.aspect.before(inst, action, function (bfns) { + BI.aspect.before(inst, action, (function (bfns) { return function () { for (let i = 0, len = bfns.length; i < len; i++) { try { @@ -273,11 +278,11 @@ const callPoint = function (inst, types) { } } }; - }(bfns)); + }(bfns))); } - let afns = points[type][action].after; + const afns = points[type][action].after; if (afns) { - BI.aspect.after(inst, action, function (afns) { + BI.aspect.after(inst, action, (function (afns) { return function () { for (let i = 0, len = afns.length; i < len; i++) { try { @@ -287,66 +292,69 @@ const callPoint = function (inst, types) { } } }; - }(afns)); + }(afns))); } } } }); -}; +} export const Models = { - getModel: function (type, config) { + getModel (type, config) { if (!modelInjection[type]) { - _global.console && console.error("model: [" + type + "] 未定义"); + _global.console && console.error(`model: [${type}] 未定义`); } runConfigFunction(type); - var inst = new modelInjection[type](config); + const inst = new modelInjection[type](config); inst._constructor && inst._constructor(config); inst.mixins && callPoint(inst, inst.mixins); callPoint(inst, type); + return inst; - } -} + }, +}; -let stores = {}; +const stores = {}; export const Stores = { - getStore: function (type, config) { + getStore (type, config) { if (!storeInjection[type]) { - _global.console && console.error("store: [" + type + "] 未定义"); + _global.console && console.error(`store: [${type}] 未定义`); } if (stores[type]) { return stores[type]; } const inst = stores[type] = new storeInjection[type](config); - inst._constructor && inst._constructor(config, function () { + inst._constructor && inst._constructor(config, () => { delete stores[type]; }); callPoint(inst, type); + return inst; - } -} + }, +}; -let services = {}; +const services = {}; export const Services = { getService: (type, config) => { if (!serviceInjection[type]) { - _global.console && console.error("service: [" + type + "] 未定义"); + _global.console && console.error(`service: [${type}] 未定义`); } if (services[type]) { return services[type]; } services[type] = new serviceInjection[type](config); callPoint(services[type], type); + return services[type]; - } -} + }, +}; -let providers = {}, +const providers = {}, providerInstance = {}; export const Providers = { getProvider: (type, config) => { if (!providerInjection[type]) { - _global.console && console.error("provider: [" + type + "] 未定义"); + _global.console && console.error(`provider: [${type}] 未定义`); } runConfigFunction(type); if (!providers[type]) { @@ -355,12 +363,13 @@ export const Providers = { if (!providerInstance[type] && providers[type].$get) { providerInstance[type] = new (providers[type].$get())(config); } + return providerInstance[type]; - } -} + }, +}; export const Actions = { - runAction: function (type, event, config) { + runAction (type, event, config) { each(actions[type], (i, act) => { try { act(event, config); @@ -369,38 +378,38 @@ export const Actions = { } }); }, - runGlobalAction: function () { - var args = [].slice.call(arguments); + runGlobalAction () { + const args = [].slice.call(arguments); each(globalAction, (i, act) => { try { - act.apply(null, args); + act(...args); } catch (e) { _global.console && console.error(e); } }); - } -} + }, +}; -let kv = {}; +const kv = {}; export function shortcut(xtype, cls) { - if (kv[xtype] != null) { - _global.console && console.error("组件: [" + xtype + "] 已经注册过了"); + if (isNotNull(kv[xtype])) { + _global.console && console.error(`组件: [${xtype}] 已经注册过了`); } if (cls) { - cls["xtype"] = xtype; + cls.xtype = xtype; } kv[xtype] = cls; } // 根据配置属性生成widget -const createRealWidget = function (config, context, lazy) { - const cls = isFunction(config.type) ? config.type : kv[config.type]; +const createRealWidget = (config, context, lazy) => { + const Cls = isFunction(config.type) ? config.type : kv[config.type]; - if (!cls) { - throw new Error("组件: [" + config.type + "] 未定义"); + if (!Cls) { + throw new Error(`组件: [${config.type}] 未定义`); } let pushed = false; - const widget = new cls(); + const widget = new Cls(); widget._context = Widget.context || context; if (!Widget.context && context) { pushed = true; @@ -414,6 +423,7 @@ const createRealWidget = function (config, context, lazy) { widget._lazyConstructor(); // } pushed && Widget.popContext(); + return widget; }; @@ -426,15 +436,15 @@ export function createWidget(item, options, context, lazy) { options || (options = {}); } - var el, w; + let el, w; if (item.type || options.type) { el = extend({}, options, item); } else if (item.el && (item.el.type || options.type)) { el = extend({}, options, item.el); } - + let elType; if (el) { - var elType = (el.type && el.type.xtype) || el.type; + elType = (el.type && el.type.xtype) || el.type; runConfigFunction(elType); } @@ -443,7 +453,7 @@ export function createWidget(item, options, context, lazy) { if (isEmpty(item) && isEmpty(options)) { return createWidget({ - type: "bi.layout" + type: "bi.layout", }); } if (isWidget(item)) { @@ -451,7 +461,7 @@ export function createWidget(item, options, context, lazy) { } if (el) { w = BI.Plugin.getWidget(elType, el); - var wType = (w.type && w.type.xtype) || w.type; + const wType = (w.type && w.type.xtype) || w.type; if (wType === elType) { if (BI.Plugin.hasObject(elType)) { if (!w.listeners || isArray(w.listeners)) { @@ -459,7 +469,7 @@ export function createWidget(item, options, context, lazy) { eventName: BI.Events.MOUNT, action: () => { BI.Plugin.getObject(elType, this); - } + }, }]); } else { w.listeners[BI.Events.MOUNT] = [ @@ -469,8 +479,10 @@ export function createWidget(item, options, context, lazy) { ].concat(w.listeners[BI.Events.MOUNT] || []); } } + return createRealWidget(w, context, lazy); } + return createWidget(w, options, context, lazy); } if (isWidget(item.el)) { @@ -485,6 +497,7 @@ export function _lazyCreateWidget (item, options, context) { export function createElement() { const widget = createWidget.apply(this, arguments); + return widget.element; } @@ -504,5 +517,5 @@ export function getResource(type, config) { if (providerInjection[type]) { return Providers.getProvider(type, config); } - throw new Error("未知类型: [" + type + "] 未定义"); + throw new Error(`未知类型: [${type}] 未定义`); } diff --git a/src/core/index.js b/src/core/index.js index 85847f032..d24cd4241 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -22,13 +22,13 @@ export * from "./controller"; export * from "./func"; // 有了后删掉 -export const emptyFn = () => { } +export const emptyFn = () => { }; export { StyleLoaderManager, ShowListener, - shortcut, -} + shortcut +}; Object.assign(BI, { ...base,