Browse Source

refact: KERNEL-14316 去掉 jQuery 以外的全局变量

es6
Treecat 2 years ago
parent
commit
be9a5e8512
  1. 4
      package.json
  2. 28
      rollup.config.js
  3. 18
      src/core/0.foundation.js
  4. 644
      src/core/2.base.js
  5. 8
      src/core/3.ob.js
  6. 237
      src/core/4.widget.js
  7. 1
      src/core/5.inject.js
  8. 1
      src/core/controller/controller.resizer.js
  9. 197
      src/core/func/alias.js
  10. 1
      src/core/func/date.js
  11. 5
      src/core/index.js
  12. 1
      src/core/loader/loader.style.js
  13. 1
      src/core/platform/web/function.js
  14. 6
      src/core/platform/web/jquery/_jquery.js
  15. 1
      src/core/platform/web/jquery/fn.js
  16. 2
      src/core/platform/web/jquery/jquery.mousewheel.js
  17. 7
      src/core/structure/aes.js
  18. 2
      src/core/structure/prefixIntervalTree.js
  19. 72
      src/core/system.js
  20. 1
      src/core/utils/events/mousemovetracker.js
  21. 1
      src/core/utils/events/wheelhandler.js
  22. 6
      test/prepare.js
  23. 47
      test/utils.js

4
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",

28
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(),
],
},
];

18
src/core/0.foundation.js vendored

@ -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
};

644
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,7 +28,9 @@ 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);
};
@ -45,7 +59,24 @@ 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);
@ -56,7 +87,7 @@ export function UUID() {
}
export function isWidget(widget) {
return widget instanceof BI.Widget;
return widget instanceof Widget;
}
export function createWidgets(items, options, context) {
@ -70,31 +101,37 @@ export function createWidgets(items, options, context) {
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);
@ -114,13 +151,15 @@ 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;
@ -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;
@ -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,10 +445,15 @@ 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;
}
}
@ -374,8 +462,36 @@ export function abc2Int(string) {
}
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 "";
}
@ -392,12 +508,33 @@ 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"
], 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);
});
@ -484,14 +621,48 @@ export function uniq(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();
@ -555,10 +726,13 @@ export function inherit(sp, overrides) {
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;
@ -593,8 +767,8 @@ 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;
}
@ -661,7 +841,9 @@ export function isDeepMatch(object, attrs) {
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) {
@ -760,9 +942,21 @@ export function deepDiff(object, other) {
}
// 通用方法
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;
}));
});
}
};
}());
@ -876,7 +1082,9 @@ export function parseSafeInt(value) {
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) {
@ -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) {
@ -970,9 +1180,7 @@ 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");
}
/**
* 让字符串通过指定字符做补齐的函数
*
@ -1130,7 +1337,9 @@ export function checkDateVoid(YY, MM, DD, minDate, maxDate) {
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;
}
@ -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];
}
@ -1295,49 +1515,61 @@ 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._;

8
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,14 +65,14 @@ 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);
});
@ -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);
}

237
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,7 +154,10 @@ export class Widget extends OB {
const init = () => {
// 加个保险
if (initCallbackCalled === true) {
_global.console && console.error("组件: 请检查beforeInit内部的写法,callback只能执行一次");
_global.console &&
console.error(
"组件: 请检查beforeInit内部的写法,callback只能执行一次"
);
return;
}
@ -143,7 +166,10 @@ export class Widget extends OB {
const render = () => {
// 加个保险
if (renderCallbackCalled === true) {
_global.console && console.error("组件: 请检查beforeRender内部的写法,callback只能执行一次");
_global.console &&
console.error(
"组件: 请检查beforeRender内部的写法,callback只能执行一次"
);
return;
}
@ -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,9 +284,16 @@ 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();
});
@ -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()) {
@ -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 {
@ -687,21 +770,13 @@ export class Widget extends OB {
return this.element.css(name, value);
}
getText() {
}
setText(text) {
getText() {}
}
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,12 +973,12 @@ 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);
@ -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]);
}
}
@ -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) {
@ -1063,9 +1146,9 @@ Widget.registerRenderEngine({
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) => {

1
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: {},

1
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() {

197
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": "&#10;",
};
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 "&amp;":
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 `\\u00${
Math.floor(c / 16).toString(16)
}${(c % 16).toString(16)}`;
})}"`;
}
return "\"" + s + "\"";
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("");
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();
return new Date();
};

1
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;

5
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";

1
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() {

1
src/core/platform/web/function.js

@ -1,5 +1,6 @@
// 浏览器相关方法
import { isString } from "../../2.base";
import { _global } from "../../0.foundation";
let __isIE;

6
src/core/platform/web/jquery/_jquery.js vendored

@ -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;

1
src/core/platform/web/jquery/fn.js vendored

@ -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({

2
src/core/platform/web/jquery/jquery.mousewheel.js

@ -1,3 +1,5 @@
import { _global } from "../../../0.foundation";
/* eslint-disable */
/* !
* jQuery Mousewheel 3.1.13

7
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.
*/

2
src/core/structure/prefixIntervalTree.js

@ -1,3 +1,5 @@
import { _global } from "../0.foundation";
// 线段树
const parent = function (node) {
return Math.floor(node / 2);

72
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";
});

1
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 ||

1
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;

6
test/prepare.js

@ -1,6 +0,0 @@
!(function () {
// 先把准备环境准备好
while(BI.prepares && BI.prepares.length > 0) {
BI.prepares.shift()();
}
})();

47
test/utils.js

@ -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();
}
})
})();
Loading…
Cancel
Save