Browse Source

Pull request #3448: refact: KERNEL-14316 去掉 jQuery 以外的全局变量

Merge in VISUAL/fineui from ~TREECAT/fineui:es6 to es6

* commit '412824a83d77bac285d8b93372937a80310116cf':
  refact: KERNEL-14316 去掉 jQuery 以外的全局变量
es6
treecat-罗群 2 years ago
parent
commit
a9aa5e6d3a
  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/babel-preset-fineui": "^3.0.0",
"@fui/eslint-plugin": "^1.0.19", "@fui/eslint-plugin": "^1.0.19",
"@juggle/resize-observer": "^3.4.0", "@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", "@types/node": "15.6.1",
"@typescript-eslint/eslint-plugin": "2.33.0", "@typescript-eslint/eslint-plugin": "2.33.0",
"@typescript-eslint/parser": "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 resolve = require("@rollup/plugin-node-resolve");
const commonjs = require("@rollup/plugin-commonjs"); const commonjs = require("@rollup/plugin-commonjs");
const path = require("path"); 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"; const input = "src/index.js";
module.exports = [ module.exports = [
@ -16,24 +17,23 @@ module.exports = [
{ {
file: "dist/fineui.esm.js", file: "dist/fineui.esm.js",
format: "esm", format: "esm",
sourcemap: true sourcemap: true,
} },
], ],
plugins: [ plugins: [
alias({ alias({
entries: [ entries: [
{ find: "@", replacement: path.resolve(__dirname, "src") } { find: "@", replacement: path.resolve(__dirname, "src") },
] ],
}), }),
resolve(), resolve(),
babel({ babel({
babelHelpers: "runtime", babelHelpers: "inline",
presets: ["@babel/preset-env"],
plugins: [ 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. * Created by richie on 15/7/8.
*/ *
/** * 初始化 _global 对象为什么不是 globalThis
* 初始化BI对象
*/ */
let _global = undefined; let _global = undefined;
if (typeof window !== "undefined") { if (typeof window !== "undefined") {
@ -20,9 +18,9 @@ if (_global) {
_global._global = _global; _global._global = _global;
} }
if (_global.BI == null) { const prepares = [];
_global.BI = { prepares: [] };
} export {
if (_global.BI.prepares == null) { _global,
_global.BI.prepares = []; 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() { function obExtend() {
const target = arguments[0] || {}, length = arguments.length; const target = arguments[0] || {}, length = arguments.length;
@ -65,17 +65,17 @@ export class OB {
_initListeners() { _initListeners() {
if (this.options.listeners !== null) { if (this.options.listeners !== null) {
BI._.each(this.options.listeners, (lis, eventName) => { each(this.options.listeners, (eventName, lis) => {
if (isFunction(lis)) { if (isFunction(lis)) {
this.on(eventName, lis); this.on(eventName, lis);
return; return;
} }
if (isArray(lis)) { if (isArray(lis)) {
BI._.each(lis, l => { lis.forEach(l => {
this.on(eventName, l); this.on(eventName, l);
}); });
return; return;
} }
(lis.target ? lis.target : this)[lis.once ? "once" : "on"](lis.eventName, bind(lis.action, this)); (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]; const fns = this._getEvents()[eventName];
if (isArray(fns)) { if (isArray(fns)) {
const newFns = []; const newFns = [];
BI._.each(fns, ifn => { fns.forEach(ifn => {
if (ifn !== fn) { if (ifn !== fn) {
newFns.push(ifn); newFns.push(ifn);
} }

281
src/core/4.widget.js

@ -6,12 +6,27 @@
* @cfg {JSON} options 配置属性 * @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 { OB } from "./3.ob";
import { Providers, _lazyCreateWidget } from "./5.inject"; import { Providers, _lazyCreateWidget } from "./5.inject";
import { DOM } from "./utils"; import { DOM } from "./utils";
import { Events, emptyFn, pixFormat } from "./constant"; import { Events, emptyFn, pixFormat } from "./constant";
import { Plugin } from "./6.plugin"; import { Plugin } from "./6.plugin";
import { _global } from "./0.foundation";
const cancelAnimationFrame = const cancelAnimationFrame =
_global.cancelAnimationFrame || _global.cancelAnimationFrame ||
@ -21,10 +36,17 @@ const cancelAnimationFrame =
_global.msCancelAnimationFrame || _global.msCancelAnimationFrame ||
_global.clearTimeout; _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) { function callLifeHook(self, life) {
let hooks = [], hook; let hooks = [],
hook;
hook = self[life]; hook = self[life];
if (hook) { if (hook) {
hooks = hooks.concat(isArray(hook) ? hook : [hook]); hooks = hooks.concat(isArray(hook) ? hook : [hook]);
@ -39,7 +61,7 @@ function callLifeHook(self, life) {
} }
export class Widget extends OB { export class Widget extends OB {
_defaultConfig () { _defaultConfig() {
return extend(super._defaultConfig(), { return extend(super._defaultConfig(), {
root: false, root: false,
tagName: "div", tagName: "div",
@ -56,18 +78,16 @@ export class Widget extends OB {
baseCls: "", baseCls: "",
extraCls: "", extraCls: "",
cls: "", cls: "",
css: null, css: null
// vdom: false // vdom: false
}); });
} }
_constructor () { _constructor() {}
}
// 覆盖父类的_constructor方法,widget不走ob的生命周期 // 覆盖父类的_constructor方法,widget不走ob的生命周期
_constructed () { _constructed() {
if (this.setup) { if (this.setup) {
pushTarget(this); pushTarget(this);
const delegate = this.setup(this.options); const delegate = this.setup(this.options);
@ -81,7 +101,7 @@ export class Widget extends OB {
} }
} }
_lazyConstructor () { _lazyConstructor() {
if (!this.__constructed) { if (!this.__constructed) {
this.__constructed = true; this.__constructed = true;
this._init(); this._init();
@ -134,8 +154,11 @@ export class Widget extends OB {
const init = () => { const init = () => {
// 加个保险 // 加个保险
if (initCallbackCalled === true) { if (initCallbackCalled === true) {
_global.console && console.error("组件: 请检查beforeInit内部的写法,callback只能执行一次"); _global.console &&
console.error(
"组件: 请检查beforeInit内部的写法,callback只能执行一次"
);
return; return;
} }
initCallbackCalled = true; initCallbackCalled = true;
@ -143,8 +166,11 @@ export class Widget extends OB {
const render = () => { const render = () => {
// 加个保险 // 加个保险
if (renderCallbackCalled === true) { if (renderCallbackCalled === true) {
_global.console && console.error("组件: 请检查beforeRender内部的写法,callback只能执行一次"); _global.console &&
console.error(
"组件: 请检查beforeRender内部的写法,callback只能执行一次"
);
return; return;
} }
renderCallbackCalled = true; renderCallbackCalled = true;
@ -154,9 +180,11 @@ export class Widget extends OB {
if (this.options.beforeRender || this.beforeRender) { if (this.options.beforeRender || this.beforeRender) {
this.__async = true; 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) { if (beforeRenderResult instanceof Promise) {
beforeRenderResult.then(render).catch(e => { beforeRenderResult.then(render).catch((e) => {
_global.console && console.error(e); _global.console && console.error(e);
render(); render();
}); });
@ -169,9 +197,11 @@ export class Widget extends OB {
if (this.options.beforeInit || this.beforeInit) { if (this.options.beforeInit || this.beforeInit) {
this.__asking = true; 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) { if (beforeInitResult instanceof Promise) {
beforeInitResult.then(init).catch(e => { beforeInitResult.then(init).catch((e) => {
_global.console && console.error(e); _global.console && console.error(e);
init(); init();
}); });
@ -211,12 +241,14 @@ export class Widget extends OB {
this._initElementWidth(); this._initElementWidth();
this._initElementHeight(); this._initElementHeight();
if (o._baseCls || o.baseCls || o.extraCls) { 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 (o.cls) {
if (isFunction(o.cls)) { if (isFunction(o.cls)) {
let cls = this.__watch(o.cls, (context, newValue) => { 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); this.element.addClass(cls);
} else { } else {
@ -240,7 +272,7 @@ export class Widget extends OB {
newValue[k] = ""; newValue[k] = "";
} }
} }
this.element.css(css = newValue); this.element.css((css = newValue));
}); });
this.element.css(css); this.element.css(css);
} else { } else {
@ -252,13 +284,20 @@ export class Widget extends OB {
__watch(getter, handler, options) { __watch(getter, handler, options) {
if (_global.Fix) { if (_global.Fix) {
this._watchers = this._watchers || []; this._watchers = this._watchers || [];
const watcher = new Fix.Watcher(null, () => getter.call(this, this), (handler && (v => { const watcher = new Fix.Watcher(
handler.call(this, this, v); null,
})) || emptyFn, extend({ deep: true }, options)); () => getter.call(this, this),
(handler &&
((v) => {
handler.call(this, this, v);
})) ||
emptyFn,
extend({ deep: true }, options)
);
this._watchers.push(() => { this._watchers.push(() => {
watcher.teardown(); watcher.teardown();
}); });
return watcher.value; return watcher.value;
} else { } else {
return getter(); return getter();
@ -277,7 +316,8 @@ export class Widget extends OB {
if (isWidget(o.element)) { if (isWidget(o.element)) {
this.element = this.options.element.element; this.element = this.options.element.element;
this._parent = o.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) { } else if (o.element) {
this.element = Widget._renderEngine.createElement(this); this.element = Widget._renderEngine.createElement(this);
this._isRoot = true; this._isRoot = true;
@ -308,9 +348,11 @@ export class Widget extends OB {
_initVisual() { _initVisual() {
const o = this.options; const o = this.options;
if (o.invisible) { if (o.invisible) {
const invisible = o.invisible = isFunction(o.invisible) ? this.__watch(o.invisible, (context, newValue) => { const invisible = (o.invisible = isFunction(o.invisible)
this.setVisible(!newValue); ? this.__watch(o.invisible, (context, newValue) => {
}) : o.invisible; this.setVisible(!newValue);
})
: o.invisible);
if (invisible) { if (invisible) {
// 用display属性做显示和隐藏,否则jquery会在显示时将display设为block会覆盖掉display:flex属性 // 用display属性做显示和隐藏,否则jquery会在显示时将display设为block会覆盖掉display:flex属性
this.__setElementVisible(false); this.__setElementVisible(false);
@ -322,17 +364,21 @@ export class Widget extends OB {
const o = this.options; const o = this.options;
if (o.disabled || o.invalid) { if (o.disabled || o.invalid) {
if (this.options.disabled) { if (this.options.disabled) {
const disabled = o.disabled = isFunction(o.disabled) ? this.__watch(o.disabled, (context, newValue) => { const disabled = (o.disabled = isFunction(o.disabled)
this.setEnable(!newValue); ? this.__watch(o.disabled, (context, newValue) => {
}) : o.disabled; this.setEnable(!newValue);
})
: o.disabled);
if (disabled) { if (disabled) {
this.setEnable(false); this.setEnable(false);
} }
} }
if (this.options.invalid) { if (this.options.invalid) {
const invalid = o.invalid = isFunction(o.invalid) ? this.__watch(o.invalid, (context, newValue) => { const invalid = (o.invalid = isFunction(o.invalid)
this.setValid(!newValue); ? this.__watch(o.invalid, (context, newValue) => {
}) : o.invalid; this.setValid(!newValue);
})
: o.invalid);
if (invalid) { if (invalid) {
this.setValid(false); this.setValid(false);
} }
@ -365,10 +411,17 @@ export class Widget extends OB {
_initElement() { _initElement() {
this.__isMounting = true; this.__isMounting = true;
// 当开启worker模式时,可以通过$render来实现另一种效果 // 当开启worker模式时,可以通过$render来实现另一种效果
const workerMode = Providers.getProvider("bi.provider.system").getWorkerMode(); const workerMode =
const render = isFunction(this.options.render) ? this.options.render : (workerMode ? (this.$render || this.render) : this.render); 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); 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); els = Plugin.getRender(this.options.type, els);
if (isPlainObject(els)) { if (isPlainObject(els)) {
els = [els]; els = [els];
@ -378,7 +431,7 @@ export class Widget extends OB {
each(els, (i, el) => { each(els, (i, el) => {
if (el) { if (el) {
_lazyCreateWidget(el, { _lazyCreateWidget(el, {
element: this, element: this
}); });
} }
}); });
@ -400,16 +453,34 @@ export class Widget extends OB {
* @private * @private
*/ */
_mount(force, deep, lifeHook, predicate, layer) { _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; return false;
} }
layer = layer || 0; layer = layer || 0;
lifeHook !== false && !this.__async && callLifeHook(this, "beforeMount"); lifeHook !== false &&
!this.__async &&
callLifeHook(this, "beforeMount");
this._isMounted = true; this._isMounted = true;
this.__isMounting = false; this.__isMounting = false;
for (const key in this._children) { for (const key in this._children) {
const child = this._children[key]; 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) {
if (!this._parent.isEnabled()) { if (!this._parent.isEnabled()) {
@ -426,7 +497,7 @@ export class Widget extends OB {
this.__afterMount(lifeHook, predicate); this.__afterMount(lifeHook, predicate);
// }, 0); // }, 0);
} }
return true; return true;
} }
@ -454,7 +525,7 @@ export class Widget extends OB {
res = this.update && this.update(nextProps, shouldUpdate); res = this.update && this.update(nextProps, shouldUpdate);
} }
callLifeHook(this, "updated"); callLifeHook(this, "updated");
return res; return res;
} }
@ -484,7 +555,9 @@ export class Widget extends OB {
} }
// 递归将所有子组件使能 // 递归将所有子组件使能
each(this._children, (i, child) => { 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.__setElementVisible(true);
this._mount(); this._mount();
if (o.animation && !lastVisible) { 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) { if (this._requestAnimationFrame) {
cancelAnimationFrame(this._requestAnimationFrame); cancelAnimationFrame(this._requestAnimationFrame);
} }
@ -544,12 +620,17 @@ export class Widget extends OB {
clearTimeout(this._animationDuring); clearTimeout(this._animationDuring);
} }
this._animationDuring = setTimeout(() => { 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); }, o.animationDuring);
} }
} else if (visible === false) { } else if (visible === false) {
if (o.animation && lastVisible) { 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) { if (this._requestAnimationFrame) {
cancelAnimationFrame(this._requestAnimationFrame); cancelAnimationFrame(this._requestAnimationFrame);
} }
@ -561,7 +642,9 @@ export class Widget extends OB {
clearTimeout(this._animationDuring); clearTimeout(this._animationDuring);
} }
this._animationDuring = setTimeout(() => { 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); this.__setElementVisible(false);
}, o.animationDuring); }, o.animationDuring);
} else { } else {
@ -620,7 +703,7 @@ export class Widget extends OB {
// TODO: self待删 // TODO: self待删
remove(self._children, this); remove(self._children, this);
}); });
return (this._children[name] = widget); return (this._children[name] = widget);
} }
@ -634,7 +717,7 @@ export class Widget extends OB {
any(this._children, (i, wi) => { any(this._children, (i, wi) => {
if (i === name) { if (i === name) {
widget = wi; widget = wi;
return true; return true;
} }
other[i] = wi; other[i] = wi;
@ -642,7 +725,7 @@ export class Widget extends OB {
if (!widget) { if (!widget) {
any(other, (i, wi) => (widget = wi.getWidgetByName(i))); any(other, (i, wi) => (widget = wi.getWidgetByName(i)));
} }
return widget; return widget;
} }
@ -673,13 +756,13 @@ export class Widget extends OB {
attr(key, value) { attr(key, value) {
if (isPlainObject(key)) { if (isPlainObject(key)) {
each(key, (k, v) => this.attr(k, v)); each(key, (k, v) => this.attr(k, v));
return; return;
} }
if (isNotNull(value)) { if (isNotNull(value)) {
this.options[key] = value; this.options[key] = value;
} }
return this.options[key]; return this.options[key];
} }
@ -687,21 +770,13 @@ export class Widget extends OB {
return this.element.css(name, value); return this.element.css(name, value);
} }
getText() { getText() {}
}
setText(text) { setText(text) {}
} getValue() {}
getValue() {
}
setValue(value) { setValue(value) {}
}
isEnabled() { isEnabled() {
return this.options.disabled === true ? false : !this.options._disabled; return this.options.disabled === true ? false : !this.options._disabled;
@ -775,7 +850,7 @@ export class Widget extends OB {
} }
} }
_empty () { _empty() {
this._assetMounted(); this._assetMounted();
each(this._children, (i, widget) => { each(this._children, (i, widget) => {
widget && widget._unMount && widget._unMount(); widget && widget._unMount && widget._unMount();
@ -784,19 +859,19 @@ export class Widget extends OB {
this.element.empty(); this.element.empty();
} }
isolate () { isolate() {
if (this._parent) { if (this._parent) {
this._parent.removeWidget(this); this._parent.removeWidget(this);
} }
DOM.hang([this]); DOM.hang([this]);
} }
empty () { empty() {
this._empty(); this._empty();
} }
// 默认的reset方法就是干掉重来 // 默认的reset方法就是干掉重来
reset () { reset() {
// 还在异步状态的不需要执行reset // 还在异步状态的不需要执行reset
if (this.__async === true || this.__asking === true) { if (this.__async === true || this.__asking === true) {
return; return;
@ -851,8 +926,10 @@ export class Widget extends OB {
} }
} }
let context = null, current = null; let context = null,
const contextStack = [], currentStack = []; current = null;
const contextStack = [],
currentStack = [];
Widget.pushContext = function (_context) { Widget.pushContext = function (_context) {
if (context) contextStack.push(context); if (context) contextStack.push(context);
@ -896,17 +973,17 @@ export function useStore(_store) {
let origin; let origin;
if (_global.Proxy) { if (_global.Proxy) {
const proxy = new Proxy(delegate, { const proxy = new Proxy(delegate, {
get (target, key) { get(target, key) {
return Reflect.get(origin, key); return Reflect.get(origin, key);
}, },
set (target, key, value) { set(target, key, value) {
return Reflect.set(origin, key, value); return Reflect.set(origin, key, value);
}, }
}); });
current._store = function () { current._store = function () {
origin = (_store || currentStore).apply(this, arguments); origin = (_store || currentStore).apply(this, arguments);
delegate.$delegate = origin; delegate.$delegate = origin;
return origin; return origin;
}; };
current.$storeDelegate = proxy; current.$storeDelegate = proxy;
@ -916,11 +993,11 @@ export function useStore(_store) {
current._store = function () { current._store = function () {
const st = (_store || currentStore).apply(this, arguments); const st = (_store || currentStore).apply(this, arguments);
extend(delegate, st); extend(delegate, st);
return st; return st;
}; };
current.$storeDelegate = delegate; current.$storeDelegate = delegate;
return current.$storeDelegate; return current.$storeDelegate;
} }
} }
@ -945,11 +1022,11 @@ export function useContext(inject) {
} }
vm = vm._parent; vm = vm._parent;
} }
return null; return null;
} }
} }
return vm; return vm;
} }
@ -967,25 +1044,31 @@ export function watch(vm, watch, handler) {
const innerHandler = watch[key]; const innerHandler = watch[key];
if (isArray(handler)) { if (isArray(handler)) {
for (let i = 0; i < handler.length; i++) { for (let i = 0; i < handler.length; i++) {
watchers.push(Fix.watch(vm.model, key, innerHandler, { watchers.push(
store: vm, Fix.watch(vm.model, key, innerHandler, {
})); store: vm
})
);
} }
} else { } else {
watchers.push(Fix.watch(vm.model, key, innerHandler, { watchers.push(
store: vm, Fix.watch(vm.model, key, innerHandler, {
})); store: vm
})
);
} }
} }
// vm中一定有_widget // vm中一定有_widget
Widget.current._watchers || (Widget.current._watchers = []); Widget.current._watchers || (Widget.current._watchers = []);
Widget.current._watchers = Widget.current._watchers.concat(watchers); Widget.current._watchers =
Widget.current._watchers.concat(watchers);
return; return;
} }
handler = watch; handler = watch;
watch = vm; watch = vm;
Widget.current.$watchDelayCallbacks || (Widget.current.$watchDelayCallbacks = []); Widget.current.$watchDelayCallbacks ||
(Widget.current.$watchDelayCallbacks = []);
Widget.current.$watchDelayCallbacks.push([watch, handler]); Widget.current.$watchDelayCallbacks.push([watch, handler]);
} }
} }
@ -994,7 +1077,7 @@ export function onBeforeMount(beforeMount) {
if (current) { if (current) {
if (current.__isMounting) { if (current.__isMounting) {
beforeMount(); beforeMount();
return; return;
} }
if (!current.beforeMount) { if (!current.beforeMount) {
@ -1010,7 +1093,7 @@ export function onMounted(mounted) {
if (current) { if (current) {
if (current._isMounted && !this.__async) { if (current._isMounted && !this.__async) {
mounted(); mounted();
return; return;
} }
if (!current.mounted) { if (!current.mounted) {
@ -1048,7 +1131,7 @@ Widget.registerRenderEngine = function (engine) {
Widget._renderEngine = engine; Widget._renderEngine = engine;
}; };
Widget.registerRenderEngine({ Widget.registerRenderEngine({
createElement (widget) { createElement(widget) {
if (isWidget(widget)) { if (isWidget(widget)) {
const o = widget.options; const o = widget.options;
if (o.element) { if (o.element) {
@ -1057,15 +1140,15 @@ Widget.registerRenderEngine({
if (o.tagName) { if (o.tagName) {
return BI.$(document.createElement(o.tagName)); return BI.$(document.createElement(o.tagName));
} }
return BI.$(document.createDocumentFragment()); return BI.$(document.createDocumentFragment());
} }
return BI.$(widget); return BI.$(widget);
}, },
createFragment () { createFragment() {
return document.createDocumentFragment(); return document.createDocumentFragment();
}, }
}); });
export function mount(widget, container, predicate, hydrate) { export function mount(widget, container, predicate, hydrate) {
@ -1087,7 +1170,7 @@ export function mount(widget, container, predicate, hydrate) {
const c = Widget._renderEngine.createElement; const c = Widget._renderEngine.createElement;
DOM.patchProps(widget.element, c(c(container).children()[0])); DOM.patchProps(widget.element, c(c(container).children()[0]));
const triggerLifeHook = w => { const triggerLifeHook = (w) => {
w.beforeMount && w.beforeMount(); w.beforeMount && w.beforeMount();
w.mounted && w.mounted(); w.mounted && w.mounted();
each(w._children, (i, child) => { each(w._children, (i, child) => {
@ -1096,12 +1179,12 @@ export function mount(widget, container, predicate, hydrate) {
}; };
// 最后触发组件树生命周期函数 // 最后触发组件树生命周期函数
triggerLifeHook(widget); triggerLifeHook(widget);
return res; return res;
} }
if (container) { if (container) {
Widget._renderEngine.createElement(container).append(widget.element); Widget._renderEngine.createElement(container).append(widget.element);
} }
return widget._mount(true, false, false, predicate); 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 { Plugin } from "./6.plugin";
import { aspect } from "./structure"; import { aspect } from "./structure";
import { Events } from "./constant"; import { Events } from "./constant";
import { _global } from "./0.foundation";
const moduleInjection = {}, moduleInjectionMap = { const moduleInjection = {}, moduleInjectionMap = {
components: {}, components: {},

1
src/core/controller/controller.resizer.js

@ -6,6 +6,7 @@
import { Controller } from "./0.controller"; import { Controller } from "./0.controller";
import { isNull, each, debounce, isNotNull, isFunction } from "../2.base"; import { isNull, each, debounce, isNotNull, isFunction } from "../2.base";
import { Widget } from "../4.widget"; import { Widget } from "../4.widget";
import { _global } from "../0.foundation";
export class ResizeController extends Controller { export class ResizeController extends Controller {
init() { 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 { each, isFunction, isNull, isObject, isPlainObject, keys, leftPad, parseDateTime, values } from "../2.base";
import {replaceAll} from "./string"; import { replaceAll } from "./string";
import {getFullDayName, getMonthName, getTimezone} from "./date"; import { getFullDayName, getMonthName, getTimezone } from "./date";
import { _global } from "../0.foundation";
let _global;
if (typeof window !== "undefined") { export const specialCharsMap = {};
_global = window;
} else if (typeof global !== "undefined") {
_global = global;
} else if (typeof self !== "undefined") {
_global = self;
} else {
_global = this;
}
if (!_global.BI) {
_global.BI = {};
}
function isEmpty(value) { function isEmpty(value) {
// 判断是否为空值 // 判断是否为空值
@ -50,7 +39,7 @@ function _eFormat(text, fmt) {
let neg = num < 0 ? (num *= -1, "-") : "", let neg = num < 0 ? (num *= -1, "-") : "",
magnitudeNeg = ""; 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)); let magnitude = Math[funcName](Math.log(num) / Math.log(10));
@ -88,7 +77,7 @@ function _eFormat(text, fmt) {
// 格式化指数的部分 // 格式化指数的部分
magnitude = formatExponential(format, magnitude, magnitudeNeg); magnitude = formatExponential(format, magnitude, magnitudeNeg);
return neg + num + "E" + magnitude; return `${neg + num}E${magnitude}`;
} }
// 获取format格式规定的数量级的形式 // 获取format格式规定的数量级的形式
@ -100,7 +89,7 @@ function _eFormat(text, fmt) {
format = format.split(/e/ig)[1]; format = format.split(/e/ig)[1];
while (num.length < format.length) { while (num.length < format.length) {
num = "0" + num; num = `0${num}`;
} }
// 如果magnitudeNeg是一个"-",而且num正好全是0,那么就别显示负号了 // 如果magnitudeNeg是一个"-",而且num正好全是0,那么就别显示负号了
@ -151,13 +140,14 @@ function _eFormat(text, fmt) {
// 判断num通过round函数之后是否有进位 // 判断num通过round函数之后是否有进位
function isValueCarried(num) { function isValueCarried(num) {
let roundNum = Math.round(num); let roundNum = Math.round(num);
num = (num + "").split(".")[0]; num = (`${num}`).split(".")[0];
roundNum = (roundNum + "").split(".")[0]; roundNum = (`${roundNum}`).split(".")[0];
return num.length !== roundNum.length; return num.length !== roundNum.length;
} }
} }
//'#.##'之类的格式处理 1.324e-18 这种的科学数字 // '#.##'之类的格式处理 1.324e-18 这种的科学数字
function _dealNumberPrecision(text, fright) { function _dealNumberPrecision(text, fright) {
if (/[eE]/.test(text)) { if (/[eE]/.test(text)) {
let precision = 0, i = 0, ch; let precision = 0, i = 0, ch;
@ -171,6 +161,7 @@ function _dealNumberPrecision(text, fright) {
precision++; precision++;
} }
} }
return Number(text).toFixed(precision); return Number(text).toFixed(precision);
} }
@ -181,9 +172,9 @@ function _dealNumberPrecision(text, fright) {
* 数字格式 * 数字格式
*/ */
function _numberFormat(text, format) { function _numberFormat(text, format) {
text = text + ""; text = `${text}`;
//在调用数字格式的时候如果text里没有任何数字则不处理 // 在调用数字格式的时候如果text里没有任何数字则不处理
if (!(/[0-9]/.test(text)) || !format) { if (!(/[0-9]/.test(text)) || !format) {
return text; return text;
} }
@ -192,14 +183,14 @@ function _numberFormat(text, format) {
const numMod = format.indexOf(";"); const numMod = format.indexOf(";");
if (numMod > -1) { if (numMod > -1) {
if (text >= 0) { 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 { } else {
// 兼容格式处理负数的情况(copy:fr-jquery.format.js) // 兼容格式处理负数的情况(copy:fr-jquery.format.js)
if (+text < 0 && format.charAt(0) !== "-") { 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); let right = _dealWithRight(tright, fright);
if (right.leftPlus) { if (right.leftPlus) {
// 小数点后有进位 // 小数点后有进位
tleft = parseInt(tleft) + 1 + ""; tleft = `${parseInt(tleft) + 1}`;
tleft = isNaN(tleft) ? "1" : tleft; tleft = isNaN(tleft) ? "1" : tleft;
} }
right = right.num; right = right.num;
let left = _dealWithLeft(tleft, fleft); let left = _dealWithLeft(tleft, fleft);
if (!(/[0-9]/.test(left))) { if (!(/[0-9]/.test(left))) {
left = left + "0"; left = `${left}0`;
} }
if (!(/[0-9]/.test(right))) { if (!(/[0-9]/.test(right))) {
return left + right; return left + right;
} else { } else {
return left + "." + right; return `${left}.${right}`;
} }
} }
@ -272,7 +263,7 @@ function _dealWithRight(tright, fright) {
if (numReg) { if (numReg) {
const num = numReg[0]; const num = numReg[0];
const orilen = num.length; const orilen = num.length;
let newnum = parseInt(num) + 1 + ""; let newnum = `${parseInt(num) + 1}`;
// 进位到整数部分 // 进位到整数部分
if (newnum.length > orilen) { if (newnum.length > orilen) {
newnum = newnum.substring(1); newnum = newnum.substring(1);
@ -284,6 +275,7 @@ function _dealWithRight(tright, fright) {
} }
} }
result.num = right; result.num = right;
return result; return result;
} }
@ -324,7 +316,7 @@ function _dealWithLeft(tleft, fleft) {
if (com) { if (com) {
combo = com[0].length - 1; combo = com[0].length - 1;
} }
left = "," + left; left = `,${left}`;
} }
break; break;
default : default :
@ -345,15 +337,16 @@ function _dealWithLeft(tleft, fleft) {
newstr = ""; newstr = "";
let n = res.length - 1 - combo; let n = res.length - 1 - combo;
for (; n >= 0; n = n - 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); const lres = res.substring(0, n + combo);
if (!isEmpty(lres)) { if (!isEmpty(lres)) {
newstr = lres + "," + newstr; newstr = `${lres},${newstr}`;
} }
} }
left = left.replace(/[0-9]+,/, newstr); left = left.replace(/[0-9]+,/, newstr);
} }
return left; return left;
} }
@ -367,7 +360,7 @@ export const cjkEncode = function (text) {
for (let i = 0; i < text.length; i++) { for (let i = 0; i < text.length; i++) {
const code = text.charCodeAt(i); const code = text.charCodeAt(i);
if (code >= 128 || code === 91 || code === 93) {// 91 is "[", 93 is "]". if (code >= 128 || code === 91 || code === 93) {// 91 is "[", 93 is "]".
newText += "[" + code.toString(16) + "]"; newText += `[${code.toString(16)}]`;
} else { } else {
newText += text.charAt(i); newText += text.charAt(i);
} }
@ -401,7 +394,7 @@ export const cjkDecode = function (text) {
const subText = text.substring(i + 1, rightIdx); const subText = text.substring(i + 1, rightIdx);
// james:主要是考虑[CDATA[]]这样的值的出现 // james:主要是考虑[CDATA[]]这样的值的出现
if (subText.length > 0) { if (subText.length > 0) {
ch = String.fromCharCode(eval("0x" + subText)); ch = String.fromCharCode(eval(`0x${subText}`));
} }
i = rightIdx; i = rightIdx;
@ -424,13 +417,11 @@ const SPECIAL_TAGS = {
"\n": "&#10;", "\n": "&#10;",
}; };
export const htmlEncode = function (text) { export const htmlEncode = function (text) {
return isNull(text) ? "" : replaceAll(text + "", keys(SPECIAL_TAGS).join("|"), function (v) { return isNull(text) ? "" : replaceAll(`${text}`, keys(SPECIAL_TAGS).join("|"), v => SPECIAL_TAGS[v] ? SPECIAL_TAGS[v] : v);
return SPECIAL_TAGS[v] ? SPECIAL_TAGS[v] : v;
});
}; };
// html decode // html decode
export const htmlDecode = function (text) { 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) { switch (v) {
case "&amp;": case "&amp;":
return "&"; return "&";
@ -453,7 +444,7 @@ export const htmlDecode = function (text) {
export const cjkEncodeDO = function (o) { export const cjkEncodeDO = function (o) {
if (isPlainObject(o)) { if (isPlainObject(o)) {
const result = {}; const result = {};
each(o, function (v, k) { each(o, (v, k) => {
if (!(typeof v === "string")) { if (!(typeof v === "string")) {
v = jsonEncode(v); v = jsonEncode(v);
} }
@ -461,8 +452,10 @@ export const cjkEncodeDO = function (o) {
k = cjkEncode(k); k = cjkEncode(k);
result[k] = cjkEncode(v); result[k] = cjkEncode(v);
}); });
return result; return result;
} }
return o; return o;
}; };
@ -485,18 +478,20 @@ export const jsonEncode = function (o) {
const encodeString = function (s) { const encodeString = function (s) {
if (/["\\\x00-\x1f]/.test(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]; let c = m[b];
if (c) { if (c) {
return c; return c;
} }
c = b.charCodeAt(); c = b.charCodeAt();
return "\\u00" +
Math.floor(c / 16).toString(16) + return `\\u00${
(c % 16).toString(16); Math.floor(c / 16).toString(16)
}) + "\""; }${(c % 16).toString(16)}`;
} })}"`;
return "\"" + s + "\""; }
return `"${s}"`;
}; };
const encodeArray = function (o) { const encodeArray = function (o) {
@ -517,6 +512,7 @@ export const jsonEncode = function (o) {
} }
} }
a.push("]"); a.push("]");
return a.join(""); return a.join("");
}; };
@ -560,12 +556,11 @@ export const jsonEncode = function (o) {
} }
} }
a.push("}"); a.push("}");
return a.join(""); return a.join("");
}; };
export const jsonDecode = function (text) { export const jsonDecode = function (text) {
let jo; let jo;
try { try {
jo = JSON.parse(text); jo = JSON.parse(text);
@ -578,7 +573,7 @@ export const jsonDecode = function (text) {
* 比如var str = "{'a':'b'}",这种形式的字符串转换为JSON就会抛异常 * 比如var str = "{'a':'b'}",这种形式的字符串转换为JSON就会抛异常
*/ */
try { try {
jo = new Function("return " + text)() || {}; jo = new Function(`return ${text}`)() || {};
} catch (e) { } catch (e) {
// do nothing // do nothing
} }
@ -594,6 +589,7 @@ export const jsonDecode = function (text) {
if (!json || typeof json !== "string") { if (!json || typeof json !== "string") {
return false; return false;
} }
return json.indexOf("__time__") !== -1; return json.indexOf("__time__") !== -1;
} }
@ -612,7 +608,7 @@ export const jsonDecode = function (text) {
} }
return o; 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 * BI.getEncodeURL("design/{tableName}/{fieldName}",{tableName: "A", fieldName: "a"}) // design/A/a
*/ */
export const getEncodeURL = function (urlTemplate, param) { export const getEncodeURL = function (urlTemplate, param) {
return replaceAll(urlTemplate, "\\{(.*?)\\}", function (ori, str) { return replaceAll(urlTemplate, "\\{(.*?)\\}", (ori, str) => encodeURIComponent(isObject(param) ? param[str] : param));
return encodeURIComponent(isObject(param) ? param[str] : param);
});
}; };
export const encodeURIComponent = function (url) { export const encodeURIComponent = function (url) {
BI.specialCharsMap = BI.specialCharsMap || {};
url = url || ""; url = url || "";
url = replaceAll(url + "", keys(BI.specialCharsMap || []).join("|"), function (str) { url = replaceAll(`${url}`, keys(specialCharsMap || []).join("|"), str => {
switch (str) { switch (str) {
case "\\": case "\\":
return BI.specialCharsMap["\\\\"] || str; return specialCharsMap["\\\\"] || str;
default: default:
return BI.specialCharsMap[str] || str; return specialCharsMap[str] || str;
} }
}); });
return _global.encodeURIComponent(url); return _global.encodeURIComponent(url);
}; };
export const decodeURIComponent = function (url) { export const decodeURIComponent = function (url) {
const reserveSpecialCharsMap = {}; const reserveSpecialCharsMap = {};
each(BI.specialCharsMap, function (initialChar, encodeChar) { each(specialCharsMap, (initialChar, encodeChar) => {
reserveSpecialCharsMap[encodeChar] = initialChar === "\\\\" ? "\\" : initialChar; reserveSpecialCharsMap[encodeChar] = initialChar === "\\\\" ? "\\" : initialChar;
}); });
url = url || ""; url = url || "";
url = replaceAll(url + "", keys(reserveSpecialCharsMap || []).join("|"), function (str) { url = replaceAll(`${url}`, keys(reserveSpecialCharsMap || []).join("|"), str => reserveSpecialCharsMap[str] || str);
return reserveSpecialCharsMap[str] || str;
});
return _global.decodeURIComponent(url); return _global.decodeURIComponent(url);
}; };
@ -675,8 +668,8 @@ export const contentFormat = function (cv, fmt) {
// 毫秒数类型 // 毫秒数类型
cv = new Date(cv); cv = new Date(cv);
} else { } else {
//字符串类型转化为date类型 // 字符串类型转化为date类型
cv = new Date(Date.parse(("" + cv).replace(/-|\./g, "/"))); cv = new Date(Date.parse((`${cv}`).replace(/-|\./g, "/")));
} }
} }
if (!isInvalidDate(cv) && !isNull(cv)) { if (!isInvalidDate(cv) && !isNull(cv)) {
@ -692,6 +685,7 @@ export const contentFormat = function (cv, fmt) {
} }
// ¤ - 货币格式 // ¤ - 货币格式
text = text.replace(/¤/g, "¥"); text = text.replace(/¤/g, "¥");
return text; return text;
}; };
@ -704,36 +698,36 @@ export const parseFmt = function (fmt) {
if (!fmt) { if (!fmt) {
return ""; return "";
} }
//日期 // 日期
fmt = String(fmt) fmt = String(fmt)
//年 //
.replace(/y{4,}/g, "%Y")//yyyy的时候替换为Y .replace(/y{4,}/g, "%Y")// yyyy的时候替换为Y
.replace(/y{2}/g, "%y")//yy的时候替换为y .replace(/y{2}/g, "%y")// yy的时候替换为y
//月 //
.replace(/M{4,}/g, "%b")//MMMM的时候替换为b,八 .replace(/M{4,}/g, "%b")// MMMM的时候替换为b,八
.replace(/M{3}/g, "%B")//MMM的时候替换为M,八月 .replace(/M{3}/g, "%B")// MMM的时候替换为M,八月
.replace(/M{2}/g, "%X")//MM的时候替换为X,08 .replace(/M{2}/g, "%X")// MM的时候替换为X,08
.replace(/M{1}/g, "%x")//M的时候替换为x,8 .replace(/M{1}/g, "%x")// M的时候替换为x,8
.replace(/a{1}/g, "%p"); .replace(/a{1}/g, "%p");
//天 //
if (new RegExp("d{2,}", "g").test(fmt)) { 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 { } 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"); fmt = fmt.replace(/h{2,}/g, "%I");
} else { } else {
fmt = fmt.replace(/h{1}/g, "%I"); 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"); fmt = fmt.replace(/H{2,}/g, "%H");
} else { } else {
fmt = fmt.replace(/H{1}/g, "%H"); 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"); .replace(/s{2,}/g, "%S");
return fmt; return fmt;
@ -753,6 +747,7 @@ export const str2Date = function (str, format) {
return null; return null;
} }
const fmt = parseFmt(format); const fmt = parseFmt(format);
return parseDateTime(str, fmt); return parseDateTime(str, fmt);
}; };
@ -777,8 +772,8 @@ export const date2Str = function (date, format) {
const ch = format.charAt(i); const ch = format.charAt(i);
if (flagch !== ch) { if (flagch !== ch) {
result += compileJFmt({ result += compileJFmt({
char: flagch, "char": flagch,
str: str, str,
len: i - start, len: i - start,
}, date); }, date);
flagch = ch; flagch = ch;
@ -789,22 +784,23 @@ export const date2Str = function (date, format) {
} }
} }
result += compileJFmt({ result += compileJFmt({
char: flagch, "char": flagch,
str: str, str,
len: len - start, len: len - start,
}, date); }, date);
} }
return result; return result;
function compileJFmt(jfmt, date) { 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) { switch (ch) {
case "E": // 星期 case "E": // 星期
str = getFullDayName(date.getDay()); str = getFullDayName(date.getDay());
break; break;
case "y": // 年 case "y": // 年
if (len <= 3) { if (len <= 3) {
str = (date.getFullYear() + "").slice(2, 4); str = (`${date.getFullYear()}`).slice(2, 4);
} else { } else {
str = date.getFullYear(); str = date.getFullYear();
} }
@ -815,12 +811,12 @@ export const date2Str = function (date, format) {
} else if (len < 2) { } else if (len < 2) {
str = date.getMonth() + 1; str = date.getMonth() + 1;
} else { } else {
str = leftPad(date.getMonth() + 1 + "", 2, "0"); str = leftPad(`${date.getMonth() + 1}`, 2, "0");
} }
break; break;
case "d": // 日 case "d": // 日
if (len > 1) { if (len > 1) {
str = leftPad(date.getDate() + "", 2, "0"); str = leftPad(`${date.getDate()}`, 2, "0");
} else { } else {
str = date.getDate(); str = date.getDate();
} }
@ -831,28 +827,28 @@ export const date2Str = function (date, format) {
hour = 12; hour = 12;
} }
if (len > 1) { if (len > 1) {
str = leftPad(hour + "", 2, "0"); str = leftPad(`${hour}`, 2, "0");
} else { } else {
str = hour; str = hour;
} }
break; break;
case "H": // 时(24) case "H": // 时(24)
if (len > 1) { if (len > 1) {
str = leftPad(date.getHours() + "", 2, "0"); str = leftPad(`${date.getHours()}`, 2, "0");
} else { } else {
str = date.getHours(); str = date.getHours();
} }
break; break;
case "m": case "m":
if (len > 1) { if (len > 1) {
str = leftPad(date.getMinutes() + "", 2, "0"); str = leftPad(`${date.getMinutes()}`, 2, "0");
} else { } else {
str = date.getMinutes(); str = date.getMinutes();
} }
break; break;
case "s": case "s":
if (len > 1) { if (len > 1) {
str = leftPad(date.getSeconds() + "", 2, "0"); str = leftPad(`${date.getSeconds()}`, 2, "0");
} else { } else {
str = date.getSeconds(); str = date.getSeconds();
} }
@ -867,6 +863,7 @@ export const date2Str = function (date, format) {
str = jfmt.str; str = jfmt.str;
break; break;
} }
return str; return str;
} }
}; };
@ -878,10 +875,11 @@ export const object2Number = function (value) {
if (typeof value === "number") { if (typeof value === "number") {
return value; return value;
} }
const str = value + ""; const str = `${value}`;
if (str.indexOf(".") === -1) { if (str.indexOf(".") === -1) {
return parseInt(str); return parseInt(str);
} }
return parseFloat(str); return parseFloat(str);
}; };
@ -894,7 +892,7 @@ export const object2Date = function (obj) {
} else if (typeof obj === "number") { } else if (typeof obj === "number") {
return new Date(obj); return new Date(obj);
} }
let str = obj + ""; let str = `${obj}`;
str = str.replace(/-/g, "/"); str = str.replace(/-/g, "/");
const dt = new Date(str); const dt = new Date(str);
if (!isInvalidDate(dt)) { if (!isInvalidDate(dt)) {
@ -902,7 +900,6 @@ export const object2Date = function (obj) {
} }
return new Date(); return new Date();
}; };
export const object2Time = function (obj) { export const object2Time = function (obj) {
@ -912,14 +909,14 @@ export const object2Time = function (obj) {
if (obj instanceof Date) { if (obj instanceof Date) {
return obj; return obj;
} }
let str = obj + ""; let str = `${obj}`;
str = str.replace(/-/g, "/"); str = str.replace(/-/g, "/");
let dt = new Date(str); let dt = new Date(str);
if (!isInvalidDate(dt)) { if (!isInvalidDate(dt)) {
return dt; return dt;
} }
if (str.indexOf("/") === -1 && str.indexOf(":") !== -1) { if (str.indexOf("/") === -1 && str.indexOf(":") !== -1) {
dt = new Date("1970/01/01 " + str); dt = new Date(`1970/01/01 ${str}`);
if (!isInvalidDate(dt)) { if (!isInvalidDate(dt)) {
return dt; return dt;
} }
@ -928,6 +925,6 @@ export const object2Time = function (obj) {
if (!isInvalidDate(dt)) { if (!isInvalidDate(dt)) {
return 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 { i18nText } from "../utils";
import { StartOfWeek } from "../constant"; import { StartOfWeek } from "../constant";
import { isKhtml } from "../platform/web"; import { isKhtml } from "../platform/web";
import { _global } from "../0.foundation";
const SECOND = 1000; const SECOND = 1000;
const MINUTE = 60 * SECOND; 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 { ResizeController } from "./controller/controller.resizer";
export { TooltipsController } from "./controller/controller.tooltips"; export { TooltipsController } from "./controller/controller.tooltips";
export * from "./decorator";
export * from "./2.base"; export * from "./2.base";
export * from "./3.ob"; export * from "./3.ob";
export * from "./4.widget"; export * from "./4.widget";
export * from "./5.inject"; export * from "./5.inject";
export * from "./6.plugin"; export * from "./6.plugin";
export * from "./system"; export * from "./system";
@ -32,3 +32,6 @@ export * from "./logic";
export * from "./wrapper"; export * from "./wrapper";
export * from "./platform/web"; export * from "./platform/web";
export * from "./utils"; 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 { extend, isNotNull } from "../2.base";
import { OB } from "../3.ob"; import { OB } from "../3.ob";
import { _global } from "../0.foundation";
export class StyleLoaderManager extends OB { export class StyleLoaderManager extends OB {
_defaultConfig() { _defaultConfig() {

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

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

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

@ -1,3 +1,7 @@
import jQuery from "jquery"; 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 { toUpperCase, remove, camelize, isKey, isNull, isNotEmptyString, map, hyphenate } from "../../../2.base";
import { makeFirstPY } from "../../../utils"; import { makeFirstPY } from "../../../utils";
import { createWidget } from "../../../5.inject"; import { createWidget } from "../../../5.inject";
import { _global } from "../../../0.foundation";
BI.jQuery.fn.extend({ BI.jQuery.fn.extend({

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

@ -1,3 +1,5 @@
import { _global } from "../../../0.foundation";
/* eslint-disable */ /* eslint-disable */
/* ! /* !
* jQuery Mousewheel 3.1.13 * 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. * 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. * CryptoJS namespace.
*/ */

2
src/core/structure/prefixIntervalTree.js

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

72
src/core/system.js

@ -3,7 +3,8 @@
* @version 2.0 * @version 2.0
* Created by windy on 2021/6/30 * 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 { OB } from "./3.ob";
import { Providers } from "./5.inject"; import { Providers } from "./5.inject";
import { provider } from "./decorator"; import { provider } from "./decorator";
@ -68,6 +69,39 @@ const sizeMap = {
L: 24, 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() @provider()
export class SystemProvider { export class SystemProvider {
static xtype = "bi.provider.system"; static xtype = "bi.provider.system";
@ -106,39 +140,7 @@ export class SystemProvider {
}; };
$get() { $get() {
return inherit(OB, { return SystemProviderOB;
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);
},
});
} }
} }
@ -146,7 +148,7 @@ export const SIZE_CONSANTS = {};
// 不再增加线型的配置了,之后不维护前置版本直接删掉,都用实线连接线 // 不再增加线型的配置了,之后不维护前置版本直接删掉,都用实线连接线
export const STYLE_CONSTANTS = {}; export const STYLE_CONSTANTS = {};
BI.prepares.push(() => { prepares.push(() => {
extend(SIZE_CONSANTS, Providers.getProvider("bi.provider.system").getSize()); extend(SIZE_CONSANTS, Providers.getProvider("bi.provider.system").getSize());
STYLE_CONSTANTS.LINK_LINE_TYPE = SIZE_CONSANTS.LIST_ITEM_HEIGHT === 24 ? "dashed" : "solid"; 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 { EventListener } from "./eventlistener";
import { bind } from "../../2.base"; import { bind } from "../../2.base";
import { _global } from "../../0.foundation";
const cancelAnimationFrame = const cancelAnimationFrame =
_global.cancelAnimationFrame || _global.cancelAnimationFrame ||

1
src/core/utils/events/wheelhandler.js

@ -1,4 +1,5 @@
import { bind } from "../../2.base"; import { bind } from "../../2.base";
import { _global } from "../../0.foundation";
const PIXEL_STEP = 10; const PIXEL_STEP = 10;
const LINE_HEIGHT = 40; 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