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. 758
      src/core/2.base.js
  5. 10
      src/core/3.ob.js
  6. 281
      src/core/4.widget.js
  7. 1
      src/core/5.inject.js
  8. 1
      src/core/controller/controller.resizer.js
  9. 201
      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
};

758
src/core/2.base.js

File diff suppressed because it is too large Load Diff

10
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);
}

281
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);
}

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

201
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 "\"" + 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();
};

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