From be9a5e85121bc4654651123e1af5c9ee0cb90187 Mon Sep 17 00:00:00 2001 From: Treecat Date: Fri, 24 Feb 2023 11:20:45 +0800 Subject: [PATCH] =?UTF-8?q?refact:=20KERNEL-14316=20=E5=8E=BB=E6=8E=89=20j?= =?UTF-8?q?Query=20=E4=BB=A5=E5=A4=96=E7=9A=84=E5=85=A8=E5=B1=80=E5=8F=98?= =?UTF-8?q?=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 4 + rollup.config.js | 28 +- src/core/0.foundation.js | 18 +- src/core/2.base.js | 758 ++++++++++++------ src/core/3.ob.js | 10 +- src/core/4.widget.js | 281 ++++--- src/core/5.inject.js | 1 + src/core/controller/controller.resizer.js | 1 + src/core/func/alias.js | 201 +++-- src/core/func/date.js | 1 + src/core/index.js | 5 +- src/core/loader/loader.style.js | 1 + src/core/platform/web/function.js | 1 + src/core/platform/web/jquery/_jquery.js | 6 +- src/core/platform/web/jquery/fn.js | 1 + .../platform/web/jquery/jquery.mousewheel.js | 2 + src/core/structure/aes.js | 7 +- src/core/structure/prefixIntervalTree.js | 2 + src/core/system.js | 72 +- src/core/utils/events/mousemovetracker.js | 1 + src/core/utils/events/wheelhandler.js | 1 + test/prepare.js | 6 - test/utils.js | 47 -- 23 files changed, 875 insertions(+), 580 deletions(-) delete mode 100644 test/prepare.js delete mode 100644 test/utils.js diff --git a/package.json b/package.json index e73b6000d..18f8b60a4 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,10 @@ "@fui/babel-preset-fineui": "^3.0.0", "@fui/eslint-plugin": "^1.0.19", "@juggle/resize-observer": "^3.4.0", + "@rollup/plugin-alias": "4.0.3", + "@rollup/plugin-babel": "6.0.3", + "@rollup/plugin-commonjs": "24.0.1", + "@rollup/plugin-node-resolve": "15.0.1", "@types/node": "15.6.1", "@typescript-eslint/eslint-plugin": "2.33.0", "@typescript-eslint/parser": "2.33.0", diff --git a/rollup.config.js b/rollup.config.js index b71ac0e49..fabb1416b 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -3,10 +3,11 @@ const alias = require("@rollup/plugin-alias"); const resolve = require("@rollup/plugin-node-resolve"); const commonjs = require("@rollup/plugin-commonjs"); const path = require("path"); -// import { fileURLToPath } from "url"; -// import path from "path"; -// const __dirname = path.dirname(fileURLToPath(import.meta.url)); +/** + * todo: 删除根目录下的 babel.config.js,然后移入到这个文件 + */ + const input = "src/index.js"; module.exports = [ @@ -16,24 +17,23 @@ module.exports = [ { file: "dist/fineui.esm.js", format: "esm", - sourcemap: true - } + sourcemap: true, + }, ], plugins: [ alias({ entries: [ - { find: "@", replacement: path.resolve(__dirname, "src") } - ] + { find: "@", replacement: path.resolve(__dirname, "src") }, + ], }), resolve(), babel({ - babelHelpers: "runtime", - presets: ["@babel/preset-env"], + babelHelpers: "inline", plugins: [ - ["@babel/plugin-proposal-decorators", { legacy: true }] - ] + ["@babel/plugin-proposal-decorators", { legacy: true }], + ], }), - commonjs() - ] - } + commonjs(), + ], + }, ]; diff --git a/src/core/0.foundation.js b/src/core/0.foundation.js index 96c6e59ba..6a251f80c 100644 --- a/src/core/0.foundation.js +++ b/src/core/0.foundation.js @@ -1,9 +1,7 @@ -/* eslint-disable eqeqeq */ /** * Created by richie on 15/7/8. - */ -/** - * 初始化BI对象 + * + * 初始化 _global 对象??为什么不是 globalThis */ let _global = undefined; if (typeof window !== "undefined") { @@ -20,9 +18,9 @@ if (_global) { _global._global = _global; } -if (_global.BI == null) { - _global.BI = { prepares: [] }; -} -if (_global.BI.prepares == null) { - _global.BI.prepares = []; -} +const prepares = []; + +export { + _global, + prepares +}; diff --git a/src/core/2.base.js b/src/core/2.base.js index f297ae095..b0e166893 100644 --- a/src/core/2.base.js +++ b/src/core/2.base.js @@ -3,7 +3,19 @@ * Create By GUY 2014\11\17 * */ -function traverse (func, context) { +import _ from "./1.lodash"; +import { Widget } from "./4.widget"; +import { createWidget } from "./5.inject"; +import { prepares, _global } from "./0.foundation"; +import { CRYPT_TYPE, aesDecrypt, aesEncrypt } from "./structure/aes"; + + +/** + * todo: 理论这么写,逻辑没问题,摇个人把这个 BI 干掉 + */ +const BI = { _ }; + +function traverse(func, context) { return function (value, key, obj) { return func.call(context, key, value, obj); }; @@ -16,8 +28,10 @@ function _apply(name) { function _applyFunc(name) { return function () { const args = Array.prototype.slice.call(arguments, 0); - args[1] = BI._.isFunction(args[1]) ? traverse(args[1], args[2]) : args[1]; - + args[1] = BI._.isFunction(args[1]) + ? traverse(args[1], args[2]) + : args[1]; + return BI._[name](...args); }; } @@ -36,7 +50,7 @@ export function assert(v, is) { if (!deepContains(is, v)) { throw new Error(`${v} error`); } - + return true; } @@ -45,18 +59,35 @@ export function warn(message) { } export function UUID() { - const f = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; + 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; } export function isWidget(widget) { - return widget instanceof BI.Widget; + return widget instanceof Widget; } export function createWidgets(items, options, context) { @@ -69,34 +100,40 @@ export function createWidgets(items, options, context) { } else { options || (options = {}); } - - return map(flatten(items), (i, item) => BI.createWidget(item, deepClone(options), context)); + + return map(flatten(items), (i, item) => + 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 || {}); - + innerAttr = isArray(innerAttr) + ? innerAttr + : makeArray(flatten(data).length, innerAttr || {}); + outerAttr = isArray(outerAttr) + ? outerAttr + : makeArray(flatten(data).length, outerAttr || {}); + return map(data, (i, item) => { if (isArray(item)) { return createItems(item, innerAttr, outerAttr); } - if (item instanceof BI.Widget) { + if (item instanceof Widget) { return extend({}, innerAttr.shift(), outerAttr.shift(), { type: null, el: item, }); } - if (innerAttr[0] instanceof BI.Widget) { + if (innerAttr[0] instanceof Widget) { outerAttr.shift(); - + return extend({}, item, { el: innerAttr.shift(), }); } - if (item.el instanceof BI.Widget) { + if (item.el instanceof Widget) { innerAttr.shift(); - + return extend({}, outerAttr.shift(), { type: null }, item); } if (item.el) { @@ -104,7 +141,7 @@ export function createItems(data, innerAttr, outerAttr) { el: extend({}, innerAttr.shift(), item.el), }); } - + return extend({}, outerAttr.shift(), { el: extend({}, innerAttr.shift(), item), }); @@ -114,15 +151,17 @@ export function createItems(data, innerAttr, outerAttr) { // 用容器包装items export function packageItems(items, layouts) { for (let i = layouts.length - 1; i >= 0; i--) { - items = map(items, (k, it) => extend({}, layouts[i], { - items: [ - extend({}, layouts[i].el, { - el: it, - }) - ], - })); - } - + items = map(items, (k, it) => + extend({}, layouts[i], { + items: [ + extend({}, layouts[i].el, { + el: it, + }) + ], + }) + ); + } + return items; } @@ -130,7 +169,7 @@ export function formatEL(obj) { if (obj && !obj.type && obj.el) { return obj; } - + return { el: obj, }; @@ -138,7 +177,7 @@ export function formatEL(obj) { // 剥开EL export function stripEL(obj) { - return obj.type && obj || obj.el || obj; + return (obj.type && obj) || obj.el || obj; } export function trans2Element(widgets) { @@ -146,19 +185,53 @@ export function trans2Element(widgets) { } // 集合相关方法 -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" -], name => { - if (name === "any") { - BI[name] = _applyFunc("some"); - } else { - BI[name] = _applyFunc(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" + ], + name => { + if (name === "any") { + BI[name] = _applyFunc("some"); + } else { + BI[name] = _applyFunc(name); + } } -}); +); export const where = BI.where; export const findWhere = BI.findWhere; export const invoke = BI.invoke; @@ -197,7 +270,7 @@ export function count(from, to, predicate) { predicate(t); } } - + return to - from; } @@ -210,10 +283,10 @@ export function firstKey(obj) { let res = undefined; any(obj, (key, value) => { res = key; - + return true; }); - + return res; } @@ -221,10 +294,10 @@ export function lastKey(obj) { let res = undefined; each(obj, (key, value) => { res = key; - + return true; }); - + return res; } @@ -232,10 +305,10 @@ export function firstObject(obj) { let res = undefined; any(obj, (key, value) => { res = value; - + return true; }); - + return res; } @@ -243,10 +316,10 @@ export function lastObject(obj) { let res = undefined; each(obj, (key, value) => { res = value; - + return true; }); - + return res; } @@ -267,7 +340,7 @@ export function backEach(obj, predicate, context) { for (let index = obj.length - 1; index >= 0; index--) { predicate(index, obj[index], obj); } - + return false; } @@ -278,7 +351,7 @@ export function backAny(obj, predicate, context) { return true; } } - + return false; } @@ -289,7 +362,7 @@ export function backEvery(obj, predicate, context) { return false; } } - + return true; } @@ -323,13 +396,23 @@ export function remove(obj, target, context) { let i; if (isArray(obj)) { for (i = 0; i < obj.length; i++) { - if ((targetIsFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!targetIsFunction && contains(target, obj[i]))) { + if ( + (targetIsFunction && + (target === obj[i] || + target.apply(context, [i, obj[i]]) === true)) || + (!targetIsFunction && contains(target, obj[i])) + ) { obj.splice(i--, 1); } } } else { each(obj, (i, v) => { - if ((targetIsFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!targetIsFunction && contains(target, obj[i]))) { + if ( + (targetIsFunction && + (target === obj[i] || + target.apply(context, [i, obj[i]]) === true)) || + (!targetIsFunction && contains(target, obj[i])) + ) { delete obj[i]; } }); @@ -362,20 +445,53 @@ export function array2String(array) { export function abc2Int(string) { let idx = 0; - const start = "A", str = string.toUpperCase(); + 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) { + if ( + idx > + (2147483646 - str.charAt(i).charCodeAt(0) + start.charCodeAt(0)) / + 26 + ) { return 0; } } - + return idx; } export function int2Abc(num) { - const DIGITS = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; - let idx = num, str = ""; + const DIGITS = [ + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z" + ]; + let idx = num, + str = ""; if (num === 0) { return ""; } @@ -387,17 +503,38 @@ export function int2Abc(num) { str = DIGITS[t - 1] + str; idx = (idx - t) / 26; } - + return str; } // 数组相关的方法 -BI._.each([ - "first", "initial", "last", "rest", "compact", "flatten", "without", "union", "intersection", - "difference", "zip", "unzip", "object", "indexOf", "lastIndexOf", "sortedIndex", "range", "take", "takeRight", "uniqBy" -], name => { - BI[name] = _apply(name); -}); +BI._.each( + [ + "first", + "initial", + "last", + "rest", + "compact", + "flatten", + "without", + "union", + "intersection", + "difference", + "zip", + "unzip", + "object", + "indexOf", + "lastIndexOf", + "sortedIndex", + "range", + "take", + "takeRight", + "uniqBy" + ], + name => { + BI[name] = _apply(name); + } +); BI._.each(["findIndex", "findLastIndex"], name => { BI[name] = _applyFunc(name); }); @@ -434,7 +571,7 @@ export function makeArray(length, value) { res.push(deepClone(value)); } } - + return res; } @@ -449,7 +586,7 @@ export function makeObject(array, value) { map[array[i]] = deepClone(value); } } - + return map; } @@ -465,7 +602,7 @@ export function makeArrayByArray(array, value) { res.push(deepClone(value)); } } - + return res; } @@ -479,19 +616,53 @@ export function uniq(array, isSorted, iteratee, context) { isSorted = false; } iteratee && (iteratee = traverse(iteratee, context)); - + return BI._uniq.call(BI._, array, isSorted, iteratee, context); } // 对象相关方法 -BI._.each([ - "keys", "allKeys", "values", "pairs", "invert", "create", "functions", "extend", "extendOwn", - "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", "pickBy" -], name => { - BI[name] = _apply(name); -}); +BI._.each( + [ + "keys", + "allKeys", + "values", + "pairs", + "invert", + "create", + "functions", + "extend", + "extendOwn", + "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", + "pickBy" + ], + name => { + BI[name] = _apply(name); + } +); export const keys = BI.keys; export const allKeys = BI.allKeys; export const values = BI.values; @@ -538,10 +709,10 @@ export const omit = BI.omit; export const tap = BI.tap; export function inherit(sp, overrides) { - function sb () { + function sb() { return sp.apply(this, arguments); } - function F () {} + function F() {} const spp = sp.prototype; F.prototype = spp; sb.prototype = new F(); @@ -549,16 +720,19 @@ export function inherit(sp, overrides) { extend(sb.prototype, overrides, { superclass: sp, }); - + return sb; } export function init() { // 先把准备环境准备好 - while (BI.prepares && BI.prepares.length > 0) { - BI.prepares.shift()(); + while (prepares && prepares.length > 0) { + prepares.shift()(); } - while (_global.___fineuiExposedFunction && _global.___fineuiExposedFunction.length > 0) { + while ( + _global.___fineuiExposedFunction && + _global.___fineuiExposedFunction.length > 0 + ) { _global.___fineuiExposedFunction.shift()(); } BI.initialized = true; @@ -569,10 +743,10 @@ export function has(obj, keys) { if (keys.length === 0) { return false; } - + return every(keys, (i, key) => BI._.has(obj, key)); } - + return BI._.has(...arguments); } @@ -582,7 +756,7 @@ export function freeze(value) { if (Object.freeze && isObject(value)) { return Object.freeze(value); } - + return value; } @@ -593,9 +767,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 +777,12 @@ export function isWidthOrHeight(w) { if (typeof w === "number") { return w >= 0; } else if (typeof w === "string") { - return /^\d{1,3}(\.\d)?%$/.test(w) || w === "auto" || /^\d+(\.\d+)?px$/.test(w) || /^calc/.test(w); + return ( + /^\d{1,3}(\.\d)?%$/.test(w) || + w === "auto" || + /^\d+(\.\d+)?px$/.test(w) || + /^calc/.test(w) + ); } } @@ -643,7 +822,8 @@ export const deepClone = BI._.cloneDeep; export const deepExtend = BI._.merge; export function isDeepMatch(object, attrs) { - const attrsKeys = keys(attrs), length = attrsKeys.length; + const attrsKeys = keys(attrs), + length = attrsKeys.length; if (object === null) { return !length; } @@ -654,21 +834,23 @@ 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; + + return ( + indexOf(obj, target, typeof fromIndex === "number" && fromIndex) >= 0 + ); } export function deepContains(obj, copy) { if (isObject(copy)) { return any(obj, (i, v) => isEqual(v, copy)); } - + return contains(obj, copy); } @@ -678,7 +860,7 @@ export function deepIndexOf(obj, target) { return i; } } - + return -1; } @@ -700,7 +882,7 @@ export function deepRemove(obj, target) { } }); } - + return done; } @@ -712,7 +894,7 @@ export function deepWithout(obj, target) { result.push(obj[i]); } } - + return result; } const result = {}; @@ -721,7 +903,7 @@ export function deepWithout(obj, target) { result[i] = v; } }); - + return result; } @@ -732,7 +914,7 @@ export function deepUnique(array) { result.push(item); } }); - + return result; } @@ -755,14 +937,26 @@ export function deepDiff(object, other) { result.push(b); } } - + return result; } // 通用方法 -BI._.each(["uniqueId", "result", "chain", "iteratee", "unescape", "before", "after", "chunk"], name => { - BI[name] = (...args) => BI._[name](...args); -}); +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; export const chain = BI.chain; @@ -773,9 +967,21 @@ export const after = BI.after; export const chunk = BI.chunk; // 事件相关方法 -BI._.each(["bind", "once", "partial", "debounce", "throttle", "delay", "defer", "wrap"], name => { - BI[name] = (...args) => BI._[name](...args); -}); +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; export const partial = BI.partial; @@ -846,9 +1052,9 @@ export const nextTick = (function () { } // $flow-disable-line if (!cb && typeof Promise !== "undefined") { - return new Promise(((resolve, reject) => { + return new Promise((resolve, reject) => { _resolve = resolve; - })); + }); } }; }()); @@ -873,10 +1079,12 @@ export function parseInt(number) { export function parseSafeInt(value) { const MAX_SAFE_INTEGER = 9007199254740991; - + return value ? clamp(parseInt(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) - : (value === 0 ? value : 0); + : value === 0 + ? value + : 0; } export function parseFloat(number) { @@ -904,7 +1112,9 @@ export function isInteger(number) { } export function isNumeric(number) { - return !_global.isNaN(_global.parseFloat(number)) && _global.isFinite(number); + return ( + !_global.isNaN(_global.parseFloat(number)) && _global.isFinite(number) + ); } export function isFloat(number) { @@ -915,7 +1125,7 @@ export function isOdd(number) { if (!isInteger(number)) { return false; } - + return (number & 1) === 1; } @@ -923,7 +1133,7 @@ export function isEven(number) { if (!isInteger(number)) { return false; } - + return (number & 1) === 0; } @@ -936,13 +1146,13 @@ 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; } @@ -951,11 +1161,11 @@ export function 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) { @@ -969,10 +1179,8 @@ export function isLiteral(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; + + return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str; } // background-color => backgroundColor @@ -1002,9 +1210,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 CRYPT_TYPE.AES: + default: + return aesEncrypt(text, key); } } @@ -1017,9 +1225,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 CRYPT_TYPE.AES: + default: + return aesDecrypt(text, key); } } @@ -1033,7 +1241,6 @@ export function escape(string) { return string.replace(/('|\\)/g, "\\$1"); } - /** * 让字符串通过指定字符做补齐的函数 * @@ -1053,7 +1260,7 @@ export function leftPad(val, size, ch) { while (result.length < size) { result = ch + result; } - + return result.toString(); } @@ -1070,7 +1277,7 @@ export function leftPad(val, size, ch) { */ export function format(format) { const args = Array.prototype.slice.call(arguments, 1); - + return format.replace(/\{(\d+)\}/g, (m, i) => args[i]); } @@ -1124,13 +1331,15 @@ export function checkDateVoid(YY, MM, DD, minDate, maxDate) { } } } - + return back; } export function checkDateLegal(str) { const ar = str.match(/\d+/g); - const YY = ar[0] | 0, MM = ar[1] | 0, DD = ar[2] | 0; + const YY = ar[0] | 0, + MM = ar[1] | 0, + DD = ar[2] | 0; if (ar.length <= 1) { return true; } @@ -1139,7 +1348,7 @@ export function checkDateLegal(str) { } const MD = BI.Date._MD.slice(0); MD[1] = isLeapYear(YY) ? 29 : 28; - + return MM >= 1 && MM <= 12 && DD <= MD[MM - 1]; } @@ -1162,69 +1371,77 @@ export function parseDateTime(str, fmt) { 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); + a[2] = str.substring( + yearlength + otherlength, + yearlength + otherlength * 2 + ); } const b = fmt.match(/%./g); - let i = 0, j = 0; + 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; + 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; - } - 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: + 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]) { @@ -1258,7 +1475,10 @@ export function parseDateTime(str, fmt) { 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; } @@ -1273,7 +1493,7 @@ export function parseDateTime(str, fmt) { m = a[i] - 1; } else if (_global.parseInt(a[i], 10) > 31 && y === 0) { y = _global.parseInt(a[i], 10); - (y < 100) && (y += (y > 29) ? 1900 : 2000); + y < 100 && (y += y > 29 ? 1900 : 2000); } else if (d === 0) { d = a[i]; } @@ -1287,7 +1507,7 @@ export function parseDateTime(str, fmt) { if (m !== -1 && d !== 0) { return BI.getDate(y, m, d, hr, min, sec); } - + return today; } @@ -1295,51 +1515,63 @@ 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; - } - if (isNotNull(BI.timeZone) && (arguments.length === 0 || (arguments.length === 1 && isNumber(arguments[0])))) { + 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 new Date(utc + BI.timeZone); // + Pool.timeZone.offset); } - + return dt; } @@ -1348,47 +1580,59 @@ 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() - BI.timeZone - new Date().getTimezoneOffset() * 60000 + ); } - + return dt.getTime(); } + +export const lodashUtils = BI._; diff --git a/src/core/3.ob.js b/src/core/3.ob.js index 8357389fd..1cf2d94ae 100644 --- a/src/core/3.ob.js +++ b/src/core/3.ob.js @@ -1,4 +1,4 @@ -import { isFunction, isArray, isObject, isArguments, reduce, bind } from "./2.base"; +import { isFunction, isArray, isObject, isArguments, reduce, bind, each } from "./2.base"; function obExtend() { const target = arguments[0] || {}, length = arguments.length; @@ -65,17 +65,17 @@ export class OB { _initListeners() { if (this.options.listeners !== null) { - BI._.each(this.options.listeners, (lis, eventName) => { + each(this.options.listeners, (eventName, lis) => { if (isFunction(lis)) { this.on(eventName, lis); return; } if (isArray(lis)) { - BI._.each(lis, l => { + lis.forEach(l => { this.on(eventName, l); }); - + return; } (lis.target ? lis.target : this)[lis.once ? "once" : "on"](lis.eventName, bind(lis.action, this)); @@ -161,7 +161,7 @@ export class OB { const fns = this._getEvents()[eventName]; if (isArray(fns)) { const newFns = []; - BI._.each(fns, ifn => { + fns.forEach(ifn => { if (ifn !== fn) { newFns.push(ifn); } diff --git a/src/core/4.widget.js b/src/core/4.widget.js index ae9db3e6e..4cd38f284 100644 --- a/src/core/4.widget.js +++ b/src/core/4.widget.js @@ -6,12 +6,27 @@ * @cfg {JSON} options 配置属性 */ -import { isFunction, isArray, each, extend, isPlainObject, isNull, uniqueId, isWidget, isWidthOrHeight, isKey, remove, any, isNotNull } from "./2.base"; +import { + isFunction, + isArray, + each, + extend, + isPlainObject, + isNull, + uniqueId, + isWidget, + isWidthOrHeight, + isKey, + remove, + any, + isNotNull +} from "./2.base"; import { OB } from "./3.ob"; import { Providers, _lazyCreateWidget } from "./5.inject"; import { DOM } from "./utils"; import { Events, emptyFn, pixFormat } from "./constant"; import { Plugin } from "./6.plugin"; +import { _global } from "./0.foundation"; const cancelAnimationFrame = _global.cancelAnimationFrame || @@ -21,10 +36,17 @@ const cancelAnimationFrame = _global.msCancelAnimationFrame || _global.clearTimeout; -const requestAnimationFrame = _global.requestAnimationFrame || _global.webkitRequestAnimationFrame || _global.mozRequestAnimationFrame || _global.oRequestAnimationFrame || _global.msRequestAnimationFrame || _global.setTimeout; +const requestAnimationFrame = + _global.requestAnimationFrame || + _global.webkitRequestAnimationFrame || + _global.mozRequestAnimationFrame || + _global.oRequestAnimationFrame || + _global.msRequestAnimationFrame || + _global.setTimeout; function callLifeHook(self, life) { - let hooks = [], hook; + let hooks = [], + hook; hook = self[life]; if (hook) { hooks = hooks.concat(isArray(hook) ? hook : [hook]); @@ -39,7 +61,7 @@ function callLifeHook(self, life) { } export class Widget extends OB { - _defaultConfig () { + _defaultConfig() { return extend(super._defaultConfig(), { root: false, tagName: "div", @@ -56,18 +78,16 @@ export class Widget extends OB { baseCls: "", extraCls: "", cls: "", - css: null, + css: null // vdom: false }); } - _constructor () { - - } + _constructor() {} // 覆盖父类的_constructor方法,widget不走ob的生命周期 - _constructed () { + _constructed() { if (this.setup) { pushTarget(this); const delegate = this.setup(this.options); @@ -81,7 +101,7 @@ export class Widget extends OB { } } - _lazyConstructor () { + _lazyConstructor() { if (!this.__constructed) { this.__constructed = true; this._init(); @@ -134,8 +154,11 @@ export class Widget extends OB { const init = () => { // 加个保险 if (initCallbackCalled === true) { - _global.console && console.error("组件: 请检查beforeInit内部的写法,callback只能执行一次"); - + _global.console && + console.error( + "组件: 请检查beforeInit内部的写法,callback只能执行一次" + ); + return; } initCallbackCalled = true; @@ -143,8 +166,11 @@ export class Widget extends OB { const render = () => { // 加个保险 if (renderCallbackCalled === true) { - _global.console && console.error("组件: 请检查beforeRender内部的写法,callback只能执行一次"); - + _global.console && + console.error( + "组件: 请检查beforeRender内部的写法,callback只能执行一次" + ); + return; } renderCallbackCalled = true; @@ -154,9 +180,11 @@ export class Widget extends OB { if (this.options.beforeRender || this.beforeRender) { this.__async = true; - const beforeRenderResult = (this.options.beforeRender || this.beforeRender).call(this, render); + const beforeRenderResult = ( + this.options.beforeRender || this.beforeRender + ).call(this, render); if (beforeRenderResult instanceof Promise) { - beforeRenderResult.then(render).catch(e => { + beforeRenderResult.then(render).catch((e) => { _global.console && console.error(e); render(); }); @@ -169,9 +197,11 @@ export class Widget extends OB { if (this.options.beforeInit || this.beforeInit) { this.__asking = true; - const beforeInitResult = (this.options.beforeInit || this.beforeInit).call(this, init); + const beforeInitResult = ( + this.options.beforeInit || this.beforeInit + ).call(this, init); if (beforeInitResult instanceof Promise) { - beforeInitResult.then(init).catch(e => { + beforeInitResult.then(init).catch((e) => { _global.console && console.error(e); init(); }); @@ -211,12 +241,14 @@ 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)) { let cls = this.__watch(o.cls, (context, newValue) => { - this.element.removeClass(cls).addClass(cls = newValue); + this.element.removeClass(cls).addClass((cls = newValue)); }); this.element.addClass(cls); } else { @@ -240,7 +272,7 @@ export class Widget extends OB { newValue[k] = ""; } } - this.element.css(css = newValue); + this.element.css((css = newValue)); }); this.element.css(css); } else { @@ -252,13 +284,20 @@ export class Widget extends OB { __watch(getter, handler, options) { if (_global.Fix) { this._watchers = this._watchers || []; - const watcher = new Fix.Watcher(null, () => getter.call(this, this), (handler && (v => { - handler.call(this, this, v); - })) || emptyFn, extend({ deep: true }, options)); + const watcher = new Fix.Watcher( + null, + () => getter.call(this, this), + (handler && + ((v) => { + handler.call(this, this, v); + })) || + emptyFn, + extend({ deep: true }, options) + ); this._watchers.push(() => { watcher.teardown(); }); - + return watcher.value; } else { return getter(); @@ -277,7 +316,8 @@ export class Widget extends OB { if (isWidget(o.element)) { this.element = this.options.element.element; this._parent = o.element; - this._parent._children && this._parent.addWidget(this.widgetName, this); + this._parent._children && + this._parent.addWidget(this.widgetName, this); } else if (o.element) { this.element = Widget._renderEngine.createElement(this); this._isRoot = true; @@ -308,9 +348,11 @@ export class Widget extends OB { _initVisual() { const o = this.options; if (o.invisible) { - const invisible = o.invisible = isFunction(o.invisible) ? this.__watch(o.invisible, (context, newValue) => { - this.setVisible(!newValue); - }) : o.invisible; + const invisible = (o.invisible = isFunction(o.invisible) + ? this.__watch(o.invisible, (context, newValue) => { + this.setVisible(!newValue); + }) + : o.invisible); if (invisible) { // 用display属性做显示和隐藏,否则jquery会在显示时将display设为block会覆盖掉display:flex属性 this.__setElementVisible(false); @@ -322,17 +364,21 @@ export class Widget extends OB { const o = this.options; if (o.disabled || o.invalid) { if (this.options.disabled) { - const disabled = o.disabled = isFunction(o.disabled) ? this.__watch(o.disabled, (context, newValue) => { - this.setEnable(!newValue); - }) : o.disabled; + const disabled = (o.disabled = isFunction(o.disabled) + ? this.__watch(o.disabled, (context, newValue) => { + this.setEnable(!newValue); + }) + : o.disabled); if (disabled) { this.setEnable(false); } } if (this.options.invalid) { - const invalid = o.invalid = isFunction(o.invalid) ? this.__watch(o.invalid, (context, newValue) => { - this.setValid(!newValue); - }) : o.invalid; + const invalid = (o.invalid = isFunction(o.invalid) + ? this.__watch(o.invalid, (context, newValue) => { + this.setValid(!newValue); + }) + : o.invalid); if (invalid) { this.setValid(false); } @@ -365,10 +411,17 @@ export class Widget extends OB { _initElement() { this.__isMounting = true; // 当开启worker模式时,可以通过$render来实现另一种效果 - const workerMode = Providers.getProvider("bi.provider.system").getWorkerMode(); - const render = isFunction(this.options.render) ? this.options.render : (workerMode ? (this.$render || this.render) : this.render); + const workerMode = + Providers.getProvider("bi.provider.system").getWorkerMode(); + const render = isFunction(this.options.render) + ? this.options.render + : workerMode + ? this.$render || this.render + : this.render; let els = render && render.call(this); - els = this.options.configRender ? this.options.configRender.call(this, els) : els; + els = this.options.configRender + ? this.options.configRender.call(this, els) + : els; els = Plugin.getRender(this.options.type, els); if (isPlainObject(els)) { els = [els]; @@ -378,7 +431,7 @@ export class Widget extends OB { each(els, (i, el) => { if (el) { _lazyCreateWidget(el, { - element: this, + element: this }); } }); @@ -400,16 +453,34 @@ export class Widget extends OB { * @private */ _mount(force, deep, lifeHook, predicate, layer) { - if (!force && (this._isMounted || !this.isVisible() || this.__asking === true || !(this._isRoot === true || (this._parent && this._parent._isMounted === true)))) { + if ( + !force && + (this._isMounted || + !this.isVisible() || + this.__asking === true || + !( + this._isRoot === true || + (this._parent && this._parent._isMounted === true) + )) + ) { return false; } layer = layer || 0; - lifeHook !== false && !this.__async && callLifeHook(this, "beforeMount"); + lifeHook !== false && + !this.__async && + callLifeHook(this, "beforeMount"); this._isMounted = true; this.__isMounting = false; for (const key in this._children) { const child = this._children[key]; - child._mount && child._mount(deep ? force : false, deep, lifeHook, predicate, layer + 1); + child._mount && + child._mount( + deep ? force : false, + deep, + lifeHook, + predicate, + layer + 1 + ); } if (this._parent) { if (!this._parent.isEnabled()) { @@ -426,7 +497,7 @@ export class Widget extends OB { this.__afterMount(lifeHook, predicate); // }, 0); } - + return true; } @@ -454,7 +525,7 @@ export class Widget extends OB { res = this.update && this.update(nextProps, shouldUpdate); } callLifeHook(this, "updated"); - + return res; } @@ -484,7 +555,9 @@ export class Widget extends OB { } // 递归将所有子组件使能 each(this._children, (i, child) => { - !child._manualSetEnable && child._setEnable && child._setEnable(enable); + !child._manualSetEnable && + child._setEnable && + child._setEnable(enable); }); } @@ -532,7 +605,10 @@ 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); } @@ -544,12 +620,17 @@ export class Widget extends OB { 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); } @@ -561,7 +642,9 @@ export class Widget extends OB { 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 { @@ -620,7 +703,7 @@ export class Widget extends OB { // TODO: self待删 remove(self._children, this); }); - + return (this._children[name] = widget); } @@ -634,7 +717,7 @@ export class Widget extends OB { any(this._children, (i, wi) => { if (i === name) { widget = wi; - + return true; } other[i] = wi; @@ -642,7 +725,7 @@ export class Widget extends OB { if (!widget) { any(other, (i, wi) => (widget = wi.getWidgetByName(i))); } - + return widget; } @@ -673,13 +756,13 @@ export class Widget extends OB { attr(key, value) { if (isPlainObject(key)) { each(key, (k, v) => this.attr(k, v)); - + return; } if (isNotNull(value)) { this.options[key] = value; } - + return this.options[key]; } @@ -687,21 +770,13 @@ export class Widget extends OB { return this.element.css(name, value); } - getText() { - - } + getText() {} - setText(text) { + setText(text) {} - } - - getValue() { - - } + getValue() {} - setValue(value) { - - } + setValue(value) {} isEnabled() { return this.options.disabled === true ? false : !this.options._disabled; @@ -775,7 +850,7 @@ export class Widget extends OB { } } - _empty () { + _empty() { this._assetMounted(); each(this._children, (i, widget) => { widget && widget._unMount && widget._unMount(); @@ -784,19 +859,19 @@ export class Widget extends OB { this.element.empty(); } - isolate () { + isolate() { if (this._parent) { this._parent.removeWidget(this); } DOM.hang([this]); } - empty () { + empty() { this._empty(); } // 默认的reset方法就是干掉重来 - reset () { + reset() { // 还在异步状态的不需要执行reset if (this.__async === true || this.__asking === true) { return; @@ -851,8 +926,10 @@ export class Widget extends OB { } } -let context = null, current = null; -const contextStack = [], currentStack = []; +let context = null, + current = null; +const contextStack = [], + currentStack = []; Widget.pushContext = function (_context) { if (context) contextStack.push(context); @@ -896,17 +973,17 @@ export function useStore(_store) { let origin; if (_global.Proxy) { const proxy = new Proxy(delegate, { - get (target, key) { + get(target, key) { return Reflect.get(origin, key); }, - set (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; }; current.$storeDelegate = proxy; @@ -916,11 +993,11 @@ export function useStore(_store) { current._store = function () { const st = (_store || currentStore).apply(this, arguments); extend(delegate, st); - + return st; }; current.$storeDelegate = delegate; - + return current.$storeDelegate; } } @@ -945,11 +1022,11 @@ export function useContext(inject) { } vm = vm._parent; } - + return null; } } - + return vm; } @@ -967,25 +1044,31 @@ export function watch(vm, watch, handler) { const innerHandler = watch[key]; if (isArray(handler)) { for (let i = 0; i < handler.length; i++) { - watchers.push(Fix.watch(vm.model, key, innerHandler, { - store: vm, - })); + watchers.push( + Fix.watch(vm.model, key, innerHandler, { + store: vm + }) + ); } } else { - watchers.push(Fix.watch(vm.model, key, innerHandler, { - store: vm, - })); + watchers.push( + Fix.watch(vm.model, key, innerHandler, { + store: vm + }) + ); } } // vm中一定有_widget Widget.current._watchers || (Widget.current._watchers = []); - Widget.current._watchers = Widget.current._watchers.concat(watchers); - + Widget.current._watchers = + Widget.current._watchers.concat(watchers); + return; } handler = watch; watch = vm; - Widget.current.$watchDelayCallbacks || (Widget.current.$watchDelayCallbacks = []); + Widget.current.$watchDelayCallbacks || + (Widget.current.$watchDelayCallbacks = []); Widget.current.$watchDelayCallbacks.push([watch, handler]); } } @@ -994,7 +1077,7 @@ export function onBeforeMount(beforeMount) { if (current) { if (current.__isMounting) { beforeMount(); - + return; } if (!current.beforeMount) { @@ -1010,7 +1093,7 @@ export function onMounted(mounted) { if (current) { if (current._isMounted && !this.__async) { mounted(); - + return; } if (!current.mounted) { @@ -1048,7 +1131,7 @@ Widget.registerRenderEngine = function (engine) { Widget._renderEngine = engine; }; Widget.registerRenderEngine({ - createElement (widget) { + createElement(widget) { if (isWidget(widget)) { const o = widget.options; if (o.element) { @@ -1057,15 +1140,15 @@ Widget.registerRenderEngine({ if (o.tagName) { return BI.$(document.createElement(o.tagName)); } - + return BI.$(document.createDocumentFragment()); } - + return BI.$(widget); }, - createFragment () { + createFragment() { return document.createDocumentFragment(); - }, + } }); export function mount(widget, container, predicate, hydrate) { @@ -1087,7 +1170,7 @@ export function mount(widget, container, predicate, hydrate) { const c = Widget._renderEngine.createElement; DOM.patchProps(widget.element, c(c(container).children()[0])); - const triggerLifeHook = w => { + const triggerLifeHook = (w) => { w.beforeMount && w.beforeMount(); w.mounted && w.mounted(); each(w._children, (i, child) => { @@ -1096,12 +1179,12 @@ export function mount(widget, container, predicate, hydrate) { }; // 最后触发组件树生命周期函数 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 92ad4db34..7cad97339 100644 --- a/src/core/5.inject.js +++ b/src/core/5.inject.js @@ -4,6 +4,7 @@ import { Widget } from "./4.widget"; import { Plugin } from "./6.plugin"; import { aspect } from "./structure"; import { Events } from "./constant"; +import { _global } from "./0.foundation"; const moduleInjection = {}, moduleInjectionMap = { components: {}, diff --git a/src/core/controller/controller.resizer.js b/src/core/controller/controller.resizer.js index e14ee1ad0..802f7f69e 100644 --- a/src/core/controller/controller.resizer.js +++ b/src/core/controller/controller.resizer.js @@ -6,6 +6,7 @@ import { Controller } from "./0.controller"; import { isNull, each, debounce, isNotNull, isFunction } from "../2.base"; import { Widget } from "../4.widget"; +import { _global } from "../0.foundation"; export class ResizeController extends Controller { init() { diff --git a/src/core/func/alias.js b/src/core/func/alias.js index b8596e7cf..8c7e802ff 100644 --- a/src/core/func/alias.js +++ b/src/core/func/alias.js @@ -1,20 +1,9 @@ -import {each, isFunction, isNull, isObject, isPlainObject, keys, leftPad, parseDateTime, values} from "../2.base"; -import {replaceAll} from "./string"; -import {getFullDayName, getMonthName, getTimezone} from "./date"; - -let _global; -if (typeof window !== "undefined") { - _global = window; -} else if (typeof global !== "undefined") { - _global = global; -} else if (typeof self !== "undefined") { - _global = self; -} else { - _global = this; -} -if (!_global.BI) { - _global.BI = {}; -} +import { each, isFunction, isNull, isObject, isPlainObject, keys, leftPad, parseDateTime, values } from "../2.base"; +import { replaceAll } from "./string"; +import { getFullDayName, getMonthName, getTimezone } from "./date"; +import { _global } from "../0.foundation"; + +export const specialCharsMap = {}; function isEmpty(value) { // 判断是否为空值 @@ -50,7 +39,7 @@ function _eFormat(text, fmt) { let neg = num < 0 ? (num *= -1, "-") : "", magnitudeNeg = ""; - const funcName = num > 0 && num < 1 ? "floor" : "ceil"; // -0.9999->-1 + const funcName = num > 0 && num < 1 ? "floor" : "ceil"; // -0.9999->-1 // 数量级 let magnitude = Math[funcName](Math.log(num) / Math.log(10)); @@ -88,7 +77,7 @@ function _eFormat(text, fmt) { // 格式化指数的部分 magnitude = formatExponential(format, magnitude, magnitudeNeg); - return neg + num + "E" + magnitude; + return `${neg + num}E${magnitude}`; } // 获取format格式规定的数量级的形式 @@ -100,7 +89,7 @@ function _eFormat(text, fmt) { format = format.split(/e/ig)[1]; while (num.length < format.length) { - num = "0" + num; + num = `0${num}`; } // 如果magnitudeNeg是一个"-",而且num正好全是0,那么就别显示负号了 @@ -151,13 +140,14 @@ function _eFormat(text, fmt) { // 判断num通过round函数之后是否有进位 function isValueCarried(num) { let roundNum = Math.round(num); - num = (num + "").split(".")[0]; - roundNum = (roundNum + "").split(".")[0]; + num = (`${num}`).split(".")[0]; + roundNum = (`${roundNum}`).split(".")[0]; + return num.length !== roundNum.length; } } -//'#.##'之类的格式处理 1.324e-18 这种的科学数字 +// '#.##'之类的格式处理 1.324e-18 这种的科学数字 function _dealNumberPrecision(text, fright) { if (/[eE]/.test(text)) { let precision = 0, i = 0, ch; @@ -171,6 +161,7 @@ function _dealNumberPrecision(text, fright) { precision++; } } + return Number(text).toFixed(precision); } @@ -181,9 +172,9 @@ function _dealNumberPrecision(text, fright) { * 数字格式 */ function _numberFormat(text, format) { - text = text + ""; + text = `${text}`; - //在调用数字格式的时候如果text里没有任何数字则不处理 + // 在调用数字格式的时候如果text里没有任何数字则不处理 if (!(/[0-9]/.test(text)) || !format) { return text; } @@ -192,14 +183,14 @@ function _numberFormat(text, format) { const numMod = format.indexOf(";"); if (numMod > -1) { if (text >= 0) { - return _numberFormat(text + "", format.substring(0, numMod)); + return _numberFormat(`${text}`, format.substring(0, numMod)); } - return _numberFormat((-text) + "", format.substring(numMod + 1)); - + + return _numberFormat(`${-text}`, format.substring(numMod + 1)); } else { // 兼容格式处理负数的情况(copy:fr-jquery.format.js) if (+text < 0 && format.charAt(0) !== "-") { - return _numberFormat((-text) + "", "-" + format); + return _numberFormat(`${-text}`, `-${format}`); } } @@ -218,19 +209,19 @@ function _numberFormat(text, format) { let right = _dealWithRight(tright, fright); if (right.leftPlus) { // 小数点后有进位 - tleft = parseInt(tleft) + 1 + ""; + tleft = `${parseInt(tleft) + 1}`; tleft = isNaN(tleft) ? "1" : tleft; } right = right.num; let left = _dealWithLeft(tleft, fleft); if (!(/[0-9]/.test(left))) { - left = left + "0"; + left = `${left}0`; } if (!(/[0-9]/.test(right))) { return left + right; } else { - return left + "." + right; + return `${left}.${right}`; } } @@ -272,7 +263,7 @@ function _dealWithRight(tright, fright) { if (numReg) { const num = numReg[0]; const orilen = num.length; - let newnum = parseInt(num) + 1 + ""; + let newnum = `${parseInt(num) + 1}`; // 进位到整数部分 if (newnum.length > orilen) { newnum = newnum.substring(1); @@ -284,6 +275,7 @@ function _dealWithRight(tright, fright) { } } result.num = right; + return result; } @@ -324,7 +316,7 @@ function _dealWithLeft(tleft, fleft) { if (com) { combo = com[0].length - 1; } - left = "," + left; + left = `,${left}`; } break; default : @@ -345,15 +337,16 @@ function _dealWithLeft(tleft, fleft) { newstr = ""; let n = res.length - 1 - combo; for (; n >= 0; n = n - combo) { - newstr = res.substring(n, combo) + "," + newstr; + newstr = `${res.substring(n, combo)},${newstr}`; } const lres = res.substring(0, n + combo); if (!isEmpty(lres)) { - newstr = lres + "," + newstr; + newstr = `${lres},${newstr}`; } } left = left.replace(/[0-9]+,/, newstr); } + return left; } @@ -367,7 +360,7 @@ export const cjkEncode = function (text) { for (let i = 0; i < text.length; i++) { const code = text.charCodeAt(i); if (code >= 128 || code === 91 || code === 93) {// 91 is "[", 93 is "]". - newText += "[" + code.toString(16) + "]"; + newText += `[${code.toString(16)}]`; } else { newText += text.charAt(i); } @@ -401,7 +394,7 @@ export const cjkDecode = function (text) { const subText = text.substring(i + 1, rightIdx); // james:主要是考虑[CDATA[]]这样的值的出现 if (subText.length > 0) { - ch = String.fromCharCode(eval("0x" + subText)); + ch = String.fromCharCode(eval(`0x${subText}`)); } i = rightIdx; @@ -424,13 +417,11 @@ const SPECIAL_TAGS = { "\n": " ", }; export const htmlEncode = function (text) { - return isNull(text) ? "" : replaceAll(text + "", keys(SPECIAL_TAGS).join("|"), function (v) { - return SPECIAL_TAGS[v] ? SPECIAL_TAGS[v] : v; - }); + return isNull(text) ? "" : replaceAll(`${text}`, keys(SPECIAL_TAGS).join("|"), v => SPECIAL_TAGS[v] ? SPECIAL_TAGS[v] : v); }; // html decode export const htmlDecode = function (text) { - return isNull(text) ? "" : replaceAll(text + "", values(SPECIAL_TAGS).join("|"), function (v) { + return isNull(text) ? "" : replaceAll(`${text}`, values(SPECIAL_TAGS).join("|"), v => { switch (v) { case "&": return "&"; @@ -453,7 +444,7 @@ export const htmlDecode = function (text) { export const cjkEncodeDO = function (o) { if (isPlainObject(o)) { const result = {}; - each(o, function (v, k) { + each(o, (v, k) => { if (!(typeof v === "string")) { v = jsonEncode(v); } @@ -461,8 +452,10 @@ export const cjkEncodeDO = function (o) { k = cjkEncode(k); result[k] = cjkEncode(v); }); + return result; } + return o; }; @@ -485,18 +478,20 @@ export const jsonEncode = function (o) { const encodeString = function (s) { if (/["\\\x00-\x1f]/.test(s)) { - return "\"" + s.replace(/([\x00-\x1f\\"])/g, function (a, b) { + return `"${s.replace(/([\x00-\x1f\\"])/g, (a, b) => { let c = m[b]; if (c) { return c; } c = b.charCodeAt(); - return "\\u00" + - Math.floor(c / 16).toString(16) + - (c % 16).toString(16); - }) + "\""; - } - return "\"" + s + "\""; + + return `\\u00${ + Math.floor(c / 16).toString(16) + }${(c % 16).toString(16)}`; + })}"`; + } + + return `"${s}"`; }; const encodeArray = function (o) { @@ -517,6 +512,7 @@ export const jsonEncode = function (o) { } } a.push("]"); + return a.join(""); }; @@ -560,12 +556,11 @@ export const jsonEncode = function (o) { } } a.push("}"); + return a.join(""); - }; export const jsonDecode = function (text) { - let jo; try { jo = JSON.parse(text); @@ -578,7 +573,7 @@ export const jsonDecode = function (text) { * 比如:var str = "{'a':'b'}",这种形式的字符串转换为JSON就会抛异常 */ try { - jo = new Function("return " + text)() || {}; + jo = new Function(`return ${text}`)() || {}; } catch (e) { // do nothing } @@ -594,6 +589,7 @@ export const jsonDecode = function (text) { if (!json || typeof json !== "string") { return false; } + return json.indexOf("__time__") !== -1; } @@ -612,7 +608,7 @@ export const jsonDecode = function (text) { } return o; - })(jo); + }(jo)); }; /** @@ -624,34 +620,31 @@ export const jsonDecode = function (text) { * BI.getEncodeURL("design/{tableName}/{fieldName}",{tableName: "A", fieldName: "a"}) // design/A/a */ export const getEncodeURL = function (urlTemplate, param) { - return replaceAll(urlTemplate, "\\{(.*?)\\}", function (ori, str) { - return encodeURIComponent(isObject(param) ? param[str] : param); - }); + return replaceAll(urlTemplate, "\\{(.*?)\\}", (ori, str) => encodeURIComponent(isObject(param) ? param[str] : param)); }; export const encodeURIComponent = function (url) { - BI.specialCharsMap = BI.specialCharsMap || {}; url = url || ""; - url = replaceAll(url + "", keys(BI.specialCharsMap || []).join("|"), function (str) { + url = replaceAll(`${url}`, keys(specialCharsMap || []).join("|"), str => { switch (str) { case "\\": - return BI.specialCharsMap["\\\\"] || str; + return specialCharsMap["\\\\"] || str; default: - return BI.specialCharsMap[str] || str; + return specialCharsMap[str] || str; } }); + return _global.encodeURIComponent(url); }; export const decodeURIComponent = function (url) { const reserveSpecialCharsMap = {}; - each(BI.specialCharsMap, function (initialChar, encodeChar) { + each(specialCharsMap, (initialChar, encodeChar) => { reserveSpecialCharsMap[encodeChar] = initialChar === "\\\\" ? "\\" : initialChar; }); url = url || ""; - url = replaceAll(url + "", keys(reserveSpecialCharsMap || []).join("|"), function (str) { - return reserveSpecialCharsMap[str] || str; - }); + url = replaceAll(`${url}`, keys(reserveSpecialCharsMap || []).join("|"), str => reserveSpecialCharsMap[str] || str); + return _global.decodeURIComponent(url); }; @@ -675,8 +668,8 @@ export const contentFormat = function (cv, fmt) { // 毫秒数类型 cv = new Date(cv); } else { - //字符串类型转化为date类型 - cv = new Date(Date.parse(("" + cv).replace(/-|\./g, "/"))); + // 字符串类型转化为date类型 + cv = new Date(Date.parse((`${cv}`).replace(/-|\./g, "/"))); } } if (!isInvalidDate(cv) && !isNull(cv)) { @@ -692,6 +685,7 @@ export const contentFormat = function (cv, fmt) { } // ¤ - 货币格式 text = text.replace(/¤/g, "¥"); + return text; }; @@ -704,36 +698,36 @@ export const parseFmt = function (fmt) { if (!fmt) { return ""; } - //日期 + // 日期 fmt = String(fmt) - //年 - .replace(/y{4,}/g, "%Y")//yyyy的时候替换为Y - .replace(/y{2}/g, "%y")//yy的时候替换为y - //月 - .replace(/M{4,}/g, "%b")//MMMM的时候替换为b,八 - .replace(/M{3}/g, "%B")//MMM的时候替换为M,八月 - .replace(/M{2}/g, "%X")//MM的时候替换为X,08 - .replace(/M{1}/g, "%x")//M的时候替换为x,8 + // 年 + .replace(/y{4,}/g, "%Y")// yyyy的时候替换为Y + .replace(/y{2}/g, "%y")// yy的时候替换为y + // 月 + .replace(/M{4,}/g, "%b")// MMMM的时候替换为b,八 + .replace(/M{3}/g, "%B")// MMM的时候替换为M,八月 + .replace(/M{2}/g, "%X")// MM的时候替换为X,08 + .replace(/M{1}/g, "%x")// M的时候替换为x,8 .replace(/a{1}/g, "%p"); - //天 + // 天 if (new RegExp("d{2,}", "g").test(fmt)) { - fmt = fmt.replace(/d{2,}/g, "%d");//dd的时候替换为d + fmt = fmt.replace(/d{2,}/g, "%d");// dd的时候替换为d } else { - fmt = fmt.replace(/d{1}/g, "%e");//d的时候替换为j + fmt = fmt.replace(/d{1}/g, "%e");// d的时候替换为j } - //时 - if (new RegExp("h{2,}", "g").test(fmt)) {//12小时制 + // 时 + if (new RegExp("h{2,}", "g").test(fmt)) {// 12小时制 fmt = fmt.replace(/h{2,}/g, "%I"); } else { fmt = fmt.replace(/h{1}/g, "%I"); } - if (new RegExp("H{2,}", "g").test(fmt)) {//24小时制 + if (new RegExp("H{2,}", "g").test(fmt)) {// 24小时制 fmt = fmt.replace(/H{2,}/g, "%H"); } else { fmt = fmt.replace(/H{1}/g, "%H"); } - fmt = fmt.replace(/m{2,}/g, "%M")//分 - //秒 + fmt = fmt.replace(/m{2,}/g, "%M")// 分 + // 秒 .replace(/s{2,}/g, "%S"); return fmt; @@ -753,6 +747,7 @@ export const str2Date = function (str, format) { return null; } const fmt = parseFmt(format); + return parseDateTime(str, fmt); }; @@ -777,8 +772,8 @@ export const date2Str = function (date, format) { const ch = format.charAt(i); if (flagch !== ch) { result += compileJFmt({ - char: flagch, - str: str, + "char": flagch, + str, len: i - start, }, date); flagch = ch; @@ -789,22 +784,23 @@ export const date2Str = function (date, format) { } } result += compileJFmt({ - char: flagch, - str: str, + "char": flagch, + str, len: len - start, }, date); } + return result; function compileJFmt(jfmt, date) { - let str = jfmt.str, len = jfmt.len, ch = jfmt["char"]; + let str = jfmt.str, len = jfmt.len, ch = jfmt.char; switch (ch) { case "E": // 星期 str = getFullDayName(date.getDay()); break; case "y": // 年 if (len <= 3) { - str = (date.getFullYear() + "").slice(2, 4); + str = (`${date.getFullYear()}`).slice(2, 4); } else { str = date.getFullYear(); } @@ -815,12 +811,12 @@ export const date2Str = function (date, format) { } else if (len < 2) { str = date.getMonth() + 1; } else { - str = leftPad(date.getMonth() + 1 + "", 2, "0"); + str = leftPad(`${date.getMonth() + 1}`, 2, "0"); } break; case "d": // 日 if (len > 1) { - str = leftPad(date.getDate() + "", 2, "0"); + str = leftPad(`${date.getDate()}`, 2, "0"); } else { str = date.getDate(); } @@ -831,28 +827,28 @@ export const date2Str = function (date, format) { hour = 12; } if (len > 1) { - str = leftPad(hour + "", 2, "0"); + str = leftPad(`${hour}`, 2, "0"); } else { str = hour; } break; case "H": // 时(24) if (len > 1) { - str = leftPad(date.getHours() + "", 2, "0"); + str = leftPad(`${date.getHours()}`, 2, "0"); } else { str = date.getHours(); } break; case "m": if (len > 1) { - str = leftPad(date.getMinutes() + "", 2, "0"); + str = leftPad(`${date.getMinutes()}`, 2, "0"); } else { str = date.getMinutes(); } break; case "s": if (len > 1) { - str = leftPad(date.getSeconds() + "", 2, "0"); + str = leftPad(`${date.getSeconds()}`, 2, "0"); } else { str = date.getSeconds(); } @@ -867,6 +863,7 @@ export const date2Str = function (date, format) { str = jfmt.str; break; } + return str; } }; @@ -878,10 +875,11 @@ export const object2Number = function (value) { if (typeof value === "number") { return value; } - const str = value + ""; + const str = `${value}`; if (str.indexOf(".") === -1) { return parseInt(str); } + return parseFloat(str); }; @@ -894,7 +892,7 @@ export const object2Date = function (obj) { } else if (typeof obj === "number") { return new Date(obj); } - let str = obj + ""; + let str = `${obj}`; str = str.replace(/-/g, "/"); const dt = new Date(str); if (!isInvalidDate(dt)) { @@ -902,7 +900,6 @@ export const object2Date = function (obj) { } return new Date(); - }; export const object2Time = function (obj) { @@ -912,14 +909,14 @@ export const object2Time = function (obj) { if (obj instanceof Date) { return obj; } - let str = obj + ""; + let str = `${obj}`; str = str.replace(/-/g, "/"); let dt = new Date(str); if (!isInvalidDate(dt)) { return dt; } if (str.indexOf("/") === -1 && str.indexOf(":") !== -1) { - dt = new Date("1970/01/01 " + str); + dt = new Date(`1970/01/01 ${str}`); if (!isInvalidDate(dt)) { return dt; } @@ -928,6 +925,6 @@ export const object2Time = function (obj) { if (!isInvalidDate(dt)) { return dt; } + return new Date(); - }; diff --git a/src/core/func/date.js b/src/core/func/date.js index f629fb22a..b592ad7d7 100644 --- a/src/core/func/date.js +++ b/src/core/func/date.js @@ -3,6 +3,7 @@ import { getDate, getTime, parseInt } from "../2.base"; import { i18nText } from "../utils"; import { StartOfWeek } from "../constant"; import { isKhtml } from "../platform/web"; +import { _global } from "../0.foundation"; const SECOND = 1000; const MINUTE = 60 * SECOND; diff --git a/src/core/index.js b/src/core/index.js index 89b01230c..861f82bcb 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -14,10 +14,10 @@ export { PopoverController } from "./controller/controller.popover"; export { ResizeController } from "./controller/controller.resizer"; export { TooltipsController } from "./controller/controller.tooltips"; -export * from "./decorator"; export * from "./2.base"; export * from "./3.ob"; export * from "./4.widget"; + export * from "./5.inject"; export * from "./6.plugin"; export * from "./system"; @@ -32,3 +32,6 @@ export * from "./logic"; export * from "./wrapper"; export * from "./platform/web"; export * from "./utils"; + + +export { shortcut, provider } from "./decorator"; \ No newline at end of file diff --git a/src/core/loader/loader.style.js b/src/core/loader/loader.style.js index c775ff49a..a8b1dd2b0 100644 --- a/src/core/loader/loader.style.js +++ b/src/core/loader/loader.style.js @@ -5,6 +5,7 @@ */ import { extend, isNotNull } from "../2.base"; import { OB } from "../3.ob"; +import { _global } from "../0.foundation"; export class StyleLoaderManager extends OB { _defaultConfig() { diff --git a/src/core/platform/web/function.js b/src/core/platform/web/function.js index 2044e4160..5ab7fd47b 100644 --- a/src/core/platform/web/function.js +++ b/src/core/platform/web/function.js @@ -1,5 +1,6 @@ // 浏览器相关方法 import { isString } from "../../2.base"; +import { _global } from "../../0.foundation"; let __isIE; diff --git a/src/core/platform/web/jquery/_jquery.js b/src/core/platform/web/jquery/_jquery.js index a0e0ca2a7..017d94ecc 100644 --- a/src/core/platform/web/jquery/_jquery.js +++ b/src/core/platform/web/jquery/_jquery.js @@ -1,3 +1,7 @@ import jQuery from "jquery"; +import { _global } from "@/core/0.foundation"; -BI.jQuery = BI.$ = jQuery; +// todo:先垫着,不然开发会崩 +_global.BI = _global.BI || {}; + +_global.BI.jQuery = _global.BI.$ = jQuery; diff --git a/src/core/platform/web/jquery/fn.js b/src/core/platform/web/jquery/fn.js index 16041a83e..6af28974b 100644 --- a/src/core/platform/web/jquery/fn.js +++ b/src/core/platform/web/jquery/fn.js @@ -3,6 +3,7 @@ import { htmlEncode } from "../../../func"; import { toUpperCase, remove, camelize, isKey, isNull, isNotEmptyString, map, hyphenate } from "../../../2.base"; import { makeFirstPY } from "../../../utils"; import { createWidget } from "../../../5.inject"; +import { _global } from "../../../0.foundation"; BI.jQuery.fn.extend({ diff --git a/src/core/platform/web/jquery/jquery.mousewheel.js b/src/core/platform/web/jquery/jquery.mousewheel.js index 576658a56..f55fd91e9 100644 --- a/src/core/platform/web/jquery/jquery.mousewheel.js +++ b/src/core/platform/web/jquery/jquery.mousewheel.js @@ -1,3 +1,5 @@ +import { _global } from "../../../0.foundation"; + /* eslint-disable */ /* ! * jQuery Mousewheel 3.1.13 diff --git a/src/core/structure/aes.js b/src/core/structure/aes.js index b21b49aaa..f2e650d89 100644 --- a/src/core/structure/aes.js +++ b/src/core/structure/aes.js @@ -7,10 +7,11 @@ code.google.com/p/crypto-js/wiki/License /** * CryptoJS core components. */ -BI.CRYPT_TYPE = BI.CRYPT_TYPE || {}; -BI.CRYPT_TYPE.AES = "aes"; -const CryptoJS = CryptoJS || (function (Math, undefined) { + +export const CRYPT_TYPE = { AES: "aes" }; + +const CryptoJS = (function (Math, undefined) { /** * CryptoJS namespace. */ diff --git a/src/core/structure/prefixIntervalTree.js b/src/core/structure/prefixIntervalTree.js index a1356970f..f4e58cbc4 100644 --- a/src/core/structure/prefixIntervalTree.js +++ b/src/core/structure/prefixIntervalTree.js @@ -1,3 +1,5 @@ +import { _global } from "../0.foundation"; + // 线段树 const parent = function (node) { return Math.floor(node / 2); diff --git a/src/core/system.js b/src/core/system.js index 0d6c69a1f..dc66fd40b 100644 --- a/src/core/system.js +++ b/src/core/system.js @@ -3,7 +3,8 @@ * @version 2.0 * Created by windy on 2021/6/30 */ -import { deepExtend, extend, inherit } from "./2.base"; +import { prepares } from "./0.foundation"; +import { deepExtend, extend, inherit, object } from "./2.base"; import { OB } from "./3.ob"; import { Providers } from "./5.inject"; import { provider } from "./decorator"; @@ -68,6 +69,39 @@ const sizeMap = { L: 24, }; +class SystemProviderOB extends OB { + getSize () { + const size = system.size; + const H_GAP_SIZE = sizeMap[size.H_GAP_SIZE]; + const V_GAP_SIZE = sizeMap[size.V_GAP_SIZE]; + + return extend({}, size, { + H_GAP_SIZE, + V_GAP_SIZE, + }); + } + + getResponsiveMode () { + return system.responsiveMode; + } + + getWorkerMode () { + return system.workerMode; + } + + getLayoutOptimize () { + return system.layoutOptimize; + } + + getDependencies () { + return system.dependencies; + } + + getLoading(config) { + return system.loadingCreator(config); + } +} + @provider() export class SystemProvider { static xtype = "bi.provider.system"; @@ -106,39 +140,7 @@ export class SystemProvider { }; $get() { - return inherit(OB, { - - getSize () { - const size = system.size; - const H_GAP_SIZE = sizeMap[size.H_GAP_SIZE]; - const V_GAP_SIZE = sizeMap[size.V_GAP_SIZE]; - - return extend({}, size, { - H_GAP_SIZE, - V_GAP_SIZE, - }); - }, - - getResponsiveMode () { - return system.responsiveMode; - }, - - getWorkerMode () { - return system.workerMode; - }, - - getLayoutOptimize () { - return system.layoutOptimize; - }, - - getDependencies () { - return system.dependencies; - }, - - getLoading(config) { - return system.loadingCreator(config); - }, - }); + return SystemProviderOB; } } @@ -146,7 +148,7 @@ export const SIZE_CONSANTS = {}; // 不再增加线型的配置了,之后不维护前置版本直接删掉,都用实线连接线 export const STYLE_CONSTANTS = {}; -BI.prepares.push(() => { +prepares.push(() => { extend(SIZE_CONSANTS, Providers.getProvider("bi.provider.system").getSize()); STYLE_CONSTANTS.LINK_LINE_TYPE = SIZE_CONSANTS.LIST_ITEM_HEIGHT === 24 ? "dashed" : "solid"; }); diff --git a/src/core/utils/events/mousemovetracker.js b/src/core/utils/events/mousemovetracker.js index 63c02e13a..84255c70d 100644 --- a/src/core/utils/events/mousemovetracker.js +++ b/src/core/utils/events/mousemovetracker.js @@ -1,5 +1,6 @@ import { EventListener } from "./eventlistener"; import { bind } from "../../2.base"; +import { _global } from "../../0.foundation"; const cancelAnimationFrame = _global.cancelAnimationFrame || diff --git a/src/core/utils/events/wheelhandler.js b/src/core/utils/events/wheelhandler.js index 366b5afa6..abae9a308 100644 --- a/src/core/utils/events/wheelhandler.js +++ b/src/core/utils/events/wheelhandler.js @@ -1,4 +1,5 @@ import { bind } from "../../2.base"; +import { _global } from "../../0.foundation"; const PIXEL_STEP = 10; const LINE_HEIGHT = 40; diff --git a/test/prepare.js b/test/prepare.js deleted file mode 100644 index 849a7aa0f..000000000 --- a/test/prepare.js +++ /dev/null @@ -1,6 +0,0 @@ -!(function () { - // 先把准备环境准备好 - while(BI.prepares && BI.prepares.length > 0) { - BI.prepares.shift()(); - } -})(); \ No newline at end of file diff --git a/test/utils.js b/test/utils.js deleted file mode 100644 index 8ecf90a72..000000000 --- a/test/utils.js +++ /dev/null @@ -1,47 +0,0 @@ -!(function () { - BI.Test = {}; - BI._.extend(BI.Test, { - createWidget: function (widgetJson) { - var widget = BI.createWidget(BI.extend(widgetJson, { - root: true - })); - widget.element.appendTo("body"); - return widget; - }, - - /** - * 模拟一次输入框的keydown事件 - */ - triggerKeyDown: function (element, value, keyCode, callback) { - // keydown - var e = BI.$.Event("keydown"); - e.keyCode = keyCode; - element.trigger(e); - - // input - BI.isNotNull(value) && element.val(value); - var e1 = BI.$.Event("input"); - e1.originalEvent = {}; - e1.keyCode = keyCode; - element.trigger(e1); - - // keyup 至少等300ms后触发 - var e2 = BI.$.Event("keyup"); - e2.keyCode = keyCode; - element.trigger(e2); - BI.delay(function () { - callback(); - }, 300); - }, - - /** - * 模拟一次鼠标hover - */ - triggerMouseover: function (element, callback) { - // keydown - var e = BI.$.Event("mouseover"); - element.trigger(e); - callback && callback(); - } - }) -})(); \ No newline at end of file